Let's use AI to Earn!
TypeScript auto-publishdouyindouyin-apielectron-appelectron-reactkuaishoukwaipublishedshipinhaotoolxiaohongshu
fix: the published requests for modifications and ESLint fixes (#189)
布莱恩·奥夫托·杰森张a679028b5819
diff --git a/.gitignore b/.gitignoreindex 40b52f02..5dfe9973 100644--- a/.gitignore+++ b/.gitignore@@ -43,4 +43,5 @@ public/bin/*!public/bin/webkit!public/bin/*.md-sh/*\ No newline at end of file+sh/*+project/web/.cursor/diff --git a/project/web/@types/i18next.d.ts b/project/web/@types/i18next.d.tsindex 4ae27cf1..5f225356 100644--- a/project/web/@types/i18next.d.ts+++ b/project/web/@types/i18next.d.ts@@ -1,15 +1,15 @@-import "i18next";-import Resources from "./resources";+import type Resources from './resources'+import 'i18next'-declare module "i18next" {+declare module 'i18next' {interface CustomTypeOptions {- defaultNS: "translation";- resources: Resources;+ defaultNS: 'translation'+ resources: Resources}namespace JSX {interface IntrinsicElements {- "chatlio-widget": any;+ 'chatlio-widget': any}}}diff --git a/project/web/@types/resources.d.ts b/project/web/@types/resources.d.tsindex 4b033dea..113a4818 100644--- a/project/web/@types/resources.d.ts+++ b/project/web/@types/resources.d.ts@@ -1,2769 +1,2769 @@interface Resources {- "account": {- "title": "账户",- "describe": "账户页面",- "today": "今天",- "defaultSpace": "defaultSpace",- "addPost": "添加帖子",- "calendarMode": "日历模式",- "listModeTab": "列表模式",- "newWork": "新建作品",- "allPlatforms": "所有平台",- "accountManager": "账号管理器",- "addAccount": "添加频道",- "mcpManager": "MCP 管理器",- "online": "在线",- "offline": "离线",- "checkLoginStatus": "登录状态检测",- "checkAllLoginStatus": "一键检测登录状态",- "nickname": "昵称",- "fansCount": "粉丝数",- "platform": "平台",- "loginStatus": "登录状态",- "accountStatus": "账号状态",- "normal": "正常",- "disabled": "禁用",- "unknownPlatform": "未知平台",- "unknownAccount": "未知账户",- "addAccountModal": {- "title": "账号添加",- "subtitle": "选择平台添加账号",- "currentSpace": "当前空间",- "pleaseChooseSpaceFirst": "请先选择空间",- "addTo": "添加到:"- },- "facebookPages": {- "title": "选择Facebook页面",- "selectAll": "全选",- "cancel": "取消",- "confirm": "确认选择",- "loading": "加载中...",- "noPages": "暂无可用页面",- "fetchError": "获取页面列表失败",- "submitError": "页面选择失败",- "submitSuccess": "页面选择成功",- "selectAtLeastOne": "请至少选择一个页面",- "noPagesMessage": "您还没有创建任何Facebook页面",- "createPageTip": "点击上方链接创建页面,然后点击刷新按钮",- "createPageLink": "创建Facebook页面",- "refresh": "刷新"- },- "listMode": {- "title": "发布计划列表",- "recordCount": "共 {{count}} 条发布计划",- "newWork": "新建作品",- "noRecords": "暂无发布计划",- "channels": "频道筛选",- "queue": "我的发布",- "sent": "发布历史",- "createdDaysAgo": "您于 {{days}} 天前创建",- "viewPost": "查看帖子",- "noSentPosts": "暂无已发布的帖子",- "selectAccountFirst": "请先选择一个账号",- "searchChannels": "搜索频道",- "selectAll": "全选",- "noChannelsFound": "未找到匹配的频道",- "selectChannel": "选择频道"- },- "chooseSpace": "选择空间",- "pleaseChooseSpace": "请选择空间",- "accountAddedToSpace": "账号已添加到空间",- "noNewAccountDetected": "未检测到新账号,稍后可在账号管理器中手动调整空间",- "ipInfo": {- "loading": "获取IP信息中...",- "error": "IP信息获取失败",- "tooltip": "ASN: {{asn}}\n组织: {{org}}"- },- "ipType": {- "direct": "直连",- "proxy": "代理"- },- "createSpace": {- "title": "新建空间",- "button": "新建空间",- "name": "空间名",- "namePlaceholder": "请输入空间名称",- "cancel": "取消",- "save": "保存",- "success": "新建空间成功",- "failed": "新建空间失败",- "nameRequired": "请输入空间名称"- },- "locationRestriction": {- "cnSpace": "当前空间为中国属地,仅显示国内平台",- "nonCnSpace": "当前空间为非中国属地,国内平台暂不可用"- },- "userManageSidebar": {- "allAccounts": "全部账号",- "spaces": "空间",- "createSpace": "新建空间",- "spaceNamePlaceholder": "请输入空间名称",- "cannotOperateDefault": "不能操作默认列表",- "rename": "重命名",- "delete": "删除",- "confirmDelete": "提示",- "confirmDeleteContent": "请确认是否删除列表:",- "deleteSuccess": "删除成功",- "createSpaceTitle": "新建空间",- "renameSpaceTitle": "重命名空间",- "cancel": "取消",- "save": "保存",- "spaceName": "空间名"- },- "userManageModal": {- "account": "账号",- "platform": "平台",- "space": "所属列表"- },- "deleteAccount": "删除账户",- "messages": {- "ipLocationError": "获取IP地理位置信息失败",- "createSpaceFirst": "请先创建空间",- "deleteSuccess": "删除成功",- "facebookAuthFailed": "Facebook授权失败",- "unsupportedPlatform": "未支持的平台类型",- "accountListRefreshed": "账号列表已刷新",- "refreshAccountListFailed": "刷新账号列表失败",- "authFailed": "授权失败",- "pleaseRetry": "请重试",- "platformNotSupported": "暂不支持 {{platform}} 平台的直接授权",- "sortSuccess": "排序成功",- "sortFailed": "排序失败"- },- "rednote": "小红书",- "kwai": "快手",- "bilibili": "哔哩哔哩",- "wxgzh": "微信公众号",- "douyin": "抖音",- "wxsph": "微信视频号",- "deleteConfirm": {- "title": "删除提示",- "content": "是否删除以下 {{count}} 个账号?",- "cancel": "取消",- "confirm": "确认"- },- "mobileOnlySupport": "移动端支持",- "xhsOfflineTip": "小红书账号已离线,请下载App进行操作",- "reauthConfirm": {- "title": "会话已过期",- "content": "您的 {{platformName}} 账号 \"{{nickname}}\"(位于 {{spaceName}})会话已过期。是否重新登录?",- "loginAgain": "重新登录"- }- },- "cgmaterial": {- "header": {- "title": "AI草稿箱",- "importContent": "导入发布内容",- "createGroup": "新建草稿箱组"- },- "sidebar": {- "noGroups": "暂无草稿箱组",- "noGroupsDesc": "创建您的第一个草稿箱组开始整理素材",- "selectGroup": "请选择草稿箱组",- "selectGroupDesc": "从左侧选择一个草稿箱组来查看其中的素材",- "edit": "编辑",- "delete": "删除",- "deleteConfirm": "删除草稿组",- "deleteConfirmDesc": "确定要删除\"{{name}}\"吗?",- "deleteSuccess": "删除成功",- "deleteFailed": "删除失败",- "updateSuccess": "更新成功",- "updateFailed": "更新失败",- "noDesc": "暂无描述"- },- "content": {- "noMaterials": "暂无草稿素材",- "noMaterialsDesc": "创建您的第一个素材或批量生成草稿",- "createMaterial": "创建素材",- "batchGenerate": "批量生成草稿",- "edit": "编辑",- "generating": "生成中",- "completed": "已生成"- },- "createGroup": {- "title": "新建草稿箱组",- "name": "组名称",- "namePlaceholder": "请输入草稿箱组名称",- "type": "类型",- "typePlaceholder": "请选择草稿类型",- "imageText": "图文草稿",- "video": "视频草稿",- "desc": "描述",- "descPlaceholder": "请输入草稿箱组描述(可选)",- "createSuccess": "创建草稿箱组成功",- "createFailed": "创建草稿箱组失败",- "getGroupsFailed": "获取草稿箱组失败",- "getMaterialsFailed": "获取草稿素材失败"- },- "createMaterial": {- "title": "创建素材",- "selectCoverGroup": "选择封面组(图片组)",- "selectCoverGroupDesc": "选择一个图片组作为封面来源",- "selectVideoGroup": "选择视频组",- "selectVideoGroupDesc": "选择一个视频组作为视频素材来源",- "selectCover": "选择封面(图片,单选)",- "selectVideo": "选择视频素材(单选)",- "reselectCoverGroup": "重新选择封面组",- "reselectVideoGroup": "重新选择视频组",- "coverMustBeImage": "封面必须是图片",- "imageGroupOnly": "图文组不能选择视频素材",- "videoGroupOnly": "视频组只能选择视频素材",- "selectMediaGroup": "请选择媒体组",- "selectCoverAndMaterials": "请完整选择封面和素材",- "selectCoverGroupRequired": "请选择封面组(图片组)",- "selectVideoGroupRequired": "请选择视频组",- "selectCoverRequired": "请选择封面(图片)",- "selectVideoRequired": "请选择视频素材",- "createSuccess": "创建素材成功",- "createFailed": "创建素材失败"- },- "batchGenerate": {- "title": "批量生成草稿",- "model": "大模型",- "modelPlaceholder": "请选择大模型",- "prompt": "提示词",- "promptPlaceholder": "请输入提示词",- "titlePlaceholder": "请输入标题",- "descPlaceholder": "请输入简介",- "coverGroup": "封面组",- "coverGroupPlaceholder": "请选择封面组",- "mediaGroups": "素材组",- "mediaGroupsPlaceholder": "请选择素材组",- "num": "生成数量",- "location": "地理位置",- "preview": "预览",- "startTask": "开始任务",- "cancel": "取消",- "taskStarted": "批量生成任务已启动",- "generateFailed": "批量生成草稿失败",- "previewFailed": "获取预览失败",- "noPreview": "暂无预览内容"- },- "previewModal": {- "title": "生成预览"- },- "import": {- "title": "导入已有发布内容",- "selectAccount": "选择账户",- "publishContent": "{{nickname}} 的发布内容 (选择要导入的内容)",- "loadedCount": "共 {{total}} 条,已加载 {{loaded}} 条",- "loadMore": "加载更多 ({{count}} 条剩余)",- "importSelected": "导入选中内容",- "selectToImport": "请选择要导入的发布内容",- "selectGroupFirst": "请先选择草稿箱组",- "importSuccess": "成功导入 {{count}} 条内容到草稿箱",- "importFailed": "导入失败",- "getAccountsFailed": "获取账户列表失败",- "getPublishListFailed": "获取发布列表失败",- "checkProgress": "导入查询",- "importRecords": "导入记录详情",- "importStatus": "导入状态:",- "successCount": "成功 {{count}} 条",- "failedCount": "失败 {{count}} 条",- "runningCount": "进行中 {{count}} 条",- "pendingCount": "等待中 {{count}} 条",- "noRecords": "暂无导入记录",- "checkStatusFailed": "查询导入状态失败",- "accountId": "账户ID",- "userId": "用户ID",- "uid": "UID",- "publishTime": "发布时间",- "mediaType": "媒体类型",- "image": "图片",- "video": "视频",- "article": "文章",- "desc": "描述",- "interactionData": "互动数据",- "views": "浏览",- "likes": "点赞",- "comments": "评论",- "shares": "分享",- "cover": "封面",- "close": "关闭",- "noTitle": "无标题",- "success": "成功",- "failed": "失败",- "running": "进行中",- "pending": "等待中",- "vipRequired": "VIP专属功能",- "vipRequiredDesc": "导入发布内容功能仅限VIP会员使用,是否立即开通VIP会员?",- "upgradeNow": "立即开通",- "cancel": "取消",- "noValidRecords": "没有有效的发布内容可以导入",- "importFailedWithReason": "导入失败: {{reason}}",- "unknownError": "未知错误",- "status": {- "success": "成功",- "failed": "失败",- "running": "进行中",- "pending": "等待中"+ 'account': {+ title: '账户'+ describe: '账户页面'+ today: '今天'+ defaultSpace: 'defaultSpace'+ addPost: '添加帖子'+ calendarMode: '日历模式'+ listModeTab: '列表模式'+ newWork: '新建作品'+ allPlatforms: '所有平台'+ accountManager: '账号管理器'+ addAccount: '添加频道'+ mcpManager: 'MCP 管理器'+ online: '在线'+ offline: '离线'+ checkLoginStatus: '登录状态检测'+ checkAllLoginStatus: '一键检测登录状态'+ nickname: '昵称'+ fansCount: '粉丝数'+ platform: '平台'+ loginStatus: '登录状态'+ accountStatus: '账号状态'+ normal: '正常'+ disabled: '禁用'+ unknownPlatform: '未知平台'+ unknownAccount: '未知账户'+ addAccountModal: {+ title: '账号添加'+ subtitle: '选择平台添加账号'+ currentSpace: '当前空间'+ pleaseChooseSpaceFirst: '请先选择空间'+ addTo: '添加到:'+ }+ facebookPages: {+ title: '选择Facebook页面'+ selectAll: '全选'+ cancel: '取消'+ confirm: '确认选择'+ loading: '加载中...'+ noPages: '暂无可用页面'+ fetchError: '获取页面列表失败'+ submitError: '页面选择失败'+ submitSuccess: '页面选择成功'+ selectAtLeastOne: '请至少选择一个页面'+ noPagesMessage: '您还没有创建任何Facebook页面'+ createPageTip: '点击上方链接创建页面,然后点击刷新按钮'+ createPageLink: '创建Facebook页面'+ refresh: '刷新'+ }+ listMode: {+ title: '发布计划列表'+ recordCount: '共 {{count}} 条发布计划'+ newWork: '新建作品'+ noRecords: '暂无发布计划'+ channels: '频道筛选'+ queue: '我的发布'+ sent: '发布历史'+ createdDaysAgo: '您于 {{days}} 天前创建'+ viewPost: '查看帖子'+ noSentPosts: '暂无已发布的帖子'+ selectAccountFirst: '请先选择一个账号'+ searchChannels: '搜索频道'+ selectAll: '全选'+ noChannelsFound: '未找到匹配的频道'+ selectChannel: '选择频道'+ }+ chooseSpace: '选择空间'+ pleaseChooseSpace: '请选择空间'+ accountAddedToSpace: '账号已添加到空间'+ noNewAccountDetected: '未检测到新账号,稍后可在账号管理器中手动调整空间'+ ipInfo: {+ loading: '获取IP信息中...'+ error: 'IP信息获取失败'+ tooltip: 'ASN: {{asn}}\n组织: {{org}}'+ }+ ipType: {+ direct: '直连'+ proxy: '代理'+ }+ createSpace: {+ title: '新建空间'+ button: '新建空间'+ name: '空间名'+ namePlaceholder: '请输入空间名称'+ cancel: '取消'+ save: '保存'+ success: '新建空间成功'+ failed: '新建空间失败'+ nameRequired: '请输入空间名称'+ }+ locationRestriction: {+ cnSpace: '当前空间为中国属地,仅显示国内平台'+ nonCnSpace: '当前空间为非中国属地,国内平台暂不可用'+ }+ userManageSidebar: {+ allAccounts: '全部账号'+ spaces: '空间'+ createSpace: '新建空间'+ spaceNamePlaceholder: '请输入空间名称'+ cannotOperateDefault: '不能操作默认列表'+ rename: '重命名'+ delete: '删除'+ confirmDelete: '提示'+ confirmDeleteContent: '请确认是否删除列表:'+ deleteSuccess: '删除成功'+ createSpaceTitle: '新建空间'+ renameSpaceTitle: '重命名空间'+ cancel: '取消'+ save: '保存'+ spaceName: '空间名'+ }+ userManageModal: {+ account: '账号'+ platform: '平台'+ space: '所属列表'+ }+ deleteAccount: '删除账户'+ messages: {+ ipLocationError: '获取IP地理位置信息失败'+ createSpaceFirst: '请先创建空间'+ deleteSuccess: '删除成功'+ facebookAuthFailed: 'Facebook授权失败'+ unsupportedPlatform: '未支持的平台类型'+ accountListRefreshed: '账号列表已刷新'+ refreshAccountListFailed: '刷新账号列表失败'+ authFailed: '授权失败'+ pleaseRetry: '请重试'+ platformNotSupported: '暂不支持 {{platform}} 平台的直接授权'+ sortSuccess: '排序成功'+ sortFailed: '排序失败'+ }+ rednote: '小红书'+ kwai: '快手'+ bilibili: '哔哩哔哩'+ wxgzh: '微信公众号'+ douyin: '抖音'+ wxsph: '微信视频号'+ deleteConfirm: {+ title: '删除提示'+ content: '是否删除以下 {{count}} 个账号?'+ cancel: '取消'+ confirm: '确认'+ }+ mobileOnlySupport: '移动端支持'+ xhsOfflineTip: '小红书账号已离线,请下载App进行操作'+ reauthConfirm: {+ title: '会话已过期'+ content: '您的 {{platformName}} 账号 "{{nickname}}"(位于 {{spaceName}})会话已过期。是否重新登录?'+ loginAgain: '重新登录'+ }+ }+ 'cgmaterial': {+ header: {+ title: 'AI草稿箱'+ importContent: '导入发布内容'+ createGroup: '新建草稿箱组'+ }+ sidebar: {+ noGroups: '暂无草稿箱组'+ noGroupsDesc: '创建您的第一个草稿箱组开始整理素材'+ selectGroup: '请选择草稿箱组'+ selectGroupDesc: '从左侧选择一个草稿箱组来查看其中的素材'+ edit: '编辑'+ delete: '删除'+ deleteConfirm: '删除草稿组'+ deleteConfirmDesc: '确定要删除"{{name}}"吗?'+ deleteSuccess: '删除成功'+ deleteFailed: '删除失败'+ updateSuccess: '更新成功'+ updateFailed: '更新失败'+ noDesc: '暂无描述'+ }+ content: {+ noMaterials: '暂无草稿素材'+ noMaterialsDesc: '创建您的第一个素材或批量生成草稿'+ createMaterial: '创建素材'+ batchGenerate: '批量生成草稿'+ edit: '编辑'+ generating: '生成中'+ completed: '已生成'+ }+ createGroup: {+ title: '新建草稿箱组'+ name: '组名称'+ namePlaceholder: '请输入草稿箱组名称'+ type: '类型'+ typePlaceholder: '请选择草稿类型'+ imageText: '图文草稿'+ video: '视频草稿'+ desc: '描述'+ descPlaceholder: '请输入草稿箱组描述(可选)'+ createSuccess: '创建草稿箱组成功'+ createFailed: '创建草稿箱组失败'+ getGroupsFailed: '获取草稿箱组失败'+ getMaterialsFailed: '获取草稿素材失败'+ }+ createMaterial: {+ title: '创建素材'+ selectCoverGroup: '选择封面组(图片组)'+ selectCoverGroupDesc: '选择一个图片组作为封面来源'+ selectVideoGroup: '选择视频组'+ selectVideoGroupDesc: '选择一个视频组作为视频素材来源'+ selectCover: '选择封面(图片,单选)'+ selectVideo: '选择视频素材(单选)'+ reselectCoverGroup: '重新选择封面组'+ reselectVideoGroup: '重新选择视频组'+ coverMustBeImage: '封面必须是图片'+ imageGroupOnly: '图文组不能选择视频素材'+ videoGroupOnly: '视频组只能选择视频素材'+ selectMediaGroup: '请选择媒体组'+ selectCoverAndMaterials: '请完整选择封面和素材'+ selectCoverGroupRequired: '请选择封面组(图片组)'+ selectVideoGroupRequired: '请选择视频组'+ selectCoverRequired: '请选择封面(图片)'+ selectVideoRequired: '请选择视频素材'+ createSuccess: '创建素材成功'+ createFailed: '创建素材失败'+ }+ batchGenerate: {+ title: '批量生成草稿'+ model: '大模型'+ modelPlaceholder: '请选择大模型'+ prompt: '提示词'+ promptPlaceholder: '请输入提示词'+ titlePlaceholder: '请输入标题'+ descPlaceholder: '请输入简介'+ coverGroup: '封面组'+ coverGroupPlaceholder: '请选择封面组'+ mediaGroups: '素材组'+ mediaGroupsPlaceholder: '请选择素材组'+ num: '生成数量'+ location: '地理位置'+ preview: '预览'+ startTask: '开始任务'+ cancel: '取消'+ taskStarted: '批量生成任务已启动'+ generateFailed: '批量生成草稿失败'+ previewFailed: '获取预览失败'+ noPreview: '暂无预览内容'+ }+ previewModal: {+ title: '生成预览'+ }+ import: {+ title: '导入已有发布内容'+ selectAccount: '选择账户'+ publishContent: '{{nickname}} 的发布内容 (选择要导入的内容)'+ loadedCount: '共 {{total}} 条,已加载 {{loaded}} 条'+ loadMore: '加载更多 ({{count}} 条剩余)'+ importSelected: '导入选中内容'+ selectToImport: '请选择要导入的发布内容'+ selectGroupFirst: '请先选择草稿箱组'+ importSuccess: '成功导入 {{count}} 条内容到草稿箱'+ importFailed: '导入失败'+ getAccountsFailed: '获取账户列表失败'+ getPublishListFailed: '获取发布列表失败'+ checkProgress: '导入查询'+ importRecords: '导入记录详情'+ importStatus: '导入状态:'+ successCount: '成功 {{count}} 条'+ failedCount: '失败 {{count}} 条'+ runningCount: '进行中 {{count}} 条'+ pendingCount: '等待中 {{count}} 条'+ noRecords: '暂无导入记录'+ checkStatusFailed: '查询导入状态失败'+ accountId: '账户ID'+ userId: '用户ID'+ uid: 'UID'+ publishTime: '发布时间'+ mediaType: '媒体类型'+ image: '图片'+ video: '视频'+ article: '文章'+ desc: '描述'+ interactionData: '互动数据'+ views: '浏览'+ likes: '点赞'+ comments: '评论'+ shares: '分享'+ cover: '封面'+ close: '关闭'+ noTitle: '无标题'+ success: '成功'+ failed: '失败'+ running: '进行中'+ pending: '等待中'+ vipRequired: 'VIP专属功能'+ vipRequiredDesc: '导入发布内容功能仅限VIP会员使用,是否立即开通VIP会员?'+ upgradeNow: '立即开通'+ cancel: '取消'+ noValidRecords: '没有有效的发布内容可以导入'+ importFailedWithReason: '导入失败: {{reason}}'+ unknownError: '未知错误'+ status: {+ success: '成功'+ failed: '失败'+ running: '进行中'+ pending: '等待中'}- },- "detail": {- "title": "素材详情",- "titleLabel": "标题:",- "descLabel": "简介:",- "typeLabel": "类型:",- "coverLabel": "封面:",- "materialsLabel": "素材内容:",- "statusLabel": "状态:",- "noMaterials": "暂无素材内容",- "materialImageAlt": "素材图片"- },- "materialType": {- "imageText": "图文",- "video": "视频"- },- "materialStatus": {- "generating": "生成中",- "completed": "已生成"- },- "editGroup": {- "title": "编辑草稿箱组",- "namePlaceholder": "请输入新组名",- "enterName": "请输入新组名"- },- "editMaterial": {- "title": "编辑素材",- "updateSuccess": "更新素材成功",- "updateFailed": "更新素材失败",- "selectMediaGroup": "选择媒体组",- "selectCover": "选择封面(单选)",- "selectMaterials": "选择素材(多选)"- },- "fields": {- "title": "标题",- "description": "简介",- "location": "地理位置"- },- "mediaGroupType": {- "img": "图片组",- "video": "视频组",- "mixed": "混合组"- },- "selectCover": "选择封面(单选)",- "selectMaterials": "选择素材(多选)",- "validation": {- "enterTitle": "请输入标题"- },- "title": "标题",- "description": "简介",- "location": "地理位置",- "mediaCount": "个资源",- "pleaseCompleteForm": "请完善表单信息"- },- "common": {- "profile": "个人中心",- "logout": "退出登录",- "unknownUser": "未知用户",- "docs": "帮助文档",- "login": "登录",- "support": "支持",- "notifications": "消息通知",- "noNotifications": "暂无消息",- "markAllAsRead": "全部标记为已读",- "markAsRead": "标记为已读",- "unreadCount": "未读消息",- "viewAll": "查看全部",- "actions": {- "cancel": "取消",- "confirm": "确认",- "selectAll": "全选",- "loading": "加载中...",- "noData": "暂无数据",- "noImage": "暂无图片",- "noDescription": "暂无描述",- "noContent": "暂无内容"- },- "notificationTypes": {- "system": "系统通知",- "user": "用户通知",- "material": "素材通知",- "other": "其他通知"- },- "header": {- "messages": "消息通知",- "income": "收入记录",- "wallet": "我的钱包",- "materialLibrary": "素材库",- "draftBox": "草稿箱"- },- "tasks": "任务中心",- "signIn": {- "title": "每日签到得积分",- "myPoints": "我的积分",- "signIn": "签到",- "today": "今天",- "rules": "签到规则",- "rules1": "连续签到 1-7天, 每天1积分",- "rules2": "连续签到 8-21天, 每天2积分",- "rules3": "连续签到 22天以上, 每天3积分",- "signedIn": "已签到",- "notSignedIn": "未签到",- "signInSuccess": "签到成功",- "signInFailed": "签到失败",- "alreadySignedIn": "今日已签到",- "consecutiveDays": "连续签到天数",- "totalPoints": "总积分"- },- "downloadApp": {- "title": "下载{{appName}}",- "operationInApp": "请在{{appName}}中操作添加",- "description": "为了更好的用户体验和功能完整性,该操作需要在 {{appName}} 中完成账号添加。请下载并安装 {{appName}} 后继续操作。",- "operationDescription": "请在Aitoearn App中操作{{platform}}频道账号<br/>为了更好的用户体验和完整性,请下载并安装Aitoearn App后继续操作。",- "scanQrCode": "扫描二维码下载",- "downloadLink": "下载链接:",- "copy": "复制",- "copySuccess": "复制成功",- "copyFailed": "复制失败,请手动复制",- "copied": "已复制",- "close": "关闭",- "downloadNow": "立即下载",- "tip": "💡 提示:安装完成后,请在App中登录您的账号,然后重新尝试相关操作"- },- "websit": {- "termsOfService": {- "title": "用户协议",- "lastUpdated": "最后更新时间",- "content": {- "introduction": "欢迎使用我们的服务。在使用本服务前,请仔细阅读以下条款和条件。",- "acceptance": "1. 接受条款",- "acceptanceContent": "通过访问和使用本服务,您同意受本用户协议的约束。如果您不同意这些条款,请不要使用本服务。",- "serviceDescription": "2. 服务说明",- "serviceDescriptionContent": "本服务是一个AI内容创作平台,帮助用户生成和管理多媒体内容。",- "userResponsibilities": "3. 用户责任",- "userResponsibilitiesContent": "用户应确保其使用本服务的行为符合当地法律法规,不得用于非法目的。",- "privacy": "4. 隐私保护",- "privacyContent": "我们重视您的隐私,详细信息请参阅我们的隐私政策。",- "termination": "5. 服务终止",- "terminationContent": "我们保留在任何时候终止或暂停服务的权利。",- "contact": "6. 联系我们",- "contactContent": "如有任何问题,请通过邮件联系我们:[email protected]"+ }+ detail: {+ title: '素材详情'+ titleLabel: '标题:'+ descLabel: '简介:'+ typeLabel: '类型:'+ coverLabel: '封面:'+ materialsLabel: '素材内容:'+ statusLabel: '状态:'+ noMaterials: '暂无素材内容'+ materialImageAlt: '素材图片'+ }+ materialType: {+ imageText: '图文'+ video: '视频'+ }+ materialStatus: {+ generating: '生成中'+ completed: '已生成'+ }+ editGroup: {+ title: '编辑草稿箱组'+ namePlaceholder: '请输入新组名'+ enterName: '请输入新组名'+ }+ editMaterial: {+ title: '编辑素材'+ updateSuccess: '更新素材成功'+ updateFailed: '更新素材失败'+ selectMediaGroup: '选择媒体组'+ selectCover: '选择封面(单选)'+ selectMaterials: '选择素材(多选)'+ }+ fields: {+ title: '标题'+ description: '简介'+ location: '地理位置'+ }+ mediaGroupType: {+ img: '图片组'+ video: '视频组'+ mixed: '混合组'+ }+ selectCover: '选择封面(单选)'+ selectMaterials: '选择素材(多选)'+ validation: {+ enterTitle: '请输入标题'+ }+ title: '标题'+ description: '简介'+ location: '地理位置'+ mediaCount: '个资源'+ pleaseCompleteForm: '请完善表单信息'+ }+ 'common': {+ profile: '个人中心'+ logout: '退出登录'+ unknownUser: '未知用户'+ docs: '帮助文档'+ login: '登录'+ support: '支持'+ notifications: '消息通知'+ noNotifications: '暂无消息'+ markAllAsRead: '全部标记为已读'+ markAsRead: '标记为已读'+ unreadCount: '未读消息'+ viewAll: '查看全部'+ actions: {+ cancel: '取消'+ confirm: '确认'+ selectAll: '全选'+ loading: '加载中...'+ noData: '暂无数据'+ noImage: '暂无图片'+ noDescription: '暂无描述'+ noContent: '暂无内容'+ }+ notificationTypes: {+ system: '系统通知'+ user: '用户通知'+ material: '素材通知'+ other: '其他通知'+ }+ header: {+ messages: '消息通知'+ income: '收入记录'+ wallet: '我的钱包'+ materialLibrary: '素材库'+ draftBox: '草稿箱'+ }+ tasks: '任务中心'+ signIn: {+ title: '每日签到得积分'+ myPoints: '我的积分'+ signIn: '签到'+ today: '今天'+ rules: '签到规则'+ rules1: '连续签到 1-7天, 每天1积分'+ rules2: '连续签到 8-21天, 每天2积分'+ rules3: '连续签到 22天以上, 每天3积分'+ signedIn: '已签到'+ notSignedIn: '未签到'+ signInSuccess: '签到成功'+ signInFailed: '签到失败'+ alreadySignedIn: '今日已签到'+ consecutiveDays: '连续签到天数'+ totalPoints: '总积分'+ }+ downloadApp: {+ title: '下载{{appName}}'+ operationInApp: '请在{{appName}}中操作添加'+ description: '为了更好的用户体验和功能完整性,该操作需要在 {{appName}} 中完成账号添加。请下载并安装 {{appName}} 后继续操作。'+ operationDescription: '请在Aitoearn App中操作{{platform}}频道账号<br/>为了更好的用户体验和完整性,请下载并安装Aitoearn App后继续操作。'+ scanQrCode: '扫描二维码下载'+ downloadLink: '下载链接:'+ copy: '复制'+ copySuccess: '复制成功'+ copyFailed: '复制失败,请手动复制'+ copied: '已复制'+ close: '关闭'+ downloadNow: '立即下载'+ tip: '💡 提示:安装完成后,请在App中登录您的账号,然后重新尝试相关操作'+ }+ websit: {+ termsOfService: {+ title: '用户协议'+ lastUpdated: '最后更新时间'+ content: {+ introduction: '欢迎使用我们的服务。在使用本服务前,请仔细阅读以下条款和条件。'+ acceptance: '1. 接受条款'+ acceptanceContent: '通过访问和使用本服务,您同意受本用户协议的约束。如果您不同意这些条款,请不要使用本服务。'+ serviceDescription: '2. 服务说明'+ serviceDescriptionContent: '本服务是一个AI内容创作平台,帮助用户生成和管理多媒体内容。'+ userResponsibilities: '3. 用户责任'+ userResponsibilitiesContent: '用户应确保其使用本服务的行为符合当地法律法规,不得用于非法目的。'+ privacy: '4. 隐私保护'+ privacyContent: '我们重视您的隐私,详细信息请参阅我们的隐私政策。'+ termination: '5. 服务终止'+ terminationContent: '我们保留在任何时候终止或暂停服务的权利。'+ contact: '6. 联系我们'+ contactContent: '如有任何问题,请通过邮件联系我们:[email protected]'}- },- "privacyPolicy": {- "title": "隐私政策",- "lastUpdated": "最后更新时间",- "content": {- "introduction": "本隐私政策说明我们如何收集、使用和保护您的个人信息。",- "informationCollection": "1. 信息收集",- "informationCollectionContent": "我们收集您主动提供的信息以及您使用服务时自动收集的信息。",- "informationUse": "2. 信息使用",- "informationUseContent": "我们使用收集的信息来提供、维护和改进我们的服务。",- "informationSharing": "3. 信息共享",- "informationSharingContent": "我们不会向第三方出售、交易或转让您的个人信息。",- "dataSecurity": "4. 数据安全",- "dataSecurityContent": "我们采用适当的安全措施来保护您的个人信息。",- "userRights": "5. 用户权利",- "userRightsContent": "您有权访问、更正或删除您的个人信息。",- "contact": "6. 联系我们",- "contactContent": "如有隐私相关问题,请联系我们:[email protected]"+ }+ privacyPolicy: {+ title: '隐私政策'+ lastUpdated: '最后更新时间'+ content: {+ introduction: '本隐私政策说明我们如何收集、使用和保护您的个人信息。'+ informationCollection: '1. 信息收集'+ informationCollectionContent: '我们收集您主动提供的信息以及您使用服务时自动收集的信息。'+ informationUse: '2. 信息使用'+ informationUseContent: '我们使用收集的信息来提供、维护和改进我们的服务。'+ informationSharing: '3. 信息共享'+ informationSharingContent: '我们不会向第三方出售、交易或转让您的个人信息。'+ dataSecurity: '4. 数据安全'+ dataSecurityContent: '我们采用适当的安全措施来保护您的个人信息。'+ userRights: '5. 用户权利'+ userRightsContent: '您有权访问、更正或删除您的个人信息。'+ contact: '6. 联系我们'+ contactContent: '如有隐私相关问题,请联系我们:[email protected]'}- },- "dataDeletion": {- "title": "申请删除数据",- "subtitle": "如果您希望删除您的个人数据,请按照以下步骤操作",- "lastUpdated": "最后更新时间",- "prelaunchNote": "对于预发布用户:",- "prelaunchContent": "我们目前处于预发布阶段,如需删除数据,请直接联系我们的支持团队。",- "standardProcedure": "标准删除流程:",- "steps": [- "登录您的账户并进入设置页面",- "点击「数据管理」选项",- "选择「删除我的数据」",- "确认删除操作并等待处理完成"- ],- "contactInfo": "联系方式:",- "contactEmail": "如需帮助,请发送邮件至:[email protected]",- "processingTime": "处理时间:",- "processingTimeContent": "数据删除请求通常在 7-14 个工作日内处理完成。",- "importantNote": "重要提示:",- "importantNoteContent": "数据删除后无法恢复,请谨慎操作。某些法律要求保留的数据可能无法删除。"+ }+ dataDeletion: {+ title: '申请删除数据'+ subtitle: '如果您希望删除您的个人数据,请按照以下步骤操作'+ lastUpdated: '最后更新时间'+ prelaunchNote: '对于预发布用户:'+ prelaunchContent: '我们目前处于预发布阶段,如需删除数据,请直接联系我们的支持团队。'+ standardProcedure: '标准删除流程:'+ steps: [+ '登录您的账户并进入设置页面',+ '点击「数据管理」选项',+ '选择「删除我的数据」',+ '确认删除操作并等待处理完成',+ ]+ contactInfo: '联系方式:'+ contactEmail: '如需帮助,请发送邮件至:[email protected]'+ processingTime: '处理时间:'+ processingTimeContent: '数据删除请求通常在 7-14 个工作日内处理完成。'+ importantNote: '重要提示:'+ importantNoteContent: '数据删除后无法恢复,请谨慎操作。某些法律要求保留的数据可能无法删除。'}}- },- "dataStatistics": {- "title": "数据统计",- "description": "在这里查看和分析您的数据统计信息。",- "accountData": "账号数据",- "selectSpace": "选择空间",- "inputAccountName": "请输入账号名称",- "noAccount": "暂无账号",- "totalAccount": "累计账号数",- "online": "在线",- "offline": "离线",- "fansCount": "粉丝数",- "growthFansCount": "涨粉数",- "loginFailed": "登陆失败",- "relogin": "重新登录",- "dataDetails": "数据明细",- "timeRange": "时间范围:",- "yesterdayIncrease": "昨日新增",- "readCount": "播放数",- "commentCount": "评论数",- "likeCount": "点赞数",- "collectCount": "收藏数",- "forwardCount": "分享数"- },- "engagement": {- "title": "互动数据",- "columns": {- "postId": "帖子ID",- "platform": "平台",- "title": "标题",- "mediaType": "媒体类型",- "publishTime": "发布时间",- "viewCount": "浏览数",- "likeCount": "点赞数",- "commentCount": "评论数",- "shareCount": "分享数",- "clickCount": "点击数",- "impressionCount": "曝光数",- "favoriteCount": "收藏数",- "permaLink": "外链",- "open": "打开"- },- "placeholders": {- "uid": "请输入账户UID"- },- "actions": {- "search": "查询",- "reset": "重置"- }- },- "home": {- "releaseBanner": {- "tag": "Release v0.8.0",- "text": "通过插件和繁荣的市场构建和扩展AI工作流程。"- },- "header": {- "logo": "Aitoearn",- "nav": {- "home": "首页",- "marketplace": "市场",- "pricing": "价格",- "status": "状态",- "docs": "文档",- "blog": "博客",- "download": "下载"- },- "getStarted": "立即开始"- },- "hero": {- "stars": "105.2k",- "starsText": "stars on",- "github": "GitHub",- "title": "成为最好用的内容营销\nAI Agent",- "subtitle": "从今天起,使用AI轻松管理你的社交媒体。AITOEARN提供从灵感创意、内容制作,内容分发内容互动管理等一站式能力,让AI触手可及。",- "getStarted": "立即开始",- "useMobilePhone": "使用移动设备"- },- "brandBar": {- "title": "支持的社交媒体平台"- },- "buildSection": {- "badge": "功能1",- "title": "Content Publishing — 一键发布 · 多平台触达",- "titleBlue": "从创意灵感到多平台分发,再到数据分析和商业化",- "features": {- "hotTopic": {- "title": "多平台分发",- "description": "支持全球最多主流社交平台(Douyin, Kwai, Wechat, Bilibili, Rednote, Facebook, Instagram, TikTok, LinkedIn, Threads, YouTube, Pinterest, X)。"- },- "international": {- "title": "日历编排",- "description": "像操作日历一样规划内容,实现多平台协同发布。"+ }+ 'dataStatistics': {+ title: '数据统计'+ description: '在这里查看和分析您的数据统计信息。'+ accountData: '账号数据'+ selectSpace: '选择空间'+ inputAccountName: '请输入账号名称'+ noAccount: '暂无账号'+ totalAccount: '累计账号数'+ online: '在线'+ offline: '离线'+ fansCount: '粉丝数'+ growthFansCount: '涨粉数'+ loginFailed: '登陆失败'+ relogin: '重新登录'+ dataDetails: '数据明细'+ timeRange: '时间范围:'+ yesterdayIncrease: '昨日新增'+ readCount: '播放数'+ commentCount: '评论数'+ likeCount: '点赞数'+ collectCount: '收藏数'+ forwardCount: '分享数'+ }+ 'engagement': {+ title: '互动数据'+ columns: {+ postId: '帖子ID'+ platform: '平台'+ title: '标题'+ mediaType: '媒体类型'+ publishTime: '发布时间'+ viewCount: '浏览数'+ likeCount: '点赞数'+ commentCount: '评论数'+ shareCount: '分享数'+ clickCount: '点击数'+ impressionCount: '曝光数'+ favoriteCount: '收藏数'+ permaLink: '外链'+ open: '打开'+ }+ placeholders: {+ uid: '请输入账户UID'+ }+ actions: {+ search: '查询'+ reset: '重置'+ }+ }+ 'home': {+ releaseBanner: {+ tag: 'Release v0.8.0'+ text: '通过插件和繁荣的市场构建和扩展AI工作流程。'+ }+ header: {+ logo: 'Aitoearn'+ nav: {+ home: '首页'+ marketplace: '市场'+ pricing: '价格'+ status: '状态'+ docs: '文档'+ blog: '博客'+ download: '下载'+ }+ getStarted: '立即开始'+ }+ hero: {+ stars: '105.2k'+ starsText: 'stars on'+ github: 'GitHub'+ title: '成为最好用的内容营销\nAI Agent'+ subtitle: '从今天起,使用AI轻松管理你的社交媒体。AITOEARN提供从灵感创意、内容制作,内容分发内容互动管理等一站式能力,让AI触手可及。'+ getStarted: '立即开始'+ useMobilePhone: '使用移动设备'+ }+ brandBar: {+ title: '支持的社交媒体平台'+ }+ buildSection: {+ badge: '功能1'+ title: 'Content Publishing — 一键发布 · 多平台触达'+ titleBlue: '从创意灵感到多平台分发,再到数据分析和商业化'+ features: {+ hotTopic: {+ title: '多平台分发'+ description: '支持全球最多主流社交平台(Douyin, Kwai, Wechat, Bilibili, Rednote, Facebook, Instagram, TikTok, LinkedIn, Threads, YouTube, Pinterest, X)。'}- },- "carouselHint": "使用滚轮切换图片"- },- "hotspotSection": {- "badge": "功能2",- "title": "Content Hotspot — 爆款灵感引擎",- "titleBlue": "爆款案例库与趋势捕捉",- "features": {- "hotTopic": {- "title": "爆款案例库",- "description": "随时查看他人如何打造 10,000+ 点赞的内容。"- },- "international": {- "title": "趋势捕捉",- "description": "快速发现流行趋势,降低创作焦虑。"+ international: {+ title: '日历编排'+ description: '像操作日历一样规划内容,实现多平台协同发布。'}- },- "carouselHint": "使用滚轮切换图片"- },- "searchSection": {- "badge": "功能3",- "title": "Content Search — 品牌与市场洞察",- "titleBlue": "品牌监控与内容搜索",- "features": {- "hotTopic": {- "title": "品牌监控",- "description": "实时追踪品牌相关讨论,第一时间响应。"- },- "international": {- "title": "内容搜索",- "description": "找到目标帖子和话题,高效互动,精准拓展市场。"+ }+ carouselHint: '使用滚轮切换图片'+ }+ hotspotSection: {+ badge: '功能2'+ title: 'Content Hotspot — 爆款灵感引擎'+ titleBlue: '爆款案例库与趋势捕捉'+ features: {+ hotTopic: {+ title: '爆款案例库'+ description: '随时查看他人如何打造 10,000+ 点赞的内容。'}- },- "carouselHint": "使用滚轮切换图片"- },- "commentsSection": {- "badge": "功能4",- "title": "Comments Search — 精准用户挖掘",- "titleBlue": "智能评论搜索与精准转化",- "features": {- "hotTopic": {- "title": "智能评论搜索",- "description": "快速发现\"求链接\"\"怎么购买\"等高转化信号。"- },- "international": {- "title": "精准转化",- "description": "主动回复,提升流量变现效率。"+ international: {+ title: '趋势捕捉'+ description: '快速发现流行趋势,降低创作焦虑。'}- },- "carouselHint": "使用滚轮切换图片"- },- "connectSection": {- "badge": "功能5",- "title": "Content Engagement — 互动与增长引擎",- "titleBlue": "统一后台与主动运营",- "features": {- "creation": {- "title": "统一后台",- "description": "集中管理所有内容,互动零遗漏。"- },- "distribution": {- "title": "主动运营",- "description": "参与热门话题,与潜在用户双向互动。把\"被动内容运营\"变成\"主动流量经营\"。"+ }+ carouselHint: '使用滚轮切换图片'+ }+ searchSection: {+ badge: '功能3'+ title: 'Content Search — 品牌与市场洞察'+ titleBlue: '品牌监控与内容搜索'+ features: {+ hotTopic: {+ title: '品牌监控'+ description: '实时追踪品牌相关讨论,第一时间响应。'}- },- "carouselHint": "使用滚轮切换图片"- },- "upcomingSection": {- "badge": "即将上线",- "title": "AI 驱动的全链路内容增长与变现平台",- "titleBlue": "即将上线功能,敬请期待",- "features": {- "smartImport": {- "title": "智能导入",- "description": "直接导入历史内容,快速编辑、二次分发。例如:小红书创作者可一键同步到 YouTube,让更多用户看到。"- },- "analytics": {- "title": "Content Analytics — 全景化数据视图",- "description": "多平台对比:一个平台不给流量,不代表所有平台不给。全链路监控:追踪内容表现,助力打造下一个百万博主。"- },- "aiCreation": {- "title": "AI Content Creation — 全流程 AI 助手",- "description": "AI 文案生成:自动生成标题、描述,高效产出。AI 评论生成:主动出击,获取流量。图文卡片生成,全流程加速创作。支持主流 AI 视频模型和图片模型。"- },- "marketplace": {- "title": "Content Marketplace — 内容交易与变现",- "description": "创作者变现:在平台直接出售内容,让优质作品快速找到买家。品牌采购:企业可直接购买现成内容,节省时间与成本。让创作变成收益 —— Let's use AI to earn. Let's earn money together!"+ international: {+ title: '内容搜索'+ description: '找到目标帖子和话题,高效互动,精准拓展市场。'}}- },- "downloadSection": {- "title": "随时随地开始创作",- "titleBlue": "移动端也能轻松管理",- "description": "借助 AI ToEarn 移动应用,您的创作不再局限于桌面端。我们还为您提供App移动应用,随时随地释放您的创造力,仅需一部手机即可!",- "qrCodeText": "扫描二维码下载",- "appStore": {- "text": "Download on the",- "store": "App Store"- },- "googlePlay": {- "text": "GET IT ON",- "store": "Google Play"+ carouselHint: '使用滚轮切换图片'+ }+ commentsSection: {+ badge: '功能4'+ title: 'Comments Search — 精准用户挖掘'+ titleBlue: '智能评论搜索与精准转化'+ features: {+ hotTopic: {+ title: '智能评论搜索'+ description: '快速发现"求链接""怎么购买"等高转化信号。'+ }+ international: {+ title: '精准转化'+ description: '主动回复,提升流量变现效率。'+ }}- },- "enterpriseSection": {- "badge": "企业级服务",- "title": "专业的AI自媒体解决方案",- "titleBlue": "助力企业营销成功",- "subtitle": "企业级AI营销转型不仅需要工具,更需要稳固的基础设施。AI ToEarn 提供可靠的平台,将AI内容创作能力分发到多个部门,实现无与伦比的营销效率。"- },- "statsSection": {- "stats": {- "users": {- "number": "50K+",- "label": "用户"- },- "platforms": {- "number": "15+",- "label": "社交平台"- },- "countries": {- "number": "100+",- "label": "国家地区"- },- "content": {- "number": "5M+",- "label": "内容发布"+ carouselHint: '使用滚轮切换图片'+ }+ connectSection: {+ badge: '功能5'+ title: 'Content Engagement — 互动与增长引擎'+ titleBlue: '统一后台与主动运营'+ features: {+ creation: {+ title: '统一后台'+ description: '集中管理所有内容,互动零遗漏。'}- },- "testimonial": {- "quote": "在内容营销竞争激烈的今天,快速验证和创作工具不仅有帮助,更是生存必需品。对于我们这样的营销公司来说,AI ToEarn 在这个AI前沿为我们提供了不可或缺的价值。",- "author": "李明",- "title": "某知名MCN机构 内容运营总监"- },- "caseStudies": {- "timeSaved": {- "title": "预计每年节省创作时间",- "number": "50,000 小时"- },- "aiAssistant": {- "title": "AI营销助手:为500+企业客户提供跨平台内容分发服务"+ distribution: {+ title: '主动运营'+ description: '参与热门话题,与潜在用户双向互动。把"被动内容运营"变成"主动流量经营"。'}}- },- "communitySection": {- "badge": "社区生态",- "title": "加入我们的",- "titleBlue": "活跃创作者社区",- "subtitle": "AI ToEarn 由全球AI内容创作者社区共同推动。加入我们,一起探索AI内容营销的无限边界。",- "buttons": {- "wechat": "微信群组",- "community": "创作者交流群"- },- "wechatPopup": "扫码关注微信公众号",- "communityPopup": "扫码加入社区群",- "stats": {- "downloads": {- "number": "20万+",- "label": "下载量"- },- "members": {- "number": "15K",- "label": "社区成员"- },- "creators": {- "number": "500+",- "label": "活跃创作者"+ carouselHint: '使用滚轮切换图片'+ }+ upcomingSection: {+ badge: '即将上线'+ title: 'AI 驱动的全链路内容增长与变现平台'+ titleBlue: '即将上线功能,敬请期待'+ features: {+ smartImport: {+ title: '智能导入'+ description: '直接导入历史内容,快速编辑、二次分发。例如:小红书创作者可一键同步到 YouTube,让更多用户看到。'}+ analytics: {+ title: 'Content Analytics — 全景化数据视图'+ description: '多平台对比:一个平台不给流量,不代表所有平台不给。全链路监控:追踪内容表现,助力打造下一个百万博主。'+ }+ aiCreation: {+ title: 'AI Content Creation — 全流程 AI 助手'+ description: 'AI 文案生成:自动生成标题、描述,高效产出。AI 评论生成:主动出击,获取流量。图文卡片生成,全流程加速创作。支持主流 AI 视频模型和图片模型。'+ }+ marketplace: {+ title: 'Content Marketplace — 内容交易与变现'+ description: '创作者变现:在平台直接出售内容,让优质作品快速找到买家。品牌采购:企业可直接购买现成内容,节省时间与成本。让创作变成收益 —— Let\'s use AI to earn. Let\'s earn money together!'+ }+ }+ }+ downloadSection: {+ title: '随时随地开始创作'+ titleBlue: '移动端也能轻松管理'+ description: '借助 AI ToEarn 移动应用,您的创作不再局限于桌面端。我们还为您提供App移动应用,随时随地释放您的创造力,仅需一部手机即可!'+ qrCodeText: '扫描二维码下载'+ appStore: {+ text: 'Download on the'+ store: 'App Store'+ }+ googlePlay: {+ text: 'GET IT ON'+ store: 'Google Play'}- },- "footer": {- "resources": {- "title": "资源",- "links": {- "docs": "文档",- "blog": "博客",- "download": "下载",- "education": "教育",- "partner": "合作伙伴",- "support": "服务支持",- "roadmap": "产品线路图"+ }+ enterpriseSection: {+ badge: '企业级服务'+ title: '专业的AI自媒体解决方案'+ titleBlue: '助力企业营销成功'+ subtitle: '企业级AI营销转型不仅需要工具,更需要稳固的基础设施。AI ToEarn 提供可靠的平台,将AI内容创作能力分发到多个部门,实现无与伦比的营销效率。'+ }+ statsSection: {+ stats: {+ users: {+ number: '50K+'+ label: '用户'+ }+ platforms: {+ number: '15+'+ label: '社交平台'+ }+ countries: {+ number: '100+'+ label: '国家地区'+ }+ content: {+ number: '5M+'+ label: '内容发布'+ }+ }+ testimonial: {+ quote: '在内容营销竞争激烈的今天,快速验证和创作工具不仅有帮助,更是生存必需品。对于我们这样的营销公司来说,AI ToEarn 在这个AI前沿为我们提供了不可或缺的价值。'+ author: '李明'+ title: '某知名MCN机构 内容运营总监'+ }+ caseStudies: {+ timeSaved: {+ title: '预计每年节省创作时间'+ number: '50,000 小时'}- },- "company": {- "title": "公司",- "links": {- "talk": "联系我们",- "terms": "服务条款",- "privacy": "隐私政策",- "cookies": "Cookie 设置",- "data": "数据删除引导",- "marketplace": "市场协议",- "brand": "品牌指南"+ aiAssistant: {+ title: 'AI营销助手:为500+企业客户提供跨平台内容分发服务'}- },- "description": "AI ToEarn 自媒体运营平台一站式解决方案,从灵感创意到内容制作,从内容分发到内容互动管理",- "social": {- "github": "GitHub",- "discord": "Discord",- "youtube": "YouTube",- "linkedin": "LinkedIn",- "twitter": "Twitter"- },- "bigText": "Let's Use AI To",- "copyright": "© 2025 AITOEARN, Corp.",- "tagline": "",- "dataDeletion": {- "title": "Data Deletion Instructions",- "prelaunch": "Our application is currently in pre-launch phase and does not store real user data. If you have interacted with our test systems, contact us for data removal.",- "standardTitle": "Standard Procedure (Post-Launch):",- "standardSteps": [- "Log in to your AiToEarn account",- "Navigate to Settings > Privacy",- "Click \"Request Account Deletion\"",- "Confirmation will be sent to your registered email"- ],- "contactTitle": "Contact for Assistance:",- "contactEmail": "Email: [email protected] (Pre-launch inquiries only)"}}- },- "hot-content": {- "all": "全部",- "loading": "加载中...",- "noData": "暂无数据",- "rank": "排名",- "cover": "封面",- "title": "标题",- "author": "作者",- "category": "分类",- "likes": "点赞",- "shares": "分享",- "comments": "评论数",- "collections": "收藏数",- "publishTime": "发布于",- "fans": "粉丝数",- "viewMore": "查看更多",- "timeRange": "时间范围",- "filter": "筛选",- "hotTopics": "热门专题",- "viralTitles": "爆款标题",- "topics": "专题",- "engagement": "互动量",- "rising": "热",- "noHotTopics": "暂无热点数据",- "noViralTitles": "暂无爆款标题数据",- "noTopicData": "暂无专题数据",- "total": "总",- "items": "条",- "video": "视频",- "noImage": "暂无图片",- "platform": "平台",- "hotEvents": "热点事件",- "hotContent": "热点内容",- "noTitle": "暂无标题",- "baseInfo": "基本信息",- "views": "播放数",- "recommend": "推荐数",- "watch": "在看数",- "dailyRank": "日榜",- "updateFrequency": "更新时间",- "statEndTime": "统计数据截止",- "daily": "按日",- "sortRule": "排序规则",- "sortRuleDesc": "统计当日点赞量前500名的作品推荐",- "dataDescription": "数据说明",- "expand": "展开",- "collapse": "收起",- "hotValue": "热度值",- "hotTrend": "热度趋势",- "shortDrama": "短剧",- "cultureTourism": "文旅",- "contentOverseas": "内容出海",- "hot": "热点",- "last3days": "近3天",- "last7days": "近7天",- "last15days": "近15天",- "last30days": "近30天",- "backToAll": "返回全部",- "last90days": "近90天"- },- "imageEditor": {- "Load": "加载本地",- "Download": "下载当前",- "Custom": "自定义",- "Square": "正方形",- "Apply": "应用",- "Cancel": "取消",- "Free": "自由设定",- "Straight": "直线",- "Color": "颜色",- "Range": "粗细",- "Grayscale": "灰度",- "Invert": "旋转",- "Sepia": "深褐色",- "Sepia2": "深褐色2",- "Blur": "模糊",- "Sharpen": "锐化",- "Emboss": "浮雕",- "Remove White": "消除白色",- "Distance": "边距",- "Brightness": "亮度",- "Noise": "降噪",- "Pixelate": "像素化",- "Color Filter": "颜色过滤",- "Threshold": "阈值",- "Tint": "色调",- "Multiply": "复合",- "Flip X": "镜像",- "Flip Y": "翻转",- "Reset": "重置",- "Arrow-1": "箭头1",- "Arrow-2": "箭头2",- "Arrow-3": "箭头3",- "Star-1": "星形1",- "Star-2": "星形2",- "Polygon": "多边形",- "Location": "定位",- "Heart": "心形",- "Bubble": "气泡",- "Custom icon": "自定义图标",- "Load Mask Image": "加载水印",- "Width": "宽",- "Height": "高",- "Lock Aspect Ratio": "保持尺寸比例",- "Rectangle": "矩形",- "Circle": "圆形",- "Triangle": "三角形",- "Fill": "填充",- "Stroke": "画笔",- "Bold": "加粗",- "Italic": "斜体",- "Underline": "下划线",- "Left": "居左",- "Center": "居中",- "Right": "居右",- "Text size": "字体大小",- "Zoom In": "放大",- "Zoom Out": "缩小",- "ZoomIn": "放大",- "ZoomOut": "缩小",- "Hand": "拖动",- "Resize": "尺寸",- "Crop": "裁剪",- "Flip": "翻转",- "Rotate": "旋转",- "Draw": "画笔",- "Shape": "形状",- "Icon": "图标",- "Text": "文字",- "Mask": "水印",- "Filter": "滤镜",- "History": "历史动作",- "Undo": "撤退",- "Redo": "重做",- "Delete": "去除",- "DeleteAll": "全部去除",- "Blend": "混合",- "imageEditing": "图像编辑"- },- "income": {- "title": "我的收入",- "subtitle": "管理您的收入记录和提现申请",- "currentBalance": "当前余额",- "incomeRecords": "收入记录",- "withdrawRecords": "提现记录",- "incomeId": "收入ID",- "amount": "金额",- "type": "类型",- "description": "描述",- "createTime": "创建时间",- "actions": "操作",- "applyWithdraw": "申请提现",- "withdrawId": "提现ID",- "status": "状态",- "updateTime": "更新时间",- "confirmWithdraw": "确认提现申请",- "cancel": "取消",- "confirm": "确认提现",- "withdrawAmount": "提现金额",- "incomeType": "收入类型",- "withdrawWarning": "⚠️ 提现申请提交后,我们将在1-3个工作日内处理您的申请。",- "withdrawWarning2": "请确保您的账户信息正确,提现成功后金额将转入您的指定账户。",- "incomeTypes": {- "task": "任务收入",- "task_back": "任务回退",- "reward_back": "奖励回退",- "task_withdraw": "任务提现"- },- "withdrawStatus": {- "wait": "等待处理",- "success": "提现成功",- "fail": "提现失败",- "task_withdraw": "任务提现"- },- "messages": {- "getIncomeRecordsFailed": "获取收入记录失败",- "getWithdrawRecordsFailed": "获取提现记录失败",- "withdrawSubmitted": "提现申请提交成功",- "withdrawFailed": "提现申请提交失败",- "pleaseLoginFirst": "请先登录",- "noIncomeRecords": "暂无收入记录",- "noWithdrawRecords": "暂无提现记录",- "loading": "加载中...",- "totalRecords": "共 {{total}} 条记录"- },- "myWallet": "我的钱包"- },- "interactive": {- "title": "互动管理",- "messages": {- "pleaseLoginFirst": "请先登录",- "commentSuccess": "评论成功",- "commentFailed": "评论失败,请重试",- "replySuccess": "回复成功",- "replyFailed": "回复失败,请重试",- "aiReplyTaskCreated": "AI回复任务已创建",- "aiReplyTaskFailed": "AI回复创建失败"- },- "ui": {- "selectChannel": "请在左侧选择需要互动的频道",- "selectChannelDesc": "选择一个账号后,将自动加载该频道的最新作品与评论互动功能。",- "loadMore": "加载更多",- "noMorePosts": "没有更多作品",- "loading": "加载中...",- "sending": "发送中...",- "send": "发送",- "reply": "回复",- "expandReplies": "展开回复",- "collapseReplies": "收起回复",- "loadMoreReplies": "加载更多回复",- "loadMoreComments": "加载更多评论",- "commentPlaceholder": "输入评论...",- "replyPlaceholder": "回复@",- "noImage": "无图片",- "videoPreview": "视频预览",- "aiReply": "AI回复",- "aiReplyModalTitle": "AI智能回复",- "selectAiModel": "选择AI模型:",- "aiModelPlaceholder": "请选择AI模型",- "replyPrompt": "回复提示词:",- "promptPlaceholder": "请输入AI回复的提示词,例如:请帮我生成一个友好、专业的回复",- "cancel": "取消",- "creating": "创建中...",- "createAiReplyTask": "创建AI回复任务"- },- "stats": {- "likes": "点赞",- "comments": "评论",- "views": "浏览",- "shares": "分享",- "clicks": "点击",- "impressions": "曝光",- "favorites": "收藏"- },- "mediaTypes": {- "video": "视频",- "image": "图片",- "article": "文章"- }- },- "login": {- "welcomeBack": "哎呦赚",- "emailPlaceholder": "请输入注册邮箱",- "passwordPlaceholder": "密码",- "login": "登录/注册",- "or": "或",- "forgotPassword": "忘记密码?",- "completeRegistration": "完成注册",- "emailCode": "邮箱验证码",- "emailCodeRequired": "请输入邮箱验证码",- "emailCodeLength": "验证码长度为6位",- "enterEmailCode": "请输入邮箱验证码",- "setPassword": "设置密码",- "passwordRequired": "请输入密码",- "passwordMinLength": "密码长度不能小于6位",- "enterPassword": "请输入密码",- "inviteCode": "邀请码(选填)",- "enterInviteCode": "请输入邀请码",- "waitingForActivation": "等待激活中...",- "registering": "注册中...",- "loginSuccess": "登录成功",- "loginFailed": "登录失败",- "loginError": "登录失败,请稍后重试",- "activationEmailSent": "激活链接已发送至邮箱,请查收并点击激活",- "registerSuccess": "注册成功,已自动登录",- "checkStatusError": "检查注册状态失败",- "registerError": "注册失败,请稍后重试",- "googleLoginFailed": "Google 登录失败",- "resetPassword": "重置密码",- "emailLabel": "邮箱",- "emailRequired": "请输入邮箱",- "emailInvalid": "请输入有效的邮箱地址",- "sendResetLink": "发送重置链接",- "newPassword": "新密码",- "newPasswordRequired": "请输入新密码",- "newPasswordMinLength": "密码长度不能小于6个字符",- "newPasswordPlaceholder": "请输入新密码",- "confirmPassword": "确认密码",- "confirmPasswordRequired": "请确认密码",- "confirmPasswordMismatch": "两次输入的密码不一致",- "confirmPasswordPlaceholder": "请确认密码",- "confirmReset": "确认重置",- "waitingForEmailConfirmation": "等待邮件确认中...",- "sendFailed": "发送失败",- "resetFailed": "重置失败",- "invalidResetCode": "无效的重置码",- "resetSuccess": "密码重置成功",- "clickEmailLinkToReset": "请点击邮件中的重置链接完成密码重置",- "backToLogin": "返回登录",- "verificationCode": "验证码",- "verificationCodeRequired": "请输入验证码",- "verificationCodePlaceholder": "请输入邮箱中的验证码",- "resetEmailSent": "重置邮件已发送,请查收",- "sendEmailFailed": "发送邮件失败"- },- "material": {- "mediaManagement": {- "title": "媒体资源管理",- "createGroup": "创建媒体资源组",- "editGroup": "编辑媒体资源组",- "aiVideoGenerate": "AI视频生成",- "groupName": "资源组名称",- "groupNamePlaceholder": "请输入资源组名称",- "description": "描述",- "descriptionPlaceholder": "请输入描述(可选)",- "type": "类型",- "video": "视频",- "image": "图片",- "create": "创建",- "save": "保存",- "cancel": "取消",- "delete": "删除",- "edit": "编辑",- "deleteConfirm": "确定要删除这个媒体资源组吗?",- "createSuccess": "创建媒体资源组成功",- "createFailed": "创建媒体资源组失败",- "updateSuccess": "更新媒体资源组成功",- "updateFailed": "更新媒体资源组失败",- "deleteSuccess": "删除媒体资源组成功",- "deleteFailed": "删除媒体资源组失败",- "getListFailed": "获取媒体资源组列表失败",- "noGroups": "暂无媒体资源组",- "noGroupsDesc": "创建您的第一个媒体资源组,开始管理您的素材",- "createNow": "立即创建",- "resources": "个资源",- "noDescription": "暂无描述"- },- "aiGenerate": {- "title": "AI生成",- "backToAlbum": "返回相册",- "textToImage": "文生图",- "imageToImage": "图生图",- "fireflyCard": "Firefly卡片",- "videoGeneration": "视频生成",- "prompt": "提示词",- "promptPlaceholder": "请输入提示词",- "width": "宽度",- "height": "高度",- "generate": "生成",- "generating": "生成中...",- "content": "内容",- "contentPlaceholder": "请输入内容",- "titlePlaceholder": "请输入标题",- "template": "模板",- "uploadToMediaGroup": "上传到媒体组",- "selectMediaGroup": "选择媒体组",- "selectMediaGroupPlaceholder": "请选择媒体组",- "upload": "上传",- "uploading": "上传中...",- "uploadSuccess": "上传成功",- "uploadFailed": "上传失败",- "getMediaGroupListFailed": "获取媒体组列表失败",- "pleaseEnterPrompt": "请输入提示词",- "pleaseSelectMediaGroup": "请选择媒体组",- "pleaseEnterContent": "请输入内容",- "pleaseEnterTitle": "请输入标题",- "selectSize": "选择尺寸",- "generateCount": "生成数量",- "imageQuality": "图片质量",- "imageStyle": "图片风格",- "selectModel": "选择模型",- "standard": "标准",- "hd": "高清",- "vivid": "生动",- "natural": "自然",- "goldCardTemplate": "金卡模板",- "memoTemplate": "备忘录模板",- "simpleTemplate": "简约模板",- "blackSunTemplate": "黑日模板",- "templateE": "模板 E",- "writingTemplate": "写作模板",- "codeTemplate": "代码模板",- "templateD": "模板 D",- "videoPromptPlaceholder": "请输入视频描述",- "videoDuration": "视频时长",- "videoSize": "视频尺寸",- "videoMode": "生成模式",- "uploadImage": "上传图片",- "firstFrame": "首帧",- "tailFrame": "尾帧",- "imageUrlPlaceholder": "图片URL或base64",- "taskStatus": "任务状态",- "taskSubmitted": "任务已提交",- "taskProcessing": "任务处理中",- "taskCompleted": "任务完成",- "taskFailed": "任务失败",- "checkStatus": "检查状态",- "videoGenerationFailed": "视频生成失败",- "videoGenerationSuccess": "视频生成成功",- "pleaseEnterVideoPrompt": "请输入视频描述",- "pleaseSelectVideoModel": "请选择视频模型",- "videoUploadSuccess": "视频上传成功",- "videoUploadFailed": "视频上传失败",- "md2card": "Markdown转卡片",- "markdownPlaceholder": "请输入Markdown内容",- "selectTheme": "选择主题",- "themeMode": "主题模式",- "lightMode": "浅色模式",- "darkMode": "深色模式",- "cardWidth": "卡片宽度",- "cardHeight": "卡片高度",- "splitMode": "分割模式",- "noSplit": "不分割",- "split": "分割",- "mdxMode": "MDX模式",- "overHiddenMode": "溢出隐藏",- "generateCard": "生成卡片",- "cardGenerationFailed": "卡片生成失败",- "cardUploadSuccess": "卡片上传成功",- "cardUploadFailed": "卡片上传失败",- "pleaseEnterMarkdown": "请输入Markdown内容",- "imageGenerationFailed": "生成图片失败",- "fireflyCardGenerationFailed": "生成流光卡片失败",- "pleaseEnterContentAndTitle": "请输入内容和标题",- "taskSubmittedSuccess": "任务已提交",- "checkVideoTaskStatusFailed": "检查视频任务状态失败",- "pleaseEnterVideoDescription": "请输入视频描述",- "selectSizePlaceholder": "选择尺寸",- "generateCountPlaceholder": "生成数量",- "imageQualityPlaceholder": "图片质量",- "imageStylePlaceholder": "图片风格",- "selectModelPlaceholder": "选择模型",- "selectVideoModelPlaceholder": "选择视频模型",- "imageEditPromptPlaceholder": "请输入图片编辑提示词",- "uploadSourceImage": "上传源图片",- "uploadSourceImagePlaceholder": "请上传要编辑的图片",- "maxImages": "最多上传",- "imageEditFailed": "图片编辑失败",- "imageEditSuccess": "图片编辑成功",- "pleaseUploadSourceImage": "请上传源图片",- "imageEditTaskSubmitted": "图片编辑任务已提交",- "imageEditTaskProcessing": "图片编辑任务处理中",- "imageEditTaskCompleted": "图片编辑任务完成",- "imageEditTaskFailed": "图片编辑任务失败",- "advancedOptions": "高级选项",- "outputImageCount": "输出图像数量",- "low": "低",- "sourceImage": "源图片",- "deleteImage": "删除图片",- "clearAllImages": "清空所有图片",- "maxUploadReached": "已达到最大上传数量({{count}}张)",- "maxUploadLimitReached": "已达到最大上传数量限制:{{count}}张图片",- "autoSelectImages": "只能上传{{count}}张图片,已自动选择前{{count}}张",- "uploadSuccessCount": "成功上传 {{count}} 张图片",- "autoRemoveExcessImages": "模型最多支持{{maxCount}}张图片,已自动移除{{removedCount}}张图片",- "imageEditCompleted": "图片编辑完成",- "imageGenerationCompleted": "图片生成完成",- "noDefaultMediaGroup": "未找到默认素材库组",- "pleaseUploadAtLeastOneImage": "请上传至少一张图片",- "addImage": "添加图片",- "image": "图片",- "videoGenerationHistory": "视频生成历史",- "refresh": "刷新",- "noHistoryRecords": "暂无历史记录",- "submitTime": "提交时间",- "completeTime": "完成时间",- "progress": "进度",- "failReason": "失败原因",- "completed": "已完成",- "failed": "失败",- "processing": "处理中",- "submitted": "已提交",- "examplePrompt1": "延时绽放",- "examplePrompt2": "绚丽花朵",- "examplePrompt3": "海底世界",- "examplePrompt4": "星空漫游",- "examplePrompt5": "赛博城市",- "textToVideo": "文本转视频",- "imageToVideo": "图文转视频",- "seconds": "秒",- "selectThemePlaceholder": "选择主题",- "themeModePlaceholder": "主题模式",- "cardWidthPlaceholder": "卡片宽度",- "cardHeightPlaceholder": "卡片高度",- "splitModePlaceholder": "分割模式",- "markdownToCard": "Markdown转卡片",- "markdownCard": "Markdown卡片",- "templateA": "默认",- "templateB": "透明",- "templateC": "金句",- "templateJin": "书摘",- "templateMemo": "便当",- "templateEasy": "边框",- "templateWrite": "手写",- "pleaseUploadFirstFrame": "请上传首帧图片",- "pleaseUploadTailFrame": "请上传尾帧图片",- "imageRequirements": "图片要求",- "aspectRatioRange": "宽高比范围",- "aspectRatioRangeValue": "(0.4, 2.5)",- "dimensionRange": "宽高长度范围",- "dimensionRangeValue": "(300px, 6000px)",- "imageSizeLimit": "图片大小限制",- "imageSizeLimitValue": "小于30MB",- "imageFormatSupport": "支持格式",- "imageFormatSupportValue": "JPG, PNG, WEBP",- "estimatedCreditCost": "预计消耗积分",- "credits": "积分",- "getImageModelsFailed": "获取图片生成模型失败",- "getVideoModelsFailed": "获取视频生成模型失败"- }- },- "notification": {- "title": "消息通知",- "detailTitle": "通知详情",- "markAllAsRead": "全部标记为已读",- "markAsRead": "标记为已读",- "delete": "删除",- "close": "关闭",- "noNotifications": "暂无通知",- "confirmDelete": "确定要删除这条通知吗?",- "confirm": "确定",- "cancel": "取消",- "deleteSuccess": "删除成功",- "deleteFailed": "删除失败",- "markSuccess": "标记成功",- "markFailed": "标记失败",- "markAllSuccess": "全部标记成功",- "getNotificationListFailed": "获取通知列表失败",- "getNotificationDetailFailed": "获取通知详情失败",- "createTime": "创建时间",- "readTime": "已读时间",- "taskDetail": "任务详情",- "acceptTask": "接受任务",- "noTaskDetails": "暂无任务详情",- "taskProcessing": "任务处理中...",- "acceptingTask": "正在接受任务...",- "publishingTask": "正在发布任务...",- "submittingTask": "正在提交任务...",- "taskCompleted": "任务完成",- "taskProcessFailed": "任务处理失败",- "acceptTaskFailed": "接受任务失败",- "publishTaskFailed": "发布任务失败",- "submitTaskFailed": "提交任务失败",- "getTaskDetailFailed": "获取任务详情失败",- "accountInfoFailed": "账号信息获取失败",- "appRequiredNotice": "⚠️ 注意:",- "appRequiredMessage": "发布账号({{platform}})的任务需要在移动端App中操作,请下载对应App后继续。",- "mediaPreview": "媒体预览",- "pageInfo": "第 {{start}}-{{end}} 条,共 {{total}} 条",- "notificationTypes": {- "system": "系统通知",- "user": "用户通知",- "material": "素材通知",- "task_reminder": "任务提醒",- "other": "其他通知"- },- "taskStatus": {- "active": "进行中",- "inactive": "已结束"- },- "taskInfo": {- "description": "描述",- "publisherAccount": "发布账号",- "reward": "奖励",- "taskType": "任务类型",- "platformTypes": "支持平台"- },- "taskTypes": {- "video": "视频",- "article": "图文",- "article2": "纯文字"- },- "platforms": {- "tiktok": "TikTok",- "youtube": "YouTube",- "twitter": "Twitter",- "bilibili": "哔哩哔哩",- "KWAI": "快手",- "douyin": "抖音",- "xhs": "小红书",- "wxSph": "微信视频号",- "wxGzh": "微信公众号",- "facebook": "Facebook",- "instagram": "Instagram",- "threads": "Threads",- "pinterest": "Pinterest"- },- "time": {- "justNow": "刚刚",- "minutesAgo": "{{minutes}}分钟前",- "hoursAgo": "{{hours}}小时前",- "daysAgo": "{{days}}天前"- },- "accountSelect": {- "title": "选择发布账号",- "description": "描述",- "noAccounts": "没有符合条件的账号,请先添加账号",- "redirectingToAccounts": "正在跳转到账户界面,请添加符合条件的账号",- "accountId": "账号ID"- }- },- "pinterest": {- "title": "Pinterest 管理",- "tabs": {- "boards": "我的Board",- "pins": "我的Pin"- },- "actions": {- "selectAccount": "选择账户",- "refresh": "刷新",- "createBoard": "创建Board",- "createPin": "创建Pin",- "search": "搜索...",- "view": "查看",- "edit": "编辑",- "delete": "删除",- "link": "链接",- "change": "更改"- },- "stats": {- "followers": "关注者",- "boardCount": "Board数量",- "pinCount": "Pin数量",- "monthlyViews": "月观看量"- },- "board": {- "createTitle": "创建新Board",- "name": "Board名称",- "namePlaceholder": "输入Board名称",- "description": "描述",- "descriptionPlaceholder": "输入Board描述",- "privacy": "隐私设置",- "public": "公开",- "private": "私有",- "createButton": "创建Board",- "deleteConfirm": "确定删除此Board吗?",- "detailTitle": "Board详情",- "createTime": "创建时间",- "noDescription": "暂无描述"- },- "pin": {- "createTitle": "创建新Pin",- "selectBoard": "选择Board",- "selectBoardPlaceholder": "选择要发布到的Board",- "uploadImage": "上传图片",- "uploadImagePlaceholder": "点击上传图片到OSS",- "uploadHint": "支持JPG、PNG、GIF格式,最大10MB",- "uploading": "正在上传到OSS...",- "uploadSuccess": "✓ 上传成功",- "reupload": "重新上传",- "ossUrl": "OSS地址",- "title": "标题",- "titlePlaceholder": "输入Pin标题",- "description": "描述",- "descriptionPlaceholder": "输入Pin描述",- "link": "链接",- "linkPlaceholder": "输入目标链接(可选)",- "altText": "Alt文本",- "altTextPlaceholder": "输入图片Alt文本(可选)",- "dominantColor": "主色调",- "dominantColorTip": "选择Pin的主色调",- "createButton": "创建Pin",- "deleteConfirm": "确定删除此Pin吗?",- "detailTitle": "Pin详情",- "pinId": "Pin ID",- "boardId": "Board ID",- "creativeType": "创作类型",- "boardOwner": "Board拥有者",- "isOwner": "拥有者",- "isRemovable": "可移除",- "isStandard": "标准Pin",- "noDescription": "暂无描述",- "imageAlt": "Pin图片"- },- "badges": {- "pins": "Pins",- "followers": "关注者",- "owner": "拥有者",- "yes": "是",- "no": "否",- "selected": "当前选择"- },- "empty": {- "noBoards": "暂无Board",- "noPins": "暂无Pin"- },- "pagination": {- "total": "第 {range} 条,共 {total} 条"- },- "messages": {- "loadAccountsFailed": "加载账户列表失败",- "loadBoardsFailed": "加载Board列表失败",- "loadPinsFailed": "加载Pin列表失败",- "boardCreateSuccess": "Board创建成功",- "boardCreateFailed": "创建Board失败",- "boardDeleteSuccess": "Board删除成功",- "boardDeleteFailed": "删除Board失败",- "pinCreateSuccess": "Pin创建成功",- "pinCreateFailed": "创建Pin失败",- "pinDeleteSuccess": "Pin删除成功",- "pinDeleteFailed": "删除Pin失败",- "getBoardDetailFailed": "获取Board详情失败",- "getPinDetailFailed": "获取Pin详情失败",- "uploadImageFirst": "请先上传图片",- "selectImageFile": "请选择图片文件",- "imageSizeLimit": "图片大小不能超过10MB",- "imageUploadSuccess": "图片上传成功",- "imageUploadFailed": "图片上传失败,请重试",- "noAccountFound": "没有找到Pinterest账户"- },- "validation": {- "boardNameRequired": "请输入Board名称",- "selectBoardRequired": "请选择Board",- "titleRequired": "请输入标题",- "descriptionRequired": "请输入描述"- },- "confirm": {- "ok": "确定",- "cancel": "取消"- }- },- "pricing": {- "title": "套餐与定价",- "subtitle": "选择最适合您需求的套餐,开始您的AI创作之旅",- "monthly": "月付",- "yearly": "年付",- "save25": "省25%",- "save50": "省50%",- "month": "月",- "credits": "积分",- "videos": "视频",- "images": "图片",- "flashSale50": "限时5折",- "mostPopular": "最受欢迎",- "plans": {- "free": {- "name": "Free",- "credits": "最高60 积分",- "videos": "每月最高可生成60个视频",- "images": "每月最高可生成120张图片",- "button": "立即开始"- },- "plus": {- "name": "Plus",- "credits": "700积分",- "videos": "每月最高可生成700个视频",- "images": "每月最高可生成1400张图片",- "button": "立即购买"+ communitySection: {+ badge: '社区生态'+ title: '加入我们的'+ titleBlue: '活跃创作者社区'+ subtitle: 'AI ToEarn 由全球AI内容创作者社区共同推动。加入我们,一起探索AI内容营销的无限边界。'+ buttons: {+ wechat: '微信群组'+ community: '创作者交流群'+ }+ wechatPopup: '扫码关注微信公众号'+ communityPopup: '扫码加入社区群'+ stats: {+ downloads: {+ number: '20万+'+ label: '下载量'+ }+ members: {+ number: '15K'+ label: '社区成员'+ }+ creators: {+ number: '500+'+ label: '活跃创作者'+ }}- },- "features": {- "textModeration": "文本内容安全审查",- "imageModeration": "图片内容安全审查",- "videoModeration": "视频内容安全审查",- "multiModel": "多模型一站式支持",- "textToVideo": "文字转视频",- "imageToVideo": "图像转视频",- "videoToVideo": "视频到视频",- "consistentCharacter": "一致的角色视频",- "aiAnimation": "AI动画生成",- "aiImage": "AI图像生成",- "voiceClone": "声音克隆",- "voiceSynthesis": "声音合成",- "fasterSpeed": "更快的生成速度",- "withWatermark": "含水印输出",- "noWatermark": "无水印输出",- "storage500M": "存储空间500M",- "storage5G": "存储空间5G"- },- "faq": {- "title": "常见问题",- "paymentMethods": {- "question": "你们支持哪些支付方式?",- "answer": "我们支持多种支付方式,包括主要的信用卡(Visa、MasterCard、American Express)以及支付宝等。如果您在中国使用我们的服务,可以通过支付宝购买一次性服务。"- },- "creditDeduction": {- "question": "图片和视频生成时,积分是如何扣除的?",- "answer": "我们的图片和视频生成定价与官方渠道保持一致。通常情况下,如果官方渠道有大额采购折扣,我们也会同步将这些优惠让利给您。",- "pricingTable": {- "title": "详细价格表",- "headers": {- "model": "模型",- "type": "类型",- "duration": "时长",- "resolution": "分辨率",- "notes": "备注",- "credits": "积分",- "price": "价格",- "channel": "渠道"- },- "rows": [+ }+ footer: {+ resources: {+ title: '资源'+ links: {+ docs: '文档'+ blog: '博客'+ download: '下载'+ education: '教育'+ partner: '合作伙伴'+ support: '服务支持'+ roadmap: '产品线路图'+ }+ }+ company: {+ title: '公司'+ links: {+ talk: '联系我们'+ terms: '服务条款'+ privacy: '隐私政策'+ cookies: 'Cookie 设置'+ data: '数据删除引导'+ marketplace: '市场协议'+ brand: '品牌指南'+ }+ }+ description: 'AI ToEarn 自媒体运营平台一站式解决方案,从灵感创意到内容制作,从内容分发到内容互动管理'+ social: {+ github: 'GitHub'+ discord: 'Discord'+ youtube: 'YouTube'+ linkedin: 'LinkedIn'+ twitter: 'Twitter'+ }+ bigText: 'Let\'s Use AI To'+ copyright: '© 2025 AITOEARN, Corp.'+ tagline: ''+ dataDeletion: {+ title: 'Data Deletion Instructions'+ prelaunch: 'Our application is currently in pre-launch phase and does not store real user data. If you have interacted with our test systems, contact us for data removal.'+ standardTitle: 'Standard Procedure (Post-Launch):'+ standardSteps: [+ 'Log in to your AiToEarn account',+ 'Navigate to Settings > Privacy',+ 'Click "Request Account Deletion"',+ 'Confirmation will be sent to your registered email',+ ]+ contactTitle: 'Contact for Assistance:'+ contactEmail: 'Email: [email protected] (Pre-launch inquiries only)'+ }+ }+ }+ 'hot-content': {+ all: '全部'+ loading: '加载中...'+ noData: '暂无数据'+ rank: '排名'+ cover: '封面'+ title: '标题'+ author: '作者'+ category: '分类'+ likes: '点赞'+ shares: '分享'+ comments: '评论数'+ collections: '收藏数'+ publishTime: '发布于'+ fans: '粉丝数'+ viewMore: '查看更多'+ timeRange: '时间范围'+ filter: '筛选'+ hotTopics: '热门专题'+ viralTitles: '爆款标题'+ topics: '专题'+ engagement: '互动量'+ rising: '热'+ noHotTopics: '暂无热点数据'+ noViralTitles: '暂无爆款标题数据'+ noTopicData: '暂无专题数据'+ total: '总'+ items: '条'+ video: '视频'+ noImage: '暂无图片'+ platform: '平台'+ hotEvents: '热点事件'+ hotContent: '热点内容'+ noTitle: '暂无标题'+ baseInfo: '基本信息'+ views: '播放数'+ recommend: '推荐数'+ watch: '在看数'+ dailyRank: '日榜'+ updateFrequency: '更新时间'+ statEndTime: '统计数据截止'+ daily: '按日'+ sortRule: '排序规则'+ sortRuleDesc: '统计当日点赞量前500名的作品推荐'+ dataDescription: '数据说明'+ expand: '展开'+ collapse: '收起'+ hotValue: '热度值'+ hotTrend: '热度趋势'+ shortDrama: '短剧'+ cultureTourism: '文旅'+ contentOverseas: '内容出海'+ hot: '热点'+ last3days: '近3天'+ last7days: '近7天'+ last15days: '近15天'+ last30days: '近30天'+ backToAll: '返回全部'+ last90days: '近90天'+ }+ 'imageEditor': {+ 'Load': '加载本地'+ 'Download': '下载当前'+ 'Custom': '自定义'+ 'Square': '正方形'+ 'Apply': '应用'+ 'Cancel': '取消'+ 'Free': '自由设定'+ 'Straight': '直线'+ 'Color': '颜色'+ 'Range': '粗细'+ 'Grayscale': '灰度'+ 'Invert': '旋转'+ 'Sepia': '深褐色'+ 'Sepia2': '深褐色2'+ 'Blur': '模糊'+ 'Sharpen': '锐化'+ 'Emboss': '浮雕'+ 'Remove White': '消除白色'+ 'Distance': '边距'+ 'Brightness': '亮度'+ 'Noise': '降噪'+ 'Pixelate': '像素化'+ 'Color Filter': '颜色过滤'+ 'Threshold': '阈值'+ 'Tint': '色调'+ 'Multiply': '复合'+ 'Flip X': '镜像'+ 'Flip Y': '翻转'+ 'Reset': '重置'+ 'Arrow-1': '箭头1'+ 'Arrow-2': '箭头2'+ 'Arrow-3': '箭头3'+ 'Star-1': '星形1'+ 'Star-2': '星形2'+ 'Polygon': '多边形'+ 'Location': '定位'+ 'Heart': '心形'+ 'Bubble': '气泡'+ 'Custom icon': '自定义图标'+ 'Load Mask Image': '加载水印'+ 'Width': '宽'+ 'Height': '高'+ 'Lock Aspect Ratio': '保持尺寸比例'+ 'Rectangle': '矩形'+ 'Circle': '圆形'+ 'Triangle': '三角形'+ 'Fill': '填充'+ 'Stroke': '画笔'+ 'Bold': '加粗'+ 'Italic': '斜体'+ 'Underline': '下划线'+ 'Left': '居左'+ 'Center': '居中'+ 'Right': '居右'+ 'Text size': '字体大小'+ 'Zoom In': '放大'+ 'Zoom Out': '缩小'+ 'ZoomIn': '放大'+ 'ZoomOut': '缩小'+ 'Hand': '拖动'+ 'Resize': '尺寸'+ 'Crop': '裁剪'+ 'Flip': '翻转'+ 'Rotate': '旋转'+ 'Draw': '画笔'+ 'Shape': '形状'+ 'Icon': '图标'+ 'Text': '文字'+ 'Mask': '水印'+ 'Filter': '滤镜'+ 'History': '历史动作'+ 'Undo': '撤退'+ 'Redo': '重做'+ 'Delete': '去除'+ 'DeleteAll': '全部去除'+ 'Blend': '混合'+ 'imageEditing': '图像编辑'+ }+ 'income': {+ title: '我的收入'+ subtitle: '管理您的收入记录和提现申请'+ currentBalance: '当前余额'+ incomeRecords: '收入记录'+ withdrawRecords: '提现记录'+ incomeId: '收入ID'+ amount: '金额'+ type: '类型'+ description: '描述'+ createTime: '创建时间'+ actions: '操作'+ applyWithdraw: '申请提现'+ withdrawId: '提现ID'+ status: '状态'+ updateTime: '更新时间'+ confirmWithdraw: '确认提现申请'+ cancel: '取消'+ confirm: '确认提现'+ withdrawAmount: '提现金额'+ incomeType: '收入类型'+ withdrawWarning: '⚠️ 提现申请提交后,我们将在1-3个工作日内处理您的申请。'+ withdrawWarning2: '请确保您的账户信息正确,提现成功后金额将转入您的指定账户。'+ incomeTypes: {+ task: '任务收入'+ task_back: '任务回退'+ reward_back: '奖励回退'+ task_withdraw: '任务提现'+ }+ withdrawStatus: {+ wait: '等待处理'+ success: '提现成功'+ fail: '提现失败'+ task_withdraw: '任务提现'+ }+ messages: {+ getIncomeRecordsFailed: '获取收入记录失败'+ getWithdrawRecordsFailed: '获取提现记录失败'+ withdrawSubmitted: '提现申请提交成功'+ withdrawFailed: '提现申请提交失败'+ pleaseLoginFirst: '请先登录'+ noIncomeRecords: '暂无收入记录'+ noWithdrawRecords: '暂无提现记录'+ loading: '加载中...'+ totalRecords: '共 {{total}} 条记录'+ }+ myWallet: '我的钱包'+ }+ 'interactive': {+ title: '互动管理'+ messages: {+ pleaseLoginFirst: '请先登录'+ commentSuccess: '评论成功'+ commentFailed: '评论失败,请重试'+ replySuccess: '回复成功'+ replyFailed: '回复失败,请重试'+ aiReplyTaskCreated: 'AI回复任务已创建'+ aiReplyTaskFailed: 'AI回复创建失败'+ }+ ui: {+ selectChannel: '请在左侧选择需要互动的频道'+ selectChannelDesc: '选择一个账号后,将自动加载该频道的最新作品与评论互动功能。'+ loadMore: '加载更多'+ noMorePosts: '没有更多作品'+ loading: '加载中...'+ sending: '发送中...'+ send: '发送'+ reply: '回复'+ expandReplies: '展开回复'+ collapseReplies: '收起回复'+ loadMoreReplies: '加载更多回复'+ loadMoreComments: '加载更多评论'+ commentPlaceholder: '输入评论...'+ replyPlaceholder: '回复@'+ noImage: '无图片'+ videoPreview: '视频预览'+ aiReply: 'AI回复'+ aiReplyModalTitle: 'AI智能回复'+ selectAiModel: '选择AI模型:'+ aiModelPlaceholder: '请选择AI模型'+ replyPrompt: '回复提示词:'+ promptPlaceholder: '请输入AI回复的提示词,例如:请帮我生成一个友好、专业的回复'+ cancel: '取消'+ creating: '创建中...'+ createAiReplyTask: '创建AI回复任务'+ }+ stats: {+ likes: '点赞'+ comments: '评论'+ views: '浏览'+ shares: '分享'+ clicks: '点击'+ impressions: '曝光'+ favorites: '收藏'+ }+ mediaTypes: {+ video: '视频'+ image: '图片'+ article: '文章'+ }+ }+ 'login': {+ welcomeBack: '哎呦赚'+ emailPlaceholder: '请输入注册邮箱'+ passwordPlaceholder: '密码'+ login: '登录/注册'+ or: '或'+ forgotPassword: '忘记密码?'+ completeRegistration: '完成注册'+ emailCode: '邮箱验证码'+ emailCodeRequired: '请输入邮箱验证码'+ emailCodeLength: '验证码长度为6位'+ enterEmailCode: '请输入邮箱验证码'+ setPassword: '设置密码'+ passwordRequired: '请输入密码'+ passwordMinLength: '密码长度不能小于6位'+ enterPassword: '请输入密码'+ inviteCode: '邀请码(选填)'+ enterInviteCode: '请输入邀请码'+ waitingForActivation: '等待激活中...'+ registering: '注册中...'+ loginSuccess: '登录成功'+ loginFailed: '登录失败'+ loginError: '登录失败,请稍后重试'+ activationEmailSent: '激活链接已发送至邮箱,请查收并点击激活'+ registerSuccess: '注册成功,已自动登录'+ checkStatusError: '检查注册状态失败'+ registerError: '注册失败,请稍后重试'+ googleLoginFailed: 'Google 登录失败'+ resetPassword: '重置密码'+ emailLabel: '邮箱'+ emailRequired: '请输入邮箱'+ emailInvalid: '请输入有效的邮箱地址'+ sendResetLink: '发送重置链接'+ newPassword: '新密码'+ newPasswordRequired: '请输入新密码'+ newPasswordMinLength: '密码长度不能小于6个字符'+ newPasswordPlaceholder: '请输入新密码'+ confirmPassword: '确认密码'+ confirmPasswordRequired: '请确认密码'+ confirmPasswordMismatch: '两次输入的密码不一致'+ confirmPasswordPlaceholder: '请确认密码'+ confirmReset: '确认重置'+ waitingForEmailConfirmation: '等待邮件确认中...'+ sendFailed: '发送失败'+ resetFailed: '重置失败'+ invalidResetCode: '无效的重置码'+ resetSuccess: '密码重置成功'+ clickEmailLinkToReset: '请点击邮件中的重置链接完成密码重置'+ backToLogin: '返回登录'+ verificationCode: '验证码'+ verificationCodeRequired: '请输入验证码'+ verificationCodePlaceholder: '请输入邮箱中的验证码'+ resetEmailSent: '重置邮件已发送,请查收'+ sendEmailFailed: '发送邮件失败'+ }+ 'material': {+ mediaManagement: {+ title: '媒体资源管理'+ createGroup: '创建媒体资源组'+ editGroup: '编辑媒体资源组'+ aiVideoGenerate: 'AI视频生成'+ groupName: '资源组名称'+ groupNamePlaceholder: '请输入资源组名称'+ description: '描述'+ descriptionPlaceholder: '请输入描述(可选)'+ type: '类型'+ video: '视频'+ image: '图片'+ create: '创建'+ save: '保存'+ cancel: '取消'+ delete: '删除'+ edit: '编辑'+ deleteConfirm: '确定要删除这个媒体资源组吗?'+ createSuccess: '创建媒体资源组成功'+ createFailed: '创建媒体资源组失败'+ updateSuccess: '更新媒体资源组成功'+ updateFailed: '更新媒体资源组失败'+ deleteSuccess: '删除媒体资源组成功'+ deleteFailed: '删除媒体资源组失败'+ getListFailed: '获取媒体资源组列表失败'+ noGroups: '暂无媒体资源组'+ noGroupsDesc: '创建您的第一个媒体资源组,开始管理您的素材'+ createNow: '立即创建'+ resources: '个资源'+ noDescription: '暂无描述'+ }+ aiGenerate: {+ title: 'AI生成'+ backToAlbum: '返回相册'+ textToImage: '文生图'+ imageToImage: '图生图'+ fireflyCard: 'Firefly卡片'+ videoGeneration: '视频生成'+ prompt: '提示词'+ promptPlaceholder: '请输入提示词'+ width: '宽度'+ height: '高度'+ generate: '生成'+ generating: '生成中...'+ content: '内容'+ contentPlaceholder: '请输入内容'+ titlePlaceholder: '请输入标题'+ template: '模板'+ uploadToMediaGroup: '上传到媒体组'+ selectMediaGroup: '选择媒体组'+ selectMediaGroupPlaceholder: '请选择媒体组'+ upload: '上传'+ uploading: '上传中...'+ uploadSuccess: '上传成功'+ uploadFailed: '上传失败'+ getMediaGroupListFailed: '获取媒体组列表失败'+ pleaseEnterPrompt: '请输入提示词'+ pleaseSelectMediaGroup: '请选择媒体组'+ pleaseEnterContent: '请输入内容'+ pleaseEnterTitle: '请输入标题'+ selectSize: '选择尺寸'+ generateCount: '生成数量'+ imageQuality: '图片质量'+ imageStyle: '图片风格'+ selectModel: '选择模型'+ standard: '标准'+ hd: '高清'+ vivid: '生动'+ natural: '自然'+ goldCardTemplate: '金卡模板'+ memoTemplate: '备忘录模板'+ simpleTemplate: '简约模板'+ blackSunTemplate: '黑日模板'+ templateE: '模板 E'+ writingTemplate: '写作模板'+ codeTemplate: '代码模板'+ templateD: '模板 D'+ videoPromptPlaceholder: '请输入视频描述'+ videoDuration: '视频时长'+ videoSize: '视频尺寸'+ videoMode: '生成模式'+ uploadImage: '上传图片'+ firstFrame: '首帧'+ tailFrame: '尾帧'+ imageUrlPlaceholder: '图片URL或base64'+ taskStatus: '任务状态'+ taskSubmitted: '任务已提交'+ taskProcessing: '任务处理中'+ taskCompleted: '任务完成'+ taskFailed: '任务失败'+ checkStatus: '检查状态'+ videoGenerationFailed: '视频生成失败'+ videoGenerationSuccess: '视频生成成功'+ pleaseEnterVideoPrompt: '请输入视频描述'+ pleaseSelectVideoModel: '请选择视频模型'+ videoUploadSuccess: '视频上传成功'+ videoUploadFailed: '视频上传失败'+ md2card: 'Markdown转卡片'+ markdownPlaceholder: '请输入Markdown内容'+ selectTheme: '选择主题'+ themeMode: '主题模式'+ lightMode: '浅色模式'+ darkMode: '深色模式'+ cardWidth: '卡片宽度'+ cardHeight: '卡片高度'+ splitMode: '分割模式'+ noSplit: '不分割'+ split: '分割'+ mdxMode: 'MDX模式'+ overHiddenMode: '溢出隐藏'+ generateCard: '生成卡片'+ cardGenerationFailed: '卡片生成失败'+ cardUploadSuccess: '卡片上传成功'+ cardUploadFailed: '卡片上传失败'+ pleaseEnterMarkdown: '请输入Markdown内容'+ imageGenerationFailed: '生成图片失败'+ fireflyCardGenerationFailed: '生成流光卡片失败'+ pleaseEnterContentAndTitle: '请输入内容和标题'+ taskSubmittedSuccess: '任务已提交'+ checkVideoTaskStatusFailed: '检查视频任务状态失败'+ pleaseEnterVideoDescription: '请输入视频描述'+ selectSizePlaceholder: '选择尺寸'+ generateCountPlaceholder: '生成数量'+ imageQualityPlaceholder: '图片质量'+ imageStylePlaceholder: '图片风格'+ selectModelPlaceholder: '选择模型'+ selectVideoModelPlaceholder: '选择视频模型'+ imageEditPromptPlaceholder: '请输入图片编辑提示词'+ uploadSourceImage: '上传源图片'+ uploadSourceImagePlaceholder: '请上传要编辑的图片'+ maxImages: '最多上传'+ imageEditFailed: '图片编辑失败'+ imageEditSuccess: '图片编辑成功'+ pleaseUploadSourceImage: '请上传源图片'+ imageEditTaskSubmitted: '图片编辑任务已提交'+ imageEditTaskProcessing: '图片编辑任务处理中'+ imageEditTaskCompleted: '图片编辑任务完成'+ imageEditTaskFailed: '图片编辑任务失败'+ advancedOptions: '高级选项'+ outputImageCount: '输出图像数量'+ low: '低'+ sourceImage: '源图片'+ deleteImage: '删除图片'+ clearAllImages: '清空所有图片'+ maxUploadReached: '已达到最大上传数量({{count}}张)'+ maxUploadLimitReached: '已达到最大上传数量限制:{{count}}张图片'+ autoSelectImages: '只能上传{{count}}张图片,已自动选择前{{count}}张'+ uploadSuccessCount: '成功上传 {{count}} 张图片'+ autoRemoveExcessImages: '模型最多支持{{maxCount}}张图片,已自动移除{{removedCount}}张图片'+ imageEditCompleted: '图片编辑完成'+ imageGenerationCompleted: '图片生成完成'+ noDefaultMediaGroup: '未找到默认素材库组'+ pleaseUploadAtLeastOneImage: '请上传至少一张图片'+ addImage: '添加图片'+ image: '图片'+ videoGenerationHistory: '视频生成历史'+ refresh: '刷新'+ noHistoryRecords: '暂无历史记录'+ submitTime: '提交时间'+ completeTime: '完成时间'+ progress: '进度'+ failReason: '失败原因'+ completed: '已完成'+ failed: '失败'+ processing: '处理中'+ submitted: '已提交'+ examplePrompt1: '延时绽放'+ examplePrompt2: '绚丽花朵'+ examplePrompt3: '海底世界'+ examplePrompt4: '星空漫游'+ examplePrompt5: '赛博城市'+ textToVideo: '文本转视频'+ imageToVideo: '图文转视频'+ seconds: '秒'+ selectThemePlaceholder: '选择主题'+ themeModePlaceholder: '主题模式'+ cardWidthPlaceholder: '卡片宽度'+ cardHeightPlaceholder: '卡片高度'+ splitModePlaceholder: '分割模式'+ markdownToCard: 'Markdown转卡片'+ markdownCard: 'Markdown卡片'+ templateA: '默认'+ templateB: '透明'+ templateC: '金句'+ templateJin: '书摘'+ templateMemo: '便当'+ templateEasy: '边框'+ templateWrite: '手写'+ pleaseUploadFirstFrame: '请上传首帧图片'+ pleaseUploadTailFrame: '请上传尾帧图片'+ imageRequirements: '图片要求'+ aspectRatioRange: '宽高比范围'+ aspectRatioRangeValue: '(0.4, 2.5)'+ dimensionRange: '宽高长度范围'+ dimensionRangeValue: '(300px, 6000px)'+ imageSizeLimit: '图片大小限制'+ imageSizeLimitValue: '小于30MB'+ imageFormatSupport: '支持格式'+ imageFormatSupportValue: 'JPG, PNG, WEBP'+ estimatedCreditCost: '预计消耗积分'+ credits: '积分'+ getImageModelsFailed: '获取图片生成模型失败'+ getVideoModelsFailed: '获取视频生成模型失败'+ }+ }+ 'notification': {+ title: '消息通知'+ detailTitle: '通知详情'+ markAllAsRead: '全部标记为已读'+ markAsRead: '标记为已读'+ delete: '删除'+ close: '关闭'+ noNotifications: '暂无通知'+ confirmDelete: '确定要删除这条通知吗?'+ confirm: '确定'+ cancel: '取消'+ deleteSuccess: '删除成功'+ deleteFailed: '删除失败'+ markSuccess: '标记成功'+ markFailed: '标记失败'+ markAllSuccess: '全部标记成功'+ getNotificationListFailed: '获取通知列表失败'+ getNotificationDetailFailed: '获取通知详情失败'+ createTime: '创建时间'+ readTime: '已读时间'+ taskDetail: '任务详情'+ acceptTask: '接受任务'+ noTaskDetails: '暂无任务详情'+ taskProcessing: '任务处理中...'+ acceptingTask: '正在接受任务...'+ publishingTask: '正在发布任务...'+ submittingTask: '正在提交任务...'+ taskCompleted: '任务完成'+ taskProcessFailed: '任务处理失败'+ acceptTaskFailed: '接受任务失败'+ publishTaskFailed: '发布任务失败'+ submitTaskFailed: '提交任务失败'+ getTaskDetailFailed: '获取任务详情失败'+ accountInfoFailed: '账号信息获取失败'+ appRequiredNotice: '⚠️ 注意:'+ appRequiredMessage: '发布账号({{platform}})的任务需要在移动端App中操作,请下载对应App后继续。'+ mediaPreview: '媒体预览'+ pageInfo: '第 {{start}}-{{end}} 条,共 {{total}} 条'+ notificationTypes: {+ system: '系统通知'+ user: '用户通知'+ material: '素材通知'+ task_reminder: '任务提醒'+ other: '其他通知'+ }+ taskStatus: {+ active: '进行中'+ inactive: '已结束'+ }+ taskInfo: {+ description: '描述'+ publisherAccount: '发布账号'+ reward: '奖励'+ taskType: '任务类型'+ platformTypes: '支持平台'+ }+ taskTypes: {+ video: '视频'+ article: '图文'+ article2: '纯文字'+ }+ platforms: {+ tiktok: 'TikTok'+ youtube: 'YouTube'+ twitter: 'Twitter'+ bilibili: '哔哩哔哩'+ KWAI: '快手'+ douyin: '抖音'+ xhs: '小红书'+ wxSph: '微信视频号'+ wxGzh: '微信公众号'+ facebook: 'Facebook'+ instagram: 'Instagram'+ threads: 'Threads'+ pinterest: 'Pinterest'+ }+ time: {+ justNow: '刚刚'+ minutesAgo: '{{minutes}}分钟前'+ hoursAgo: '{{hours}}小时前'+ daysAgo: '{{days}}天前'+ }+ accountSelect: {+ title: '选择发布账号'+ description: '描述'+ noAccounts: '没有符合条件的账号,请先添加账号'+ redirectingToAccounts: '正在跳转到账户界面,请添加符合条件的账号'+ accountId: '账号ID'+ }+ }+ 'pinterest': {+ title: 'Pinterest 管理'+ tabs: {+ boards: '我的Board'+ pins: '我的Pin'+ }+ actions: {+ selectAccount: '选择账户'+ refresh: '刷新'+ createBoard: '创建Board'+ createPin: '创建Pin'+ search: '搜索...'+ view: '查看'+ edit: '编辑'+ delete: '删除'+ link: '链接'+ change: '更改'+ }+ stats: {+ followers: '关注者'+ boardCount: 'Board数量'+ pinCount: 'Pin数量'+ monthlyViews: '月观看量'+ }+ board: {+ createTitle: '创建新Board'+ name: 'Board名称'+ namePlaceholder: '输入Board名称'+ description: '描述'+ descriptionPlaceholder: '输入Board描述'+ privacy: '隐私设置'+ public: '公开'+ private: '私有'+ createButton: '创建Board'+ deleteConfirm: '确定删除此Board吗?'+ detailTitle: 'Board详情'+ createTime: '创建时间'+ noDescription: '暂无描述'+ }+ pin: {+ createTitle: '创建新Pin'+ selectBoard: '选择Board'+ selectBoardPlaceholder: '选择要发布到的Board'+ uploadImage: '上传图片'+ uploadImagePlaceholder: '点击上传图片到OSS'+ uploadHint: '支持JPG、PNG、GIF格式,最大10MB'+ uploading: '正在上传到OSS...'+ uploadSuccess: '✓ 上传成功'+ reupload: '重新上传'+ ossUrl: 'OSS地址'+ title: '标题'+ titlePlaceholder: '输入Pin标题'+ description: '描述'+ descriptionPlaceholder: '输入Pin描述'+ link: '链接'+ linkPlaceholder: '输入目标链接(可选)'+ altText: 'Alt文本'+ altTextPlaceholder: '输入图片Alt文本(可选)'+ dominantColor: '主色调'+ dominantColorTip: '选择Pin的主色调'+ createButton: '创建Pin'+ deleteConfirm: '确定删除此Pin吗?'+ detailTitle: 'Pin详情'+ pinId: 'Pin ID'+ boardId: 'Board ID'+ creativeType: '创作类型'+ boardOwner: 'Board拥有者'+ isOwner: '拥有者'+ isRemovable: '可移除'+ isStandard: '标准Pin'+ noDescription: '暂无描述'+ imageAlt: 'Pin图片'+ }+ badges: {+ pins: 'Pins'+ followers: '关注者'+ owner: '拥有者'+ yes: '是'+ no: '否'+ selected: '当前选择'+ }+ empty: {+ noBoards: '暂无Board'+ noPins: '暂无Pin'+ }+ pagination: {+ total: '第 {range} 条,共 {total} 条'+ }+ messages: {+ loadAccountsFailed: '加载账户列表失败'+ loadBoardsFailed: '加载Board列表失败'+ loadPinsFailed: '加载Pin列表失败'+ boardCreateSuccess: 'Board创建成功'+ boardCreateFailed: '创建Board失败'+ boardDeleteSuccess: 'Board删除成功'+ boardDeleteFailed: '删除Board失败'+ pinCreateSuccess: 'Pin创建成功'+ pinCreateFailed: '创建Pin失败'+ pinDeleteSuccess: 'Pin删除成功'+ pinDeleteFailed: '删除Pin失败'+ getBoardDetailFailed: '获取Board详情失败'+ getPinDetailFailed: '获取Pin详情失败'+ uploadImageFirst: '请先上传图片'+ selectImageFile: '请选择图片文件'+ imageSizeLimit: '图片大小不能超过10MB'+ imageUploadSuccess: '图片上传成功'+ imageUploadFailed: '图片上传失败,请重试'+ noAccountFound: '没有找到Pinterest账户'+ }+ validation: {+ boardNameRequired: '请输入Board名称'+ selectBoardRequired: '请选择Board'+ titleRequired: '请输入标题'+ descriptionRequired: '请输入描述'+ }+ confirm: {+ ok: '确定'+ cancel: '取消'+ }+ }+ 'pricing': {+ title: '套餐与定价'+ subtitle: '选择最适合您需求的套餐,开始您的AI创作之旅'+ monthly: '月付'+ yearly: '年付'+ save25: '省25%'+ save50: '省50%'+ month: '月'+ credits: '积分'+ videos: '视频'+ images: '图片'+ flashSale50: '限时5折'+ mostPopular: '最受欢迎'+ plans: {+ free: {+ name: 'Free'+ credits: '最高60 积分'+ videos: '每月最高可生成60个视频'+ images: '每月最高可生成120张图片'+ button: '立即开始'+ }+ plus: {+ name: 'Plus'+ credits: '700积分'+ videos: '每月最高可生成700个视频'+ images: '每月最高可生成1400张图片'+ button: '立即购买'+ }+ }+ features: {+ textModeration: '文本内容安全审查'+ imageModeration: '图片内容安全审查'+ videoModeration: '视频内容安全审查'+ multiModel: '多模型一站式支持'+ textToVideo: '文字转视频'+ imageToVideo: '图像转视频'+ videoToVideo: '视频到视频'+ consistentCharacter: '一致的角色视频'+ aiAnimation: 'AI动画生成'+ aiImage: 'AI图像生成'+ voiceClone: '声音克隆'+ voiceSynthesis: '声音合成'+ fasterSpeed: '更快的生成速度'+ withWatermark: '含水印输出'+ noWatermark: '无水印输出'+ storage500M: '存储空间500M'+ storage5G: '存储空间5G'+ }+ faq: {+ title: '常见问题'+ paymentMethods: {+ question: '你们支持哪些支付方式?'+ answer: '我们支持多种支付方式,包括主要的信用卡(Visa、MasterCard、American Express)以及支付宝等。如果您在中国使用我们的服务,可以通过支付宝购买一次性服务。'+ }+ creditDeduction: {+ question: '图片和视频生成时,积分是如何扣除的?'+ answer: '我们的图片和视频生成定价与官方渠道保持一致。通常情况下,如果官方渠道有大额采购折扣,我们也会同步将这些优惠让利给您。'+ pricingTable: {+ title: '详细价格表'+ headers: {+ model: '模型'+ type: '类型'+ duration: '时长'+ resolution: '分辨率'+ notes: '备注'+ credits: '积分'+ price: '价格'+ channel: '渠道'+ }+ rows: [{- "model": "gpt-5",- "type": "大模型",- "duration": "",- "resolution": "",- "notes": "大模型价格以官方价格为准",- "credits": "每百万tokens",- "price": "输入 9元,输出 72元",- "channel": "yun"+ model: 'gpt-5'+ type: '大模型'+ duration: ''+ resolution: ''+ notes: '大模型价格以官方价格为准'+ credits: '每百万tokens'+ price: '输入 9元,输出 72元'+ channel: 'yun'},{- "model": "gpt-5-mini",- "type": "大模型",- "duration": "",- "resolution": "",- "notes": "",- "credits": "",- "price": "输入 1.8元,输出 14.4元",- "channel": "yun"+ model: 'gpt-5-mini'+ type: '大模型'+ duration: ''+ resolution: ''+ notes: ''+ credits: ''+ price: '输入 1.8元,输出 14.4元'+ channel: 'yun'},{- "model": "gpt-5-nano",- "type": "大模型",- "duration": "",- "resolution": "",- "notes": "",- "credits": "",- "price": "输入 0.36元,输出 2.88元",- "channel": "yun"+ model: 'gpt-5-nano'+ type: '大模型'+ duration: ''+ resolution: ''+ notes: ''+ credits: ''+ price: '输入 0.36元,输出 2.88元'+ channel: 'yun'},{- "model": "gemini-2.5-pro",- "type": "大模型",- "duration": "",- "resolution": "支持视频",- "notes": "",- "credits": "",- "price": "输入9元,输出 72元",- "channel": "yun"+ model: 'gemini-2.5-pro'+ type: '大模型'+ duration: ''+ resolution: '支持视频'+ notes: ''+ credits: ''+ price: '输入9元,输出 72元'+ channel: 'yun'},{- "model": "chatgpt-4o-latest",- "type": "大模型",- "duration": "",- "resolution": "",- "notes": "",- "credits": "",- "price": "输入 36元,输出 108元",- "channel": "yun"+ model: 'chatgpt-4o-latest'+ type: '大模型'+ duration: ''+ resolution: ''+ notes: ''+ credits: ''+ price: '输入 36元,输出 108元'+ channel: 'yun'},{- "model": "gemini-2.5-flash",- "type": "大模型",- "duration": "",- "resolution": "支持视频",- "notes": "",- "credits": "",- "price": "输入 2.16元,输出 18元",- "channel": "yun"+ model: 'gemini-2.5-flash'+ type: '大模型'+ duration: ''+ resolution: '支持视频'+ notes: ''+ credits: ''+ price: '输入 2.16元,输出 18元'+ channel: 'yun'},{- "model": "qwen-vl-max-latest",- "type": "大模型",- "duration": "",- "resolution": "",- "notes": "",- "credits": "",- "price": "输入1.6元,输出4元",- "channel": "yun"+ model: 'qwen-vl-max-latest'+ type: '大模型'+ duration: ''+ resolution: ''+ notes: ''+ credits: ''+ price: '输入1.6元,输出4元'+ channel: 'yun'},{- "model": "gemini-2.5-flash-image",- "type": "图片生成",- "duration": "",- "resolution": "",- "notes": "又名nano banana,支持多图像输入",- "credits": "1",- "price": "0.27元",- "channel": "yun"+ model: 'gemini-2.5-flash-image'+ type: '图片生成'+ duration: ''+ resolution: ''+ notes: '又名nano banana,支持多图像输入'+ credits: '1'+ price: '0.27元'+ channel: 'yun'},{- "model": "seedream-3.0",- "type": "图片生成",- "duration": "",- "resolution": "",- "notes": "",- "credits": "2.6",- "price": "0.26元",- "channel": "官方"+ model: 'seedream-3.0'+ type: '图片生成'+ duration: ''+ resolution: ''+ notes: ''+ credits: '2.6'+ price: '0.26元'+ channel: '官方'},{- "model": "seededit-3.0",- "type": "图片生成",- "duration": "",- "resolution": "",- "notes": "图片编辑,支持jpeg、png格式",- "credits": "3",- "price": "0.3元",- "channel": "官方"+ model: 'seededit-3.0'+ type: '图片生成'+ duration: ''+ resolution: ''+ notes: '图片编辑,支持jpeg、png格式'+ credits: '3'+ price: '0.3元'+ channel: '官方'},{- "model": "gpt-image-1",- "type": "图片生成",- "duration": "",- "resolution": "支持图片编辑",- "notes": "",- "credits": "促销",- "price": "low $0.011-0.016,medium $0.042-0.063,high $0.167-0.25",- "channel": "yun"+ model: 'gpt-image-1'+ type: '图片生成'+ duration: ''+ resolution: '支持图片编辑'+ notes: ''+ credits: '促销'+ price: 'low $0.011-0.016,medium $0.042-0.063,high $0.167-0.25'+ channel: 'yun'},{- "model": "FLUX.1 Kontext [max]",- "type": "图片生成",- "duration": "",- "resolution": "支持图片编辑",- "notes": "",- "credits": "1.5",- "price": "0.6元",- "channel": "yun"+ model: 'FLUX.1 Kontext [max]'+ type: '图片生成'+ duration: ''+ resolution: '支持图片编辑'+ notes: ''+ credits: '1.5'+ price: '0.6元'+ channel: 'yun'},{- "model": "FLUX.1 Kontext [pro]",- "type": "图片生成",- "duration": "",- "resolution": "支持图片编辑",- "notes": "",- "credits": "1",- "price": "0.3元",- "channel": "yun"+ model: 'FLUX.1 Kontext [pro]'+ type: '图片生成'+ duration: ''+ resolution: '支持图片编辑'+ notes: ''+ credits: '1'+ price: '0.3元'+ channel: 'yun'},{- "model": "Flux 1.1 pro ultra",- "type": "图片生成",- "duration": "",- "resolution": "",- "notes": "",- "credits": "4.5",- "price": "0.45元",- "channel": "官方"+ model: 'Flux 1.1 pro ultra'+ type: '图片生成'+ duration: ''+ resolution: ''+ notes: ''+ credits: '4.5'+ price: '0.45元'+ channel: '官方'},{- "model": "Flux1.1 pro",- "type": "图片生成",- "duration": "",- "resolution": "",- "notes": "",- "credits": "3",- "price": "0.3元",- "channel": "官方"+ model: 'Flux1.1 pro'+ type: '图片生成'+ duration: ''+ resolution: ''+ notes: ''+ credits: '3'+ price: '0.3元'+ channel: '官方'},{- "model": "midjourney relax",- "type": "视频生成",- "duration": "5秒",- "resolution": "",- "notes": "",- "credits": "免费",- "price": "",- "channel": "yun"+ model: 'midjourney relax'+ type: '视频生成'+ duration: '5秒'+ resolution: ''+ notes: ''+ credits: '免费'+ price: ''+ channel: 'yun'},{- "model": "midjourney fast/turbo",- "type": "视频生成",- "duration": "5秒",- "resolution": "",- "notes": "",- "credits": "4",- "price": "",- "channel": "yun"+ model: 'midjourney fast/turbo'+ type: '视频生成'+ duration: '5秒'+ resolution: ''+ notes: ''+ credits: '4'+ price: ''+ channel: 'yun'},{- "model": "kling1.5/1.6/2.1",- "type": "视频生成",- "duration": "5秒",- "resolution": "720p",- "notes": "",- "credits": "20",- "price": "2元",- "channel": "yun"+ model: 'kling1.5/1.6/2.1'+ type: '视频生成'+ duration: '5秒'+ resolution: '720p'+ notes: ''+ credits: '20'+ price: '2元'+ channel: 'yun'},{- "model": "kling1.5/1.6/2.1",- "type": "视频生成",- "duration": "10秒",- "resolution": "720p",- "notes": "",- "credits": "40",- "price": "4元",- "channel": "yun"+ model: 'kling1.5/1.6/2.1'+ type: '视频生成'+ duration: '10秒'+ resolution: '720p'+ notes: ''+ credits: '40'+ price: '4元'+ channel: 'yun'},{- "model": "kling1.5/1.6/2.1",- "duration": "5秒",- "resolution": "1080p",- "notes": "",- "credits": "35",- "price": "3.5元",- "channel": "yun"+ model: 'kling1.5/1.6/2.1'+ duration: '5秒'+ resolution: '1080p'+ notes: ''+ credits: '35'+ price: '3.5元'+ channel: 'yun'},{- "model": "kling1.5/1.6/2.1",- "type": "视频生成",- "duration": "10秒",- "resolution": "1080p",- "notes": "",- "credits": "70",- "price": "7元",- "channel": "yun"+ model: 'kling1.5/1.6/2.1'+ type: '视频生成'+ duration: '10秒'+ resolution: '1080p'+ notes: ''+ credits: '70'+ price: '7元'+ channel: 'yun'},{- "model": "kling2.1大师",- "type": "视频生成",- "duration": "5秒",- "resolution": "1080p",- "notes": "",- "credits": "100",- "price": "10元",- "channel": "yun"+ model: 'kling2.1大师'+ type: '视频生成'+ duration: '5秒'+ resolution: '1080p'+ notes: ''+ credits: '100'+ price: '10元'+ channel: 'yun'},{- "model": "kling2.1大师",- "type": "视频生成",- "duration": "10秒",- "resolution": "1080p",- "notes": "",- "credits": "200",- "price": "20元",- "channel": "yun"+ model: 'kling2.1大师'+ type: '视频生成'+ duration: '10秒'+ resolution: '1080p'+ notes: ''+ credits: '200'+ price: '20元'+ channel: 'yun'},{- "model": "wan2.2-plus",- "type": "视频生成",- "duration": "5秒",- "resolution": "480p",- "notes": "",- "credits": "70",- "price": "0.7元",- "channel": "yun"+ model: 'wan2.2-plus'+ type: '视频生成'+ duration: '5秒'+ resolution: '480p'+ notes: ''+ credits: '70'+ price: '0.7元'+ channel: 'yun'},{- "model": "wan2.2-plus",- "type": "视频生成",- "duration": "5秒",- "resolution": "1080p",- "notes": "",- "credits": "35",- "price": "3.5元",- "channel": "yun"+ model: 'wan2.2-plus'+ type: '视频生成'+ duration: '5秒'+ resolution: '1080p'+ notes: ''+ credits: '35'+ price: '3.5元'+ channel: 'yun'},{- "model": "wan2.1-turbo(14b)",- "type": "视频生成",- "duration": "5秒",- "resolution": "720p",- "notes": "不要使用火山渠道",- "credits": "12",- "price": "1.2元",- "channel": "yun"+ model: 'wan2.1-turbo(14b)'+ type: '视频生成'+ duration: '5秒'+ resolution: '720p'+ notes: '不要使用火山渠道'+ credits: '12'+ price: '1.2元'+ channel: 'yun'},{- "model": "wan2.1-plus",- "type": "视频生成",- "duration": "5秒",- "resolution": "720p",- "notes": "支持首尾帧",- "credits": "35",- "price": "3.5元",- "channel": "yun"+ model: 'wan2.1-plus'+ type: '视频生成'+ duration: '5秒'+ resolution: '720p'+ notes: '支持首尾帧'+ credits: '35'+ price: '3.5元'+ channel: 'yun'},{- "model": "wanx2.1-vace-plus",- "type": "视频生成",- "duration": "5秒",- "resolution": "720p",- "notes": "视频编辑",- "credits": "35",- "price": "3.5元",- "channel": "yun"+ model: 'wanx2.1-vace-plus'+ type: '视频生成'+ duration: '5秒'+ resolution: '720p'+ notes: '视频编辑'+ credits: '35'+ price: '3.5元'+ channel: 'yun'},{- "model": "seedance-1.0-pro",- "type": "视频生成",- "duration": "5秒",- "resolution": "480p",- "notes": "支持10秒",- "credits": "7.2",- "price": "0.72元",- "channel": "yun"+ model: 'seedance-1.0-pro'+ type: '视频生成'+ duration: '5秒'+ resolution: '480p'+ notes: '支持10秒'+ credits: '7.2'+ price: '0.72元'+ channel: 'yun'},{- "model": "seedance-1.0-pro",- "type": "视频生成",- "duration": "5秒",- "resolution": "720p",- "notes": "10秒价格翻倍",- "credits": "16.4",- "price": "1.64元",- "channel": "yun"+ model: 'seedance-1.0-pro'+ type: '视频生成'+ duration: '5秒'+ resolution: '720p'+ notes: '10秒价格翻倍'+ credits: '16.4'+ price: '1.64元'+ channel: 'yun'},{- "model": "seedance-1.0-pro",- "type": "视频生成",- "duration": "5秒",- "resolution": "1080p",- "notes": "",- "credits": "36.7",- "price": "3.67元",- "channel": "yun"+ model: 'seedance-1.0-pro'+ type: '视频生成'+ duration: '5秒'+ resolution: '1080p'+ notes: ''+ credits: '36.7'+ price: '3.67元'+ channel: 'yun'},{- "model": "seedance-1.0-lite",- "type": "视频生成",- "duration": "5秒",- "resolution": "480p",- "notes": "支持首尾帧",- "credits": "5",- "price": "0.5元",- "channel": "yun"+ model: 'seedance-1.0-lite'+ type: '视频生成'+ duration: '5秒'+ resolution: '480p'+ notes: '支持首尾帧'+ credits: '5'+ price: '0.5元'+ channel: 'yun'},{- "model": "seedance-1.0-lite",- "type": "视频生成",- "duration": "5秒",- "resolution": "720p",- "notes": "支持10秒",- "credits": "11",- "price": "1.1元",- "channel": "yun"+ model: 'seedance-1.0-lite'+ type: '视频生成'+ duration: '5秒'+ resolution: '720p'+ notes: '支持10秒'+ credits: '11'+ price: '1.1元'+ channel: 'yun'},{- "model": "seedance-1.0-lite",- "type": "视频生成",- "duration": "5秒",- "resolution": "1080p",- "notes": "10秒价格翻倍",- "credits": "25",- "price": "2.5元",- "channel": "yun"- }+ model: 'seedance-1.0-lite'+ type: '视频生成'+ duration: '5秒'+ resolution: '1080p'+ notes: '10秒价格翻倍'+ credits: '25'+ price: '2.5元'+ channel: 'yun'+ },]}- },- "creditExpiry": {- "question": "我的积分会过期吗?",- "answer": "我们的积分过期机制非常宽松。积分自获取之日起 12 个自然月后才会过期,您有充足的时间使用。"- },- "moreCredits": {- "question": "如果我需要更多积分怎么办?",- "answer": "您可以通过每天发布内容来获取免费积分。同时,也可以通过开通会员或直接购买积分的方式获得更多积分。"- },- "checkCredits": {- "question": "如何查看我的积分情况?",- "answer": "点击您的积分余额,即可查看积分的变更明细。"- },- "hiddenFees": {- "question": "是否存在隐藏费用?",- "answer": "没有。您所看到的价格就是您最终支付的价格,不会有任何额外的隐性收费。"- },- "refundPolicy": {- "question": "有退款政策吗?",- "answer": "我们提供7天无理由退款保证。如果您对服务不满意,可以在购买后7天内申请全额退款。"}+ creditExpiry: {+ question: '我的积分会过期吗?'+ answer: '我们的积分过期机制非常宽松。积分自获取之日起 12 个自然月后才会过期,您有充足的时间使用。'+ }+ moreCredits: {+ question: '如果我需要更多积分怎么办?'+ answer: '您可以通过每天发布内容来获取免费积分。同时,也可以通过开通会员或直接购买积分的方式获得更多积分。'+ }+ checkCredits: {+ question: '如何查看我的积分情况?'+ answer: '点击您的积分余额,即可查看积分的变更明细。'+ }+ hiddenFees: {+ question: '是否存在隐藏费用?'+ answer: '没有。您所看到的价格就是您最终支付的价格,不会有任何额外的隐性收费。'+ }+ refundPolicy: {+ question: '有退款政策吗?'+ answer: '我们提供7天无理由退款保证。如果您对服务不满意,可以在购买后7天内申请全额退款。'+ }+ }+ }+ 'profile': {+ personalInfo: '个人信息'+ orderManagement: '订单管理'+ myOrders: '购买记录'+ mySubscriptions: '我的订阅'+ plusMember: 'PLUS会员'+ vipUserGreeting: '尊敬的VIP用户,您已解锁全部会员权益'+ vipDescription: '开通会员解锁全部功能,立享8种权益'+ activateNow: '立即开通'+ modifyUsername: '修改用户名'+ logout: '退出登录'+ userId: '用户ID'+ username: '用户名'+ email: '邮箱'+ accountStatus: '账号状态'+ normal: '正常'+ disabled: '禁用'+ memberType: '会员类型'+ memberExpireTime: '会员到期时间'+ nonMember: '非会员'+ monthlyMember: '月度会员'+ yearlyMember: '年度会员'+ unknown: '未知'+ upgradeCallToAction: '开通PLUS会员,体验更多高级功能!'+ activatePlusMember: '立即开通PLUS会员'+ orderId: '订单ID'+ packageType: '套餐类型'+ amount: '金额'+ status: '状态'+ createTime: '创建时间'+ expireTime: '过期时间'+ actions: '操作'+ viewDetails: '查看详情'+ goToPay: '去支付'+ subscriptionId: '订阅ID'+ cancelSubscription: '退订'+ cancelSubscriptionConfirm: '确定要退订吗?退订后将无法享受会员权益。'+ confirm: '确定'+ cancel: '取消'+ orderDetails: '订单详情'+ close: '关闭'+ goToPayment: '前往支付'+ internalId: '内部ID'+ subscriptionMode: '订阅模式'+ paymentMethod: '支付方式'+ refundedAmount: '已退款金额'+ paymentIntent: 'Payment Intent'+ paymentLink: '支付链接'+ openPaymentPage: '打开支付页面'+ totalRecords: '共 {total} 条记录'+ loading: '加载中...'+ noOrderRecords: '暂无订单记录'+ noSubscriptionRecords: '暂无订阅记录'+ pleaseLoginFirst: '请先登录'+ logoutSuccess: '退出登录成功'+ updateSuccess: '更新成功'+ updateFailed: '更新失败'+ getUserInfoFailed: '获取用户信息失败'+ getOrderListFailed: '获取订单列表失败'+ getSubscriptionListFailed: '获取订阅列表失败'+ refundSubmitted: '退款申请已提交'+ refundFailed: '退款失败'+ unsubscribeSuccess: '退订成功'+ unsubscribeFailed: '退订失败'+ getOrderDetailFailed: '获取订单详情失败'+ pleaseEnterUsername: '请输入用户名'+ usernameLengthMin: '用户名长度不能小于2个字符'+ usernameLengthMax: '用户名长度不能超过20个字符'+ confirmModify: '确认修改'+ monthlySubscription: '月度订阅'+ yearlySubscription: '年度订阅'+ oneTimeMonthly: '一次性月度'+ oneTimeYearly: '一次性年度'+ paymentSuccess: '已完成'+ waitingForPayment: '待支付'+ refundSuccess: '退款成功'+ orderCancelled: '订单取消'+ subscriptionSuccess: '订阅成功'+ subscriptionCancelled: '已取消'+ subscription: '订阅'+ quantity: '数量'+ orderExpired: '已过期'+ cancelTime: '取消时间'+ trialEndTime: '试用结束时间'+ willCancelAtPeriodEnd: '将于期末取消'+ subscriptionPastDue: '逾期'+ copySuccess: '已复制'+ resumeSubscription: '恢复订阅'+ resumeSuccess: '恢复成功'+ vipBenefits: {+ exclusiveBadge: '专属标识'+ advancedFeatures: '高级功能'+ memberGift: '会员礼包'+ prioritySupport: '优先支持'+ discount: '优惠折扣'+ unlimitedTime: '无限时长'+ fastExperience: '极速体验'+ morePrivileges: '更多特权'+ }+ points: {+ title: '积分记录'+ myPoints: '我的积分'+ pointsDescription: '查看您的积分变动记录和使用情况'+ pointsChange: '积分变动'+ balance: '余额'+ changeType: '变动类型'+ description: '描述'+ time: '时间'+ earn: '获得'+ spend: '消费'+ refund: '退还'+ expire: '过期'+ aiService: 'AI服务'+ userRegister: '用户注册'+ publish: '发布作品'+ point: '积分交易'+ noPointsRecords: '暂无积分记录'+ totalRecords: '共 {{total}} 条记录'+ }+ pointsPurchase: {+ title: '购买积分'+ currentPoints: '当前积分'+ selectAmount: '选择购买数量'+ description: '每1000积分售价15美元,滑动选择购买数量'+ purchasePoints: '购买积分'+ totalPrice: '总价'+ buyNow: '立即购买'+ paying: '支付中...'+ paymentTip: '支付完成后,请点击下方按钮确认支付状态'+ confirmPayment: '我已支付'+ purchaseSuccess: '积分购买成功!'+ paymentPending: '订单尚未支付成功,请稍后再试'+ orderRefunded: '订单已退款'+ orderCancelled: '订单已取消'+ orderUnknown: '订单状态未知,请稍后再试'+ queryFailed: '查询订单状态失败,请重试'+ createOrderFailed: '创建支付订单失败,请重试'+ redirectingToPayment: '正在跳转到支付页面...'+ publish: '发布'+ publishDesc: '发布内容获得积分奖励'+ vip: '开通会员'+ vipDesc: '会员专享积分福利'+ buyPoints: '购买积分'+ buyPointsDesc: '直接充值获得积分'+ getPointsMethods: '获取积分的方法:'+ }+ freeTrial: {+ title: '🎉 免费会员体验'+ congratulations: '恭喜您获得3天免费会员体验!'+ description: '作为新用户,您可以享受3天的免费会员权益,体验所有高级功能,包括:'+ unlimitedAI: '✓ 无限制AI生成'+ priorityProcessing: '✓ 优先处理'+ advancedModels: '✓ 高级模型'+ dedicatedSupport: '✓ 专属客服'+ noAds: '✓ 无广告体验'+ morePrivileges: '✓ 更多特权'+ completelyFree: '🎁 完全免费,无需支付任何费用'+ claimNow: '立即领取'+ later: '稍后再说'+ }+ vipHonorText: '您是尊贵的VIP用户'+ inviteCode: '邀请码'+ edit: '编辑'+ copy: '复制'+ cancelAccount: '注销账户'+ cancelAccountWarning: '注销账户是不可逆的操作,一旦注销,您的所有数据将被永久删除,包括:'+ cancelAccountDataList: '个人资料和设置,所有发布的内容,积分和会员权益,订单和支付记录'+ cancelAccountCaution: '请谨慎操作!'+ cancelAccountSecurity: '为了您的账户安全,请先获取验证码进行身份验证。'+ verificationCode: '验证码'+ pleaseEnterVerificationCode: '请输入验证码'+ getVerificationCode: '获取验证码'+ resendAfter: 's后重发'+ confirmCancel: '确认注销'+ stats: {+ totalEarned: '累计赚钱'+ balance: '当前余额'+ points: '可用积分'+ coupons: '优惠券'+ currencyYuan: '元'+ }+ deleteAccount: {+ title: '删除你的账户'+ desc: '删除账户后,你将无法继续使用 Aitoearn 服务,我们也会永久删除你的个人数据。'+ apply: '申请注销'+ }+ messages: {+ getPointsRecordsFailed: '获取积分记录失败'+ verificationCodeSent: '验证码已发送'+ getVerificationCodeFailed: '获取验证码失败'+ accountCancelledSuccess: '账户注销成功'+ priceId: '价格ID'+ }+ memberTypes: {+ oneTime: '一次性'+ trial: '试用'+ }+ }+ 'publish': {+ title: '发布作品'+ confirmClose: {+ title: '确认关闭'+ content: '关闭后,已填写的内容将丢失,是否确认关闭?'+ }+ buttons: {+ customizePerAccount: '自定义每个账户'+ cancelPublish: '取消发布'+ schedulePublish: '定时发布'+ publishNow: '立即发布'+ copyLink: '复制链接'+ delete: '删除'+ }+ tips: {+ workSaved: '你的工作被保存了,请选择账号,继续发布'+ pcNotSupported: 'Web不支持该平台,请下载App进行发布'+ accountOffline: '该账号已离线,无法发布'+ tiktokForbidden: '该平台暂不支持发布'+ xhsOffline: '小红书账号已离线,请下载App进行操作'+ selectAccount: '请选择要发布的账户'+ }+ status: {+ publishFailed: '发布失败'+ publishing: '发布中'+ publishSuccess: '发布成功'+ waitingPublish: '等待发布'+ unknown: '未知状态'+ }+ creationInfo: '您于 {{date}} 创建了此内容'+ form: {+ title: '标题'+ titlePlaceholder: '请输入标题'+ partition: '分区'+ partitionPlaceholder: '请选择分区'+ type: '类型'+ original: '原创'+ reprint: '转载'+ source: '转载来源'+ sourcePlaceholder: '转载视频请注明来源、时间、地点(例:转自https://www.xxxx.com/yyyy)'+ page: '页面'+ pagePlaceholder: '请选择页面'+ privacyStatus: '隐私状态'+ selectPrivacyStatus: '请选择隐私状态'+ public: '公开'+ unlisted: '不公开'+ private: '私人'+ region: '国区'+ regionPlaceholder: '请选择国区'+ license: '许可证'+ licensePlaceholder: '请选择许可证'+ standardYouTubeLicense: '标准 YouTube 许可证'+ creativeCommonsLicense: '知识共享许可证'+ category: '视频分类'+ categoryPlaceholder: '请选择视频分类'+ categoryPlaceholderDisabled: '请先选择国区'+ board: 'Board'+ boardPlaceholder: '请选择Board'+ location: '位置'+ searchLocation: '搜索位置'+ selectLocation: '请选择位置'+ description: '描述'+ descriptionPlaceholder: '开始写'+ }+ writingAssistant: '写作助手'+ upload: {+ finishingUp: '正在完成...'+ uploadImageOrVideo: '上传图片或视频'+ uploadImage: '请上传图片'+ uploadVideo: '请上传视频'+ dragAndSelect: '拖放 & 选择图片或视频'+ selectFile: '选择文件'+ uploadLocal: '上传本地图片或视频'+ progress: '上传进度 {{percent}}%'+ completed: '上传完成(100%)'+ failed: '上传失败'+ canceled: '上传已取消'+ }+ validation: {+ facebookStoryNoDes: 'Facebook Story不支持填写描述'+ facebookReelNoImage: 'Facebook Reel不支持上传图片'+ instagramStoryNoDes: 'Instagram Story不支持填写描述'+ instagramReelNoImage: 'Instagram Reel不支持上传图片'+ instagramPostNoVideo: 'Instagram post不支持上传视频'+ titleMaxExceeded: '{{platformName}}标题最多{{maxCount}}字'+ descriptionMaxExceeded: '{{platformName}}描述最多{{maxCount}}字'+ descriptionRequired: '描述是必须的'+ uploadImageOrVideo: '请上传图片或视频'+ uploadImage: '请上传图片'+ uploadVideo: '请上传视频'+ topicMaxExceeded: '{{platformName}}话题最多不能超过{{maxCount}}个'+ topicFormatError: '描述中的话题必须使用空格分割,如:"#话题1 #话题2"'+ titleRequired: '标题是必须的'+ topicRequired: '话题是必须的'+ partitionRequired: '您必须选择分区!'+ sourceRequired: '转载时必须填写转载来源!'+ pageRequired: '您必须选择页面!'+ boardRequired: '您必须选择Board!'+ coverSizeError: '封面最小尺寸400*400!'+ imageOnly: '已有图片,仅可继续上传图片,不能上传视频!'+ videoOnly: '已有视频,仅可继续上传视频,不能上传图片!'+ imageVideoMixed: '图片和视频不能混合上传!'+ onlyImageOrVideo: '只能上传图片或视频文件!'+ videoMaxExceeded: '视频上传数量不能大于{{maxCount}}'+ imageMaxExceeded: '图片上传数量不能大于{{maxCount}}'+ instagramImageValidation: 'Instagram Post 图片比例需在 4:5 ~ 1.91:1 范围内。'+ instagramReelAspectRatio: 'Instagram Reel 视频宽高比需在 4:5 ~ 9:16 范围内。'+ facebookReelDuration: 'Facebook Reel视频时长需为3–90秒'+ facebookStoryDuration: 'Facebook Story视频时长需为3–4小时'+ instagramVideoSize: 'Instagram视频大小不能超过100MB'+ instagramReelDuration: 'Instagram Reel视频时长需为5秒–15分钟'+ instagramStoryDuration: 'Instagram Story视频时长需为3–60秒'+ threadsVideoSize: 'Threads视频大小不能超过1GB'+ threadsVideoDuration: 'Threads视频时长需为0秒以上且不超过5分钟'+ threadsImageMin: 'Threads图片至少需要两张'+ pinterestVideoDuration: 'Pinterest视频时长需为4秒–15分钟'+ pinterestVideoSize: 'Pinterest视频大小不能超过1GB'+ tiktokVideoDuration: 'TikTok视频时长需为3秒至10分钟'+ tiktokVideoSize: 'TikTok视频大小不能超过1GB'+ tiktokVideoMinResolution: 'TikTok视频最小分辨率为360x360'+ twitterVideoDuration: 'Twitter视频时长需为0.5秒–140秒'+ twitterVideoSize: 'Twitter视频大小不能超过512MB'+ facebookPostImageSize: 'Facebook Post图片大小不能超过10MB'+ facebookStoryImageSize: 'Facebook Story图片大小不能超过4MB'+ instagramImageSize: 'Instagram图片大小不能超过8MB'+ pinterestImageSize: 'Pinterest图片大小不能超过10MB'+ tiktokImageSize: 'TikTok图片大小不能超过20MB'+ tiktokImageResolution: 'TikTok图片最大分辨率为1080x1920或1920x1080'+ twitterImageSize: 'Twitter图片大小不能超过5MB'+ twitterImageResolution: 'Twitter图片最大分辨率为8192x8192'+ youtubeResolutionSuggestion: '建议视频分辨率:1920×1080(16:9)或 1080×1920(9:16)。'+ youtubeVideoSize: 'YouTube视频大小不能超过256GB'+ youtubeVideoDuration: 'YouTube视频时长不能超过12小时'+ categoryRequired: '您必须选择视频分类!'+ kwaiResolutionSuggestion: '推荐视频分辨率:1080x1920(竖屏)。'+ kwaiDurationSuggestion: '视频时长建议:15秒-3分钟。'+ }+ preview: {+ title: '预览'+ emptyDescription: '在这里看到你的作品预览'+ videoInfo: {+ filename: '文件名'+ format: '格式'+ resolution: '分辨率'+ size: '大小'+ duration: '时长'+ }+ }+ draft: {+ selectDraft: '选择草稿'+ selectDraftGroup: '选择草稿箱组'+ selectDraftItem: '选择草稿'+ noDraftGroups: '暂无草稿箱组'+ noDrafts: '该组暂无草稿'+ backToGroups: '返回草稿箱组'+ selectDraftSuccess: '草稿已应用'+ imageGroup: '图文组'+ videoGroup: '视频组'+ selectLibrary: '选择素材库'+ selectLibraryItem: '选择素材'+ selectLibraryGroup: '选择素材库组'+ noLibraryGroups: '暂无素材库组'+ backToLibraryGroups: '返回素材库组'+ noLibraryItems: '该组暂无素材'+ selectLibrarySuccess: '素材已应用'+ }+ actions: {+ selectMaterial: '选择素材'+ selectDraft: '选择草稿'+ cropCover: '裁剪封面'+ contentModeration: '内容安全检测'+ checkingContent: '检测中...'+ contentSafe: '内容安全'+ riskLevel: '等级:'+ contentUnsafe: '内容不安全'+ preview: '点击查看'}- },- "profile": {- "personalInfo": "个人信息",- "orderManagement": "订单管理",- "myOrders": "购买记录",- "mySubscriptions": "我的订阅",- "plusMember": "PLUS会员",- "vipUserGreeting": "尊敬的VIP用户,您已解锁全部会员权益",- "vipDescription": "开通会员解锁全部功能,立享8种权益",- "activateNow": "立即开通",- "modifyUsername": "修改用户名",- "logout": "退出登录",- "userId": "用户ID",- "username": "用户名",- "email": "邮箱",- "accountStatus": "账号状态",- "normal": "正常",- "disabled": "禁用",- "memberType": "会员类型",- "memberExpireTime": "会员到期时间",- "nonMember": "非会员",- "monthlyMember": "月度会员",- "yearlyMember": "年度会员",- "unknown": "未知",- "upgradeCallToAction": "开通PLUS会员,体验更多高级功能!",- "activatePlusMember": "立即开通PLUS会员",- "orderId": "订单ID",- "packageType": "套餐类型",- "amount": "金额",- "status": "状态",- "createTime": "创建时间",- "expireTime": "过期时间",- "actions": "操作",- "viewDetails": "查看详情",- "goToPay": "去支付",- "subscriptionId": "订阅ID",- "cancelSubscription": "退订",- "cancelSubscriptionConfirm": "确定要退订吗?退订后将无法享受会员权益。",- "confirm": "确定",- "cancel": "取消",- "orderDetails": "订单详情",- "close": "关闭",- "goToPayment": "前往支付",- "internalId": "内部ID",- "subscriptionMode": "订阅模式",- "paymentMethod": "支付方式",- "refundedAmount": "已退款金额",- "paymentIntent": "Payment Intent",- "paymentLink": "支付链接",- "openPaymentPage": "打开支付页面",- "totalRecords": "共 {total} 条记录",- "loading": "加载中...",- "noOrderRecords": "暂无订单记录",- "noSubscriptionRecords": "暂无订阅记录",- "pleaseLoginFirst": "请先登录",- "logoutSuccess": "退出登录成功",- "updateSuccess": "更新成功",- "updateFailed": "更新失败",- "getUserInfoFailed": "获取用户信息失败",- "getOrderListFailed": "获取订单列表失败",- "getSubscriptionListFailed": "获取订阅列表失败",- "refundSubmitted": "退款申请已提交",- "refundFailed": "退款失败",- "unsubscribeSuccess": "退订成功",- "unsubscribeFailed": "退订失败",- "getOrderDetailFailed": "获取订单详情失败",- "pleaseEnterUsername": "请输入用户名",- "usernameLengthMin": "用户名长度不能小于2个字符",- "usernameLengthMax": "用户名长度不能超过20个字符",- "confirmModify": "确认修改",- "monthlySubscription": "月度订阅",- "yearlySubscription": "年度订阅",- "oneTimeMonthly": "一次性月度",- "oneTimeYearly": "一次性年度",- "paymentSuccess": "已完成",- "waitingForPayment": "待支付",- "refundSuccess": "退款成功",- "orderCancelled": "订单取消",- "subscriptionSuccess": "订阅成功",- "subscriptionCancelled": "已取消",- "subscription": "订阅",- "quantity": "数量",- "orderExpired": "已过期",- "cancelTime": "取消时间",- "trialEndTime": "试用结束时间",- "willCancelAtPeriodEnd": "将于期末取消",- "subscriptionPastDue": "逾期",- "copySuccess": "已复制",- "resumeSubscription": "恢复订阅",- "resumeSuccess": "恢复成功",- "vipBenefits": {- "exclusiveBadge": "专属标识",- "advancedFeatures": "高级功能",- "memberGift": "会员礼包",- "prioritySupport": "优先支持",- "discount": "优惠折扣",- "unlimitedTime": "无限时长",- "fastExperience": "极速体验",- "morePrivileges": "更多特权"- },- "points": {- "title": "积分记录",- "myPoints": "我的积分",- "pointsDescription": "查看您的积分变动记录和使用情况",- "pointsChange": "积分变动",- "balance": "余额",- "changeType": "变动类型",- "description": "描述",- "time": "时间",- "earn": "获得",- "spend": "消费",- "refund": "退还",- "expire": "过期",- "aiService": "AI服务",- "userRegister": "用户注册",- "publish": "发布作品",- "point": "积分交易",- "noPointsRecords": "暂无积分记录",- "totalRecords": "共 {{total}} 条记录"- },- "pointsPurchase": {- "title": "购买积分",- "currentPoints": "当前积分",- "selectAmount": "选择购买数量",- "description": "每1000积分售价15美元,滑动选择购买数量",- "purchasePoints": "购买积分",- "totalPrice": "总价",- "buyNow": "立即购买",- "paying": "支付中...",- "paymentTip": "支付完成后,请点击下方按钮确认支付状态",- "confirmPayment": "我已支付",- "purchaseSuccess": "积分购买成功!",- "paymentPending": "订单尚未支付成功,请稍后再试",- "orderRefunded": "订单已退款",- "orderCancelled": "订单已取消",- "orderUnknown": "订单状态未知,请稍后再试",- "queryFailed": "查询订单状态失败,请重试",- "createOrderFailed": "创建支付订单失败,请重试",- "redirectingToPayment": "正在跳转到支付页面...",- "publish": "发布",- "publishDesc": "发布内容获得积分奖励",- "vip": "开通会员",- "vipDesc": "会员专享积分福利",- "buyPoints": "购买积分",- "buyPointsDesc": "直接充值获得积分",- "getPointsMethods": "获取积分的方法:"- },- "freeTrial": {- "title": "🎉 免费会员体验",- "congratulations": "恭喜您获得3天免费会员体验!",- "description": "作为新用户,您可以享受3天的免费会员权益,体验所有高级功能,包括:",- "unlimitedAI": "✓ 无限制AI生成",- "priorityProcessing": "✓ 优先处理",- "advancedModels": "✓ 高级模型",- "dedicatedSupport": "✓ 专属客服",- "noAds": "✓ 无广告体验",- "morePrivileges": "✓ 更多特权",- "completelyFree": "🎁 完全免费,无需支付任何费用",- "claimNow": "立即领取",- "later": "稍后再说"- },- "vipHonorText": "您是尊贵的VIP用户",- "inviteCode": "邀请码",- "edit": "编辑",- "copy": "复制",- "cancelAccount": "注销账户",- "cancelAccountWarning": "注销账户是不可逆的操作,一旦注销,您的所有数据将被永久删除,包括:",- "cancelAccountDataList": "个人资料和设置,所有发布的内容,积分和会员权益,订单和支付记录",- "cancelAccountCaution": "请谨慎操作!",- "cancelAccountSecurity": "为了您的账户安全,请先获取验证码进行身份验证。",- "verificationCode": "验证码",- "pleaseEnterVerificationCode": "请输入验证码",- "getVerificationCode": "获取验证码",- "resendAfter": "s后重发",- "confirmCancel": "确认注销",- "stats": {- "totalEarned": "累计赚钱",- "balance": "当前余额",- "points": "可用积分",- "coupons": "优惠券",- "currencyYuan": "元"- },- "deleteAccount": {- "title": "删除你的账户",- "desc": "删除账户后,你将无法继续使用 Aitoearn 服务,我们也会永久删除你的个人数据。",- "apply": "申请注销"- },- "messages": {- "getPointsRecordsFailed": "获取积分记录失败",- "verificationCodeSent": "验证码已发送",- "getVerificationCodeFailed": "获取验证码失败",- "accountCancelledSuccess": "账户注销成功",- "priceId": "价格ID"- },- "memberTypes": {- "oneTime": "一次性",- "trial": "试用"- }- },- "publish": {- "title": "发布作品",- "confirmClose": {- "title": "确认关闭",- "content": "关闭后,已填写的内容将丢失,是否确认关闭?"- },- "buttons": {- "customizePerAccount": "自定义每个账户",- "cancelPublish": "取消发布",- "schedulePublish": "定时发布",- "publishNow": "立即发布",- "copyLink": "复制链接",- "delete": "删除"- },- "tips": {- "workSaved": "你的工作被保存了,请选择账号,继续发布",- "pcNotSupported": "Web不支持该平台,请下载App进行发布",- "accountOffline": "该账号已离线,无法发布",- "tiktokForbidden": "该平台暂不支持发布",- "xhsOffline": "小红书账号已离线,请下载App进行操作",- "selectAccount": "请选择要发布的账户"- },- "status": {- "publishFailed": "发布失败",- "publishing": "发布中",- "publishSuccess": "发布成功",- "waitingPublish": "等待发布",- "unknown": "未知状态"- },- "creationInfo": "您于 {{date}} 创建了此内容",- "form": {- "title": "标题",- "titlePlaceholder": "请输入标题",- "partition": "分区",- "partitionPlaceholder": "请选择分区",- "type": "类型",- "original": "原创",- "reprint": "转载",- "source": "转载来源",- "sourcePlaceholder": "转载视频请注明来源、时间、地点(例:转自https://www.xxxx.com/yyyy)",- "page": "页面",- "pagePlaceholder": "请选择页面",- "privacyStatus": "隐私状态",- "selectPrivacyStatus": "请选择隐私状态",- "public": "公开",- "unlisted": "不公开",- "private": "私人",- "region": "国区",- "regionPlaceholder": "请选择国区",- "license": "许可证",- "licensePlaceholder": "请选择许可证",- "standardYouTubeLicense": "标准 YouTube 许可证",- "creativeCommonsLicense": "知识共享许可证",- "category": "视频分类",- "categoryPlaceholder": "请选择视频分类",- "categoryPlaceholderDisabled": "请先选择国区",- "board": "Board",- "boardPlaceholder": "请选择Board",- "location": "位置",- "searchLocation": "搜索位置",- "selectLocation": "请选择位置",- "description": "描述",- "descriptionPlaceholder": "开始写"- },- "writingAssistant": "写作助手",- "upload": {- "finishingUp": "正在完成...",- "uploadImageOrVideo": "上传图片或视频",- "uploadImage": "请上传图片",- "uploadVideo": "请上传视频",- "dragAndSelect": "拖放 & 选择图片或视频",- "selectFile": "选择文件",- "uploadLocal": "上传本地图片或视频",- "progress": "上传进度 {{percent}}%",- "completed": "上传完成(100%)",- "failed": "上传失败",- "canceled": "上传已取消"- },- "validation": {- "facebookStoryNoDes": "Facebook Story不支持填写描述",- "facebookReelNoImage": "Facebook Reel不支持上传图片",- "instagramStoryNoDes": "Instagram Story不支持填写描述",- "instagramReelNoImage": "Instagram Reel不支持上传图片",- "instagramPostNoVideo": "Instagram post不支持上传视频",- "titleMaxExceeded": "{{platformName}}标题最多{{maxCount}}字",- "descriptionMaxExceeded": "{{platformName}}描述最多{{maxCount}}字",- "descriptionRequired": "描述是必须的",- "uploadImageOrVideo": "请上传图片或视频",- "uploadImage": "请上传图片",- "uploadVideo": "请上传视频",- "topicMaxExceeded": "{{platformName}}话题最多不能超过{{maxCount}}个",- "topicFormatError": "描述中的话题必须使用空格分割,如:\"#话题1 #话题2\"",- "titleRequired": "标题是必须的",- "topicRequired": "话题是必须的",- "partitionRequired": "您必须选择分区!",- "sourceRequired": "转载时必须填写转载来源!",- "pageRequired": "您必须选择页面!",- "boardRequired": "您必须选择Board!",- "coverSizeError": "封面最小尺寸400*400!",- "imageOnly": "已有图片,仅可继续上传图片,不能上传视频!",- "videoOnly": "已有视频,仅可继续上传视频,不能上传图片!",- "imageVideoMixed": "图片和视频不能混合上传!",- "onlyImageOrVideo": "只能上传图片或视频文件!",- "videoMaxExceeded": "视频上传数量不能大于{{maxCount}}",- "imageMaxExceeded": "图片上传数量不能大于{{maxCount}}",- "instagramImageValidation": "Instagram Post 图片比例需在 4:5 ~ 1.91:1 范围内。",- "instagramReelAspectRatio": "Instagram Reel 视频宽高比需在 4:5 ~ 9:16 范围内。",- "facebookReelDuration": "Facebook Reel视频时长需为3–90秒",- "facebookStoryDuration": "Facebook Story视频时长需为3–4小时",- "instagramVideoSize": "Instagram视频大小不能超过100MB",- "instagramReelDuration": "Instagram Reel视频时长需为5秒–15分钟",- "instagramStoryDuration": "Instagram Story视频时长需为3–60秒",- "threadsVideoSize": "Threads视频大小不能超过1GB",- "threadsVideoDuration": "Threads视频时长需为0秒以上且不超过5分钟",- "threadsImageMin": "Threads图片至少需要两张",- "pinterestVideoDuration": "Pinterest视频时长需为4秒–15分钟",- "pinterestVideoSize": "Pinterest视频大小不能超过1GB",- "tiktokVideoDuration": "TikTok视频时长需为3秒至10分钟",- "tiktokVideoSize": "TikTok视频大小不能超过1GB",- "tiktokVideoMinResolution": "TikTok视频最小分辨率为360x360",- "twitterVideoDuration": "Twitter视频时长需为0.5秒–140秒",- "twitterVideoSize": "Twitter视频大小不能超过512MB",- "facebookPostImageSize": "Facebook Post图片大小不能超过10MB",- "facebookStoryImageSize": "Facebook Story图片大小不能超过4MB",- "instagramImageSize": "Instagram图片大小不能超过8MB",- "pinterestImageSize": "Pinterest图片大小不能超过10MB",- "tiktokImageSize": "TikTok图片大小不能超过20MB",- "tiktokImageResolution": "TikTok图片最大分辨率为1080x1920或1920x1080",- "twitterImageSize": "Twitter图片大小不能超过5MB",- "twitterImageResolution": "Twitter图片最大分辨率为8192x8192",- "youtubeResolutionSuggestion": "建议视频分辨率:1920×1080(16:9)或 1080×1920(9:16)。",- "youtubeVideoSize": "YouTube视频大小不能超过256GB",- "youtubeVideoDuration": "YouTube视频时长不能超过12小时",- "categoryRequired": "您必须选择视频分类!",- "kwaiResolutionSuggestion": "推荐视频分辨率:1080x1920(竖屏)。",- "kwaiDurationSuggestion": "视频时长建议:15秒-3分钟。"- },- "preview": {- "title": "预览",- "emptyDescription": "在这里看到你的作品预览",- "videoInfo": {- "filename": "文件名",- "format": "格式",- "resolution": "分辨率",- "size": "大小",- "duration": "时长"+ messages: {+ authFailedRetry: '授权失败,请重试'+ pleaseInputContent: '请先输入内容'+ contentModerationFailed: '内容安全检测失败,请稍后重试'+ contentModerationError: '内容安全检测失败'+ unsupportedPlatformType: '未支持的平台类型'+ platformNotSupportedDirect: '暂不支持 {{platform}} 平台的直接授权'+ facebookAuthFailed: 'Facebook授权失败'+ accountListRefreshed: '账号列表已刷新'+ refreshAccountListFailed: '刷新账号列表失败'+ authFailed: '授权失败'+ }+ badges: {+ offline: '已离线'+ forbidden: '禁'+ }+ tiktok: {+ creatorInfo: '创作者信息'+ privacy: {+ title: '谁可以观看'+ placeholder: '请选择隐私级别'+ public: '公开'+ friends: '朋友'+ private: '仅自己'+ }+ interactions: {+ title: '允许用户'+ comment: '评论'+ duet: '合拍'+ stitch: '拼接'}- },- "draft": {- "selectDraft": "选择草稿",- "selectDraftGroup": "选择草稿箱组",- "selectDraftItem": "选择草稿",- "noDraftGroups": "暂无草稿箱组",- "noDrafts": "该组暂无草稿",- "backToGroups": "返回草稿箱组",- "selectDraftSuccess": "草稿已应用",- "imageGroup": "图文组",- "videoGroup": "视频组",- "selectLibrary": "选择素材库",- "selectLibraryItem": "选择素材",- "selectLibraryGroup": "选择素材库组",- "noLibraryGroups": "暂无素材库组",- "backToLibraryGroups": "返回素材库组",- "noLibraryItems": "该组暂无素材",- "selectLibrarySuccess": "素材已应用"- },- "actions": {- "selectMaterial": "选择素材",- "selectDraft": "选择草稿",- "cropCover": "裁剪封面",- "contentModeration": "内容安全检测",- "checkingContent": "检测中...",- "contentSafe": "内容安全",- "riskLevel": "等级:",- "contentUnsafe": "内容不安全",- "preview": "点击查看"- },- "messages": {- "authFailedRetry": "授权失败,请重试",- "pleaseInputContent": "请先输入内容",- "contentModerationFailed": "内容安全检测失败,请稍后重试",- "contentModerationError": "内容安全检测失败",- "unsupportedPlatformType": "未支持的平台类型",- "platformNotSupportedDirect": "暂不支持 {{platform}} 平台的直接授权",- "facebookAuthFailed": "Facebook授权失败",- "accountListRefreshed": "账号列表已刷新",- "refreshAccountListFailed": "刷新账号列表失败",- "authFailed": "授权失败"- },- "badges": {- "offline": "已离线",- "forbidden": "禁"- },- "tiktok": {- "creatorInfo": "创作者信息",- "privacy": {- "title": "谁可以观看",- "placeholder": "请选择隐私级别",- "public": "公开",- "friends": "朋友",- "private": "仅自己"- },- "interactions": {- "title": "允许用户",- "comment": "评论",- "duet": "合拍",- "stitch": "拼接"- },- "commercial": {- "title": "披露视频",- "toggle": "开启以披露此视频推广商品或服务以换取价值。",- "yourBrand": "您的品牌 - 您正在推广自己或自己的业务。此内容将被分类为品牌有机内容。",- "brandedContent": "品牌内容 - 您正在推广另一个品牌或第三方。此内容将被分类为品牌内容。"- },- "compliance": {- "default": "发布即表示您同意 TikTok 的音乐使用确认。",- "organic": "发布即表示您同意 TikTok 的音乐使用确认。",- "branded": "发布即表示您同意 TikTok 的品牌内容政策音乐使用确认。",- "both": "发布即表示您同意 TikTok 的品牌内容政策音乐使用确认。"+ commercial: {+ title: '披露视频'+ toggle: '开启以披露此视频推广商品或服务以换取价值。'+ yourBrand: '您的品牌 - 您正在推广自己或自己的业务。此内容将被分类为品牌有机内容。'+ brandedContent: '品牌内容 - 您正在推广另一个品牌或第三方。此内容将被分类为品牌内容。'}- },- "previewvideo": "预览视频",- "record": {- "metrics": {- "views": "查看数",- "comments": "评论数",- "likes": "点赞数",- "shares": "分享数"- },- "viewWork": "查看作品"- }- },- "route": {- "home": "首页",- "accounts": "账户",- "publish": "发布",- "hotContent": "热门内容",- "hotContentNew": "热门内容新",- "download": "下载",- "aiTools": "AI工具",- "tasks": "任务中心",- "interactive": "作品互动",- "engagement": "互动数据",- "dataStatistics": "数据统计",- "navigation": "导航",- "aiRank": "AI热榜"- },- "task": {- "title": "任务中心",- "subtitle": "接受任务,完成任务,获得奖励",- "pendingTasks": "待接受任务",- "acceptedTasks": "已接受任务",- "taskDetails": "任务详情",- "acceptTask": "接受任务",- "completeTask": "完成任务",- "submitTask": "提交任务",- "viewDetails": "查看详情",- "taskProcessing": "任务处理中...",- "acceptingTask": "正在接受任务...",- "publishingTask": "正在发布任务...",- "submittingTask": "正在提交任务...",- "taskCompleted": "任务完成",- "taskStatus": {- "pending": "待完成",- "doing": "已完成",- "accepted": "已接受",- "completed": "已完成",- "rejected": "已拒绝",- "active": "进行中",- "inactive": "已结束"- },- "taskTypes": {- "video": "视频",- "article": "图文",- "article2": "纯文字"- },- "platforms": {- "tiktok": "TikTok",- "youtube": "YouTube",- "twitter": "Twitter",- "bilibili": "哔哩哔哩",- "KWAI": "快手",- "douyin": "抖音",- "xhs": "小红书",- "wxSph": "微信视频号",- "wxGzh": "微信公众号",- "facebook": "Facebook",- "instagram": "Instagram",- "threads": "Threads",- "pinterest": "Pinterest"- },- "taskInfo": {- "publishTime": "发布时间",- "endTime": "结束时间",- "acceptTime": "接受时间",- "submitTime": "提交时间",- "reward": "奖励",- "type": "类型",- "status": "状态",- "description": "描述",- "account": "发布账号",- "currentRecruits": "已接受",- "maxRecruits": "最大招募",- "people": "人",- "firstSubmission": "首次提交"- },- "messages": {- "pleaseLoginFirst": "请先登录以查看任务",- "getPendingTasksFailed": "获取待接受任务失败",- "getAcceptedTasksFailed": "获取已接受任务失败",- "acceptTaskSuccess": "接受任务成功!",- "acceptTaskFailed": "接受任务失败",- "submitTaskSuccess": "任务提交成功!",- "submitTaskFailed": "任务提交失败",- "publishTaskFailed": "发布任务失败",- "getTaskDetailFailed": "获取任务详情失败",- "taskProcessFailed": "任务处理失败",- "noPendingTasks": "暂无待接受任务",- "noAcceptedTasks": "暂无已接受任务",- "noTaskDetails": "暂无任务详情",- "loading": "加载中...",- "totalRecords": "共 {{total}} 条记录",- "pageInfo": "第 {{start}}-{{end}} 条,共 {{total}} 条",- "taskInProgress": "任务正在进行中,可以接受",- "taskEnded": "任务已结束",- "acceptedCount": "已接受 {{current}}/{{max}} 人"- },- "modal": {- "submitTask": "提交任务",- "submitLink": "提交链接",- "submitLinkPlaceholder": "请输入任务完成后的链接",- "submitTip": "请确保您已经完成了任务要求,并提供了正确的提交链接。",- "confirmSubmit": "确认提交",- "cancel": "取消",- "close": "关闭",- "mediaPreview": "媒体预览"- },- "time": {- "justNow": "刚刚",- "minutesAgo": "{{minutes}}分钟前",- "hoursAgo": "{{hours}}小时前",- "daysAgo": "{{days}}天前"- },- "accountSelect": {- "title": "选择账号",- "description": "请选择要用于发布任务的账号",- "accountId": "账号ID",- "redirectingToAccounts": "正在跳转到账户页面,请添加频道账号"- }- },- "translation": {- "title": "AIToEarn官方网站",- "content": "最好用的开源矩阵工具"- },- "vip": {- "title": "PLUS会员",- "description": "开通会员解锁全部功能,立享8种权益",- "activateNow": "立即开通",- "upgrade": "开通会员",- "membership": "会员",- "pleaseLoginFirst": "请先登录",- "paymentOrderCreated": "支付订单创建成功",- "paymentLinkNotFound": "未获取到支付链接",- "createPaymentOrderFailed": "创建支付订单失败",- "createPaymentOrderError": "创建支付订单失败,请稍后重试",- "trialNotice": {- "badge": "🎉 新用户专享",- "description": "选择连续包月或连续包年,可享受7天免费试用期!"- },- "trialText": {- "month": "前7天免费,之后$15/月",- "year": "前7天免费,之后$120/年"- },- "badge": {- "onceMonth": "一次性",- "month": "7天免费试用",- "year": "7天免费试用",- "monthOld": "25%优惠",- "yearOld": "50%优惠"- },- "vipBenefits": {- "exclusiveBadge": "专属标识",- "advancedFeatures": "高级功能",- "memberGift": "会员礼包",- "prioritySupport": "优先支持",- "discount": "优惠折扣",- "unlimitedTime": "无限时长",- "fastExperience": "极速体验",- "morePrivileges": "更多特权"- },- "plans": {- "onceMonth": "一次性月度",- "month": "月度订阅",- "year": "年度订阅"- },- "planTitles": {- "month": "月费会员",- "year": "年费会员",- "onceMonth": "月度会员"- },- "selectDuration": "选择开通时长",- "autoRenewal": "自动续订,随时取消",- "priceUnits": {- "month": "/月",- "year": "/年"- },- "subscriptionManagement": "订阅管理",- "subscriptionPlanManagement": "订阅计划管理",- "subscriptionPlans": "订阅计划",- "purchaseHistory": "购买记录",- "myMembership": "我的会员",- "basicMembership": "基础会员",- "validUntil": "有效期至",- "activatedAutoRenewalPlans": "已开通自动续费套餐",- "activatedAutoRenewalPlansno": "未开通自动续费套餐",- "noAutoRenewalItems": "你还没有开通自动续费项目哦",- "viewMorePlans": "查看更多套餐",- "continuousAnnual": "连续包年",- "oneTimePurchase": "购买",- "alipayPayment": "支付宝支付",- "noMoreContent": "没有内容了",- "previousPage": "上一页",- "nextPage": "下一页",- "pageInfo": "第 {current} 页,共 {total} 页",- "continuousMember": "连续会员",- "singleMember": "单月会员",- "autoRenewalEnabled": "自动续费已开启",- "autoRenewalDisabled": "自动续费未开启",- "nextRenewalDate": "下次续费时间",- "membershipExpires": "有效期至",- "currentPlan": "当前计划",- "modal": {- "title": "免费试用3天会员",- "highlight": "",- "choosePlan": "选择合适你的套餐,或直接",- "buyPoints": "购买积分",- "pointsDetail": "积分详情",- "vipInfo": {- "details": "详情",- "subscription": "订阅管理",- "planType": "计划",- "monthly": "连续包月PLUS会员",- "monthly2": "月度会员",- "yearly": "连续包年PLUS会员",- "yearly2": "年度会员",- "singleMonth": "单月会员",- "trial": "试用中",- "cancelled": "已退订",- "expireTime": "到期时间",- "xufeiTime": "续费时间",- "remainingPoints": "剩余积分",- "buyPoints": "购买积分"- },- "tabs": {- "yearly": "连续包年",- "monthly": "连续包月",- "once": "单月购买"- },- "savings": {- "yearly": "省50%",- "monthly": "省25%"- },- "free": {- "title": "免费",- "price": "0",- "period": "/月",- "forever": "永久",- "currentPlan": "免费计划",- "freePlan": "免费计划",- "points": "60 积分/月",- "features": {- "dailyPoints": "发布:抖音、小红书、视频号、快手、哔哩哔哩、微信公众号、TikTok、YouTube、Facebook、Instagram、Threads、X (Twitter)、Pinterest",- "maxPoints": "互动:抖音、小红书、Facebook、Instagram、Threads",- "videos": "AI工具:核心模型池(gpt-5系列、gemini-2.5-pro/flash、qwen-vl-max、gpt-image-1、FLUX.1 Kontext、seedream/seededit、md2card、萤火卡等)",- "images": "Sora-2 & Nano Banana: 有限使用(按积分/限额)",- "storage": "内容和评论搜索、智能互动"+ compliance: {+ default: '发布即表示您同意 TikTok 的音乐使用确认。'+ organic: '发布即表示您同意 TikTok 的音乐使用确认。'+ branded: '发布即表示您同意 TikTok 的品牌内容政策音乐使用确认。'+ both: '发布即表示您同意 TikTok 的品牌内容政策音乐使用确认。'+ }+ }+ previewvideo: '预览视频'+ record: {+ metrics: {+ views: '查看数'+ comments: '评论数'+ likes: '点赞数'+ shares: '分享数'+ }+ viewWork: '查看作品'+ }+ }+ 'route': {+ home: '首页'+ accounts: '账户'+ publish: '发布'+ hotContent: '热门内容'+ hotContentNew: '热门内容新'+ download: '下载'+ aiTools: 'AI工具'+ tasks: '任务中心'+ interactive: '作品互动'+ engagement: '互动数据'+ dataStatistics: '数据统计'+ navigation: '导航'+ aiRank: 'AI热榜'+ }+ 'task': {+ title: '任务中心'+ subtitle: '接受任务,完成任务,获得奖励'+ pendingTasks: '待接受任务'+ acceptedTasks: '已接受任务'+ taskDetails: '任务详情'+ acceptTask: '接受任务'+ completeTask: '完成任务'+ submitTask: '提交任务'+ viewDetails: '查看详情'+ taskProcessing: '任务处理中...'+ acceptingTask: '正在接受任务...'+ publishingTask: '正在发布任务...'+ submittingTask: '正在提交任务...'+ taskCompleted: '任务完成'+ taskStatus: {+ pending: '待完成'+ doing: '已完成'+ accepted: '已接受'+ completed: '已完成'+ rejected: '已拒绝'+ active: '进行中'+ inactive: '已结束'+ }+ taskTypes: {+ video: '视频'+ article: '图文'+ article2: '纯文字'+ }+ platforms: {+ tiktok: 'TikTok'+ youtube: 'YouTube'+ twitter: 'Twitter'+ bilibili: '哔哩哔哩'+ KWAI: '快手'+ douyin: '抖音'+ xhs: '小红书'+ wxSph: '微信视频号'+ wxGzh: '微信公众号'+ facebook: 'Facebook'+ instagram: 'Instagram'+ threads: 'Threads'+ pinterest: 'Pinterest'+ }+ taskInfo: {+ publishTime: '发布时间'+ endTime: '结束时间'+ acceptTime: '接受时间'+ submitTime: '提交时间'+ reward: '奖励'+ type: '类型'+ status: '状态'+ description: '描述'+ account: '发布账号'+ currentRecruits: '已接受'+ maxRecruits: '最大招募'+ people: '人'+ firstSubmission: '首次提交'+ }+ messages: {+ pleaseLoginFirst: '请先登录以查看任务'+ getPendingTasksFailed: '获取待接受任务失败'+ getAcceptedTasksFailed: '获取已接受任务失败'+ acceptTaskSuccess: '接受任务成功!'+ acceptTaskFailed: '接受任务失败'+ submitTaskSuccess: '任务提交成功!'+ submitTaskFailed: '任务提交失败'+ publishTaskFailed: '发布任务失败'+ getTaskDetailFailed: '获取任务详情失败'+ taskProcessFailed: '任务处理失败'+ noPendingTasks: '暂无待接受任务'+ noAcceptedTasks: '暂无已接受任务'+ noTaskDetails: '暂无任务详情'+ loading: '加载中...'+ totalRecords: '共 {{total}} 条记录'+ pageInfo: '第 {{start}}-{{end}} 条,共 {{total}} 条'+ taskInProgress: '任务正在进行中,可以接受'+ taskEnded: '任务已结束'+ acceptedCount: '已接受 {{current}}/{{max}} 人'+ }+ modal: {+ submitTask: '提交任务'+ submitLink: '提交链接'+ submitLinkPlaceholder: '请输入任务完成后的链接'+ submitTip: '请确保您已经完成了任务要求,并提供了正确的提交链接。'+ confirmSubmit: '确认提交'+ cancel: '取消'+ close: '关闭'+ mediaPreview: '媒体预览'+ }+ time: {+ justNow: '刚刚'+ minutesAgo: '{{minutes}}分钟前'+ hoursAgo: '{{hours}}小时前'+ daysAgo: '{{days}}天前'+ }+ accountSelect: {+ title: '选择账号'+ description: '请选择要用于发布任务的账号'+ accountId: '账号ID'+ redirectingToAccounts: '正在跳转到账户页面,请添加频道账号'+ }+ }+ 'translation': {+ title: 'AIToEarn官方网站'+ content: '最好用的开源矩阵工具'+ }+ 'vip': {+ title: 'PLUS会员'+ description: '开通会员解锁全部功能,立享8种权益'+ activateNow: '立即开通'+ upgrade: '开通会员'+ membership: '会员'+ pleaseLoginFirst: '请先登录'+ paymentOrderCreated: '支付订单创建成功'+ paymentLinkNotFound: '未获取到支付链接'+ createPaymentOrderFailed: '创建支付订单失败'+ createPaymentOrderError: '创建支付订单失败,请稍后重试'+ trialNotice: {+ badge: '🎉 新用户专享'+ description: '选择连续包月或连续包年,可享受7天免费试用期!'+ }+ trialText: {+ month: '前7天免费,之后$15/月'+ year: '前7天免费,之后$120/年'+ }+ badge: {+ onceMonth: '一次性'+ month: '7天免费试用'+ year: '7天免费试用'+ monthOld: '25%优惠'+ yearOld: '50%优惠'+ }+ vipBenefits: {+ exclusiveBadge: '专属标识'+ advancedFeatures: '高级功能'+ memberGift: '会员礼包'+ prioritySupport: '优先支持'+ discount: '优惠折扣'+ unlimitedTime: '无限时长'+ fastExperience: '极速体验'+ morePrivileges: '更多特权'+ }+ plans: {+ onceMonth: '一次性月度'+ month: '月度订阅'+ year: '年度订阅'+ }+ planTitles: {+ month: '月费会员'+ year: '年费会员'+ onceMonth: '月度会员'+ }+ selectDuration: '选择开通时长'+ autoRenewal: '自动续订,随时取消'+ priceUnits: {+ month: '/月'+ year: '/年'+ }+ subscriptionManagement: '订阅管理'+ subscriptionPlanManagement: '订阅计划管理'+ subscriptionPlans: '订阅计划'+ purchaseHistory: '购买记录'+ myMembership: '我的会员'+ basicMembership: '基础会员'+ validUntil: '有效期至'+ activatedAutoRenewalPlans: '已开通自动续费套餐'+ activatedAutoRenewalPlansno: '未开通自动续费套餐'+ noAutoRenewalItems: '你还没有开通自动续费项目哦'+ viewMorePlans: '查看更多套餐'+ continuousAnnual: '连续包年'+ oneTimePurchase: '购买'+ alipayPayment: '支付宝支付'+ noMoreContent: '没有内容了'+ previousPage: '上一页'+ nextPage: '下一页'+ pageInfo: '第 {current} 页,共 {total} 页'+ continuousMember: '连续会员'+ singleMember: '单月会员'+ autoRenewalEnabled: '自动续费已开启'+ autoRenewalDisabled: '自动续费未开启'+ nextRenewalDate: '下次续费时间'+ membershipExpires: '有效期至'+ currentPlan: '当前计划'+ modal: {+ title: '免费试用3天会员'+ highlight: ''+ choosePlan: '选择合适你的套餐,或直接'+ buyPoints: '购买积分'+ pointsDetail: '积分详情'+ vipInfo: {+ details: '详情'+ subscription: '订阅管理'+ planType: '计划'+ monthly: '连续包月PLUS会员'+ monthly2: '月度会员'+ yearly: '连续包年PLUS会员'+ yearly2: '年度会员'+ singleMonth: '单月会员'+ trial: '试用中'+ cancelled: '已退订'+ expireTime: '到期时间'+ xufeiTime: '续费时间'+ remainingPoints: '剩余积分'+ buyPoints: '购买积分'+ }+ tabs: {+ yearly: '连续包年'+ monthly: '连续包月'+ once: '单月购买'+ }+ savings: {+ yearly: '省50%'+ monthly: '省25%'+ }+ free: {+ title: '免费'+ price: '0'+ period: '/月'+ forever: '永久'+ currentPlan: '免费计划'+ freePlan: '免费计划'+ points: '60 积分/月'+ features: {+ dailyPoints: '发布:抖音、小红书、视频号、快手、哔哩哔哩、微信公众号、TikTok、YouTube、Facebook、Instagram、Threads、X (Twitter)、Pinterest'+ maxPoints: '互动:抖音、小红书、Facebook、Instagram、Threads'+ videos: 'AI工具:核心模型池(gpt-5系列、gemini-2.5-pro/flash、qwen-vl-max、gpt-image-1、FLUX.1 Kontext、seedream/seededit、md2card、萤火卡等)'+ images: 'Sora-2 & Nano Banana: 有限使用(按积分/限额)'+ storage: '内容和评论搜索、智能互动'}- },- "plans": {- "goumai": "购买",- "yearly": {- "title": "年度会员",- "bestValue": "最超值",- "price": "12",- "period": "/月",- "originalPrice": "$300/年",- "button": "$144/年 省50%",- "points": "760 积分/月(含60签到积分)",- "description": "每月最多150+次视频生成",- "features": {- "contentReview": "Sora-2:免费且无限",- "dailyPoints": "Nano Banana:免费且无限",- "multiModel": "历史内容导入",- "textToVideo": "免费计划的所有功能",- "aiGeneration": "无限频道连接",- "noWatermark": "内容和评论搜索、智能互动"+ }+ plans: {+ goumai: '购买'+ yearly: {+ title: '年度会员'+ bestValue: '最超值'+ price: '12'+ period: '/月'+ originalPrice: '$300/年'+ button: '$144/年 省50%'+ points: '760 积分/月(含60签到积分)'+ description: '每月最多150+次视频生成'+ features: {+ contentReview: 'Sora-2:免费且无限'+ dailyPoints: 'Nano Banana:免费且无限'+ multiModel: '历史内容导入'+ textToVideo: '免费计划的所有功能'+ aiGeneration: '无限频道连接'+ noWatermark: '内容和评论搜索、智能互动'}- },- "monthly": {- "title": "月度会员",- "price": "19",- "period": "/月",- "originalPrice": "$25/月",- "button": "$19/月 省25%",- "points": "760 积分/月(含60签到积分)",- "description": "每月最多150+次视频生成"- },- "once": {- "title": "一次性月度",- "price": "25",- "period": "/月",- "button": "$25/月",- "points": "760 积分/月(含60签到积分)",- "description": "每月最多150+次视频生成",- "storage": "5G 存储空间"}- },- "trial": "7天免费试用",- "cancelAnytime": "包年可随时取消",- "cancelMonthly": "包月可随时取消"- },- "points": {- "title": "积分详情",- "current": "当前积分",- "remaining": "剩余积分",- "subscribed": "订阅积分",- "recharged": "充值积分",- "gifted": "赠送积分",- "validity": "积分有效期",- "tabs": {- "all": "全部",- "spend": "消耗",- "earn": "获得"- },- "noData": "没有内容了",- "disclaimer": "仅展示近1个月明细,数据更新可能有延时 积分规则",- "recordChange": "积分变动",- "recordTypes": {- "recharge": "充值",- "consume": "消耗",- "gift": "赠送",- "refund": "退款",- "expire": "过期",- "adjust": "调整"+ monthly: {+ title: '月度会员'+ price: '19'+ period: '/月'+ originalPrice: '$25/月'+ button: '$19/月 省25%'+ points: '760 积分/月(含60签到积分)'+ description: '每月最多150+次视频生成'+ }+ once: {+ title: '一次性月度'+ price: '25'+ period: '/月'+ button: '$25/月'+ points: '760 积分/月(含60签到积分)'+ description: '每月最多150+次视频生成'+ storage: '5G 存储空间'+ }+ }+ trial: '7天免费试用'+ cancelAnytime: '包年可随时取消'+ cancelMonthly: '包月可随时取消'+ }+ points: {+ title: '积分详情'+ current: '当前积分'+ remaining: '剩余积分'+ subscribed: '订阅积分'+ recharged: '充值积分'+ gifted: '赠送积分'+ validity: '积分有效期'+ tabs: {+ all: '全部'+ spend: '消耗'+ earn: '获得'+ }+ noData: '没有内容了'+ disclaimer: '仅展示近1个月明细,数据更新可能有延时 积分规则'+ recordChange: '积分变动'+ recordTypes: {+ recharge: '充值'+ consume: '消耗'+ gift: '赠送'+ refund: '退款'+ expire: '过期'+ adjust: '调整'}- },- "recharge": {- "title": "购买积分",- "current": "当前积分",- "price": "每1000积分售价15美元",- "amount": "购买积分",- "total": "总价",- "buyNow": "立即购买",- "range": "1K-50K",- "unit": "积分"- }- },- "wallet": {- "title": "我的钱包",- "columns": {- "userName": "真实姓名",- "mail": "邮箱",- "account": "账号",- "type": "类型",- "phone": "手机号",- "cardNum": "身份证号",- "actions": "操作"- },- "types": {- "ZFB": "支付宝",- "WX_PAY": "微信支付"- },- "actions": {- "create": "新增账户",- "edit": "编辑",- "delete": "删除",- "deleteConfirm": "确认删除该钱包账户?",- "confirm": "确认",- "cancel": "取消"- },- "dialogs": {- "createTitle": "新增钱包账户",- "editTitle": "编辑钱包账户"- },- "form": {- "userId": "用户ID",- "userIdPlaceholder": "自动填充当前用户ID",- "mail": "邮箱",- "mailPlaceholder": "请输入邮箱",- "mailInvalid": "请输入有效的邮箱地址",- "userName": "真实姓名",- "userNamePlaceholder": "请输入真实姓名(可选)",- "account": "账号",- "accountPlaceholder": "请输入收款账号",- "cardNum": "身份证号",- "cardNumPlaceholder": "请输入身份证号(可选)",- "phone": "手机号",- "phonePlaceholder": "请输入绑定手机号(可选)",- "type": "类型",- "typePlaceholder": "请选择类型",- "required": "必填项"- },- "messages": {- "createSuccess": "创建成功",- "updateSuccess": "更新成功",- "deleteSuccess": "删除成功"- }- },- "youtube": {- "youtubeAuth": "YouTube 授权",- "authDescription": "请输入您的邮箱地址以获取 YouTube 授权",- "email": "邮箱",- "enterEmail": "请输入邮箱地址",- "authorize": "授权",- "pleaseEnterEmail": "请输入邮箱地址",- "invalidEmail": "请输入有效的邮箱地址",- "authFailed": "授权失败,请稍后重试",- "checkAuth": "检查授权",- "notAuthorized": "未授权",- "uploadVideo": "上传视频",- "needAuthFirst": "首先需要授权",- "uploadFailed": "上传失败",- "uploadSuccess": "上传成功",- "checkFailed": "检查失败",- "alreadyAuthorized": "已授权"+ }+ recharge: {+ title: '购买积分'+ current: '当前积分'+ price: '每1000积分售价15美元'+ amount: '购买积分'+ total: '总价'+ buyNow: '立即购买'+ range: '1K-50K'+ unit: '积分'+ }+ }+ 'wallet': {+ title: '我的钱包'+ columns: {+ userName: '真实姓名'+ mail: '邮箱'+ account: '账号'+ type: '类型'+ phone: '手机号'+ cardNum: '身份证号'+ actions: '操作'+ }+ types: {+ ZFB: '支付宝'+ WX_PAY: '微信支付'+ }+ actions: {+ create: '新增账户'+ edit: '编辑'+ delete: '删除'+ deleteConfirm: '确认删除该钱包账户?'+ confirm: '确认'+ cancel: '取消'+ }+ dialogs: {+ createTitle: '新增钱包账户'+ editTitle: '编辑钱包账户'+ }+ form: {+ userId: '用户ID'+ userIdPlaceholder: '自动填充当前用户ID'+ mail: '邮箱'+ mailPlaceholder: '请输入邮箱'+ mailInvalid: '请输入有效的邮箱地址'+ userName: '真实姓名'+ userNamePlaceholder: '请输入真实姓名(可选)'+ account: '账号'+ accountPlaceholder: '请输入收款账号'+ cardNum: '身份证号'+ cardNumPlaceholder: '请输入身份证号(可选)'+ phone: '手机号'+ phonePlaceholder: '请输入绑定手机号(可选)'+ type: '类型'+ typePlaceholder: '请选择类型'+ required: '必填项'+ }+ messages: {+ createSuccess: '创建成功'+ updateSuccess: '更新成功'+ deleteSuccess: '删除成功'+ }+ }+ 'youtube': {+ youtubeAuth: 'YouTube 授权'+ authDescription: '请输入您的邮箱地址以获取 YouTube 授权'+ email: '邮箱'+ enterEmail: '请输入邮箱地址'+ authorize: '授权'+ pleaseEnterEmail: '请输入邮箱地址'+ invalidEmail: '请输入有效的邮箱地址'+ authFailed: '授权失败,请稍后重试'+ checkAuth: '检查授权'+ notAuthorized: '未授权'+ uploadVideo: '上传视频'+ needAuthFirst: '首先需要授权'+ uploadFailed: '上传失败'+ uploadSuccess: '上传成功'+ checkFailed: '检查失败'+ alreadyAuthorized: '已授权'}}-export default Resources;+export default Resourcesdiff --git a/project/web/deploy/docker-compose.yaml b/project/web/deploy/docker-compose.yamlindex 5db57d27..202dc4f6 100644--- a/project/web/deploy/docker-compose.yaml+++ b/project/web/deploy/docker-compose.yaml@@ -1,11 +1,11 @@-version: "3.8"+version: '3.8'services:aitoearn-web:image: next-base-imagecontainer_name: aitoearn-webports:- - "3000:3000"+ - '3000:3000'volumes:- ./standalone:/app- command: node server.js\ No newline at end of file+ command: node server.jsdiff --git a/project/web/eslint.config.mjs b/project/web/eslint.config.mjsindex c2c32899..39cb75fd 100644--- a/project/web/eslint.config.mjs+++ b/project/web/eslint.config.mjs@@ -6,5 +6,25 @@ export default antfu({rules: {'node/prefer-global/process': ['off'],'no-console': ['off'],+ 'no-unused-vars': 'off',+ '@typescript-eslint/no-unused-vars': 'off',+ '@typescript-eslint/ban-ts-comment': 'off',+ 'prefer-promise-reject-errors': 'off',+ 'no-async-promise-executor': 'off',+ 'array-callback-return': 'off',+ 'unused-imports/no-unused-vars': 'off',+ 'unused-imports/no-unused-imports': 'off',+ 'style/multiline-ternary': 'off',+ 'style/no-mixed-operators': 'off',+ 'style/max-statements-per-line': 'off',+ 'eqeqeq': 'off',+ 'no-useless-escape': 'off',+ '@typescript-eslint/prefer-regexp-exec': 'off',+ 'prefer-regex-literals': 'off',+ 'no-use-before-define': 'off',+ '@typescript-eslint/no-use-before-define': 'off',+ 'ts/no-use-before-define': 'off',+ 'no-empty-pattern': 'off',+ 'regexp/no-contradiction-with-assertion': 'off',},})diff --git a/project/web/src/api/account.ts b/project/web/src/api/account.tsindex 8e5d9e2f..fc41431a 100644--- a/project/web/src/api/account.ts+++ b/project/web/src/api/account.ts@@ -1,76 +1,74 @@-// 创建或更新账户-import http from "@/utils/request";-import {+import type {AccountGroupItem,SocialAccount,UpdateAccountStatisticsParams,-} from "@/api/types/account.type";+} from '@/api/types/account.type'+// 创建或更新账户+import http from '@/utils/request'-export const createOrUpdateAccountApi = (data: Partial<SocialAccount>) => {- return http.post<SocialAccount>("account/login", data);-};+export function createOrUpdateAccountApi(data: Partial<SocialAccount>) {+ return http.post<SocialAccount>('account/login', data)+}// 更新账户-export const updateAccountApi = (data: Partial<SocialAccount>) => {- return http.post<SocialAccount>("account/update", data);-};+export function updateAccountApi(data: Partial<SocialAccount>) {+ return http.post<SocialAccount>('account/update', data)+}// 更新账户状态-export const updateAccountStatusApi = (data: {- id: string;- status: number;-}) => {- return http.post<SocialAccount>("account/status", data);-};+export function updateAccountStatusApi(data: {+ id: string+ status: number+}) {+ return http.post<SocialAccount>('account/status', data)+}// 获取账户列表-export const getAccountListApi = () => {- return http.get<SocialAccount[]>("account/list/all");-};+export function getAccountListApi() {+ return http.get<SocialAccount[]>('account/list/all')+}// 获取账户详情-export const getAccountDetailApi = (id: string) => {- return http.get<SocialAccount>(`account/${id}`);-};+export function getAccountDetailApi(id: string) {+ return http.get<SocialAccount>(`account/${id}`)+}-export const updateAccountStatisticsApi = (- data: UpdateAccountStatisticsParams,-) => {- return http.post<SocialAccount>("account/statistics/update", data);-};+export function updateAccountStatisticsApi(data: UpdateAccountStatisticsParams) {+ return http.post<SocialAccount>('account/statistics/update', data)+}// 删除账户-export const deleteAccountApi = (id: string) => {- return http.post<SocialAccount>(`account/delete/${id}`);-};+export function deleteAccountApi(id: string) {+ return http.post<SocialAccount>(`account/delete/${id}`)+}// 删除多个账户-export const deleteAccountsApi = (ids: string[]) => {- return http.post<SocialAccount>("account/deletes", {+export function deleteAccountsApi(ids: string[]) {+ return http.post<SocialAccount>('account/deletes', {ids,- });-};+ })+}// 创建账户组-export const createAccountGroupApi = (data: Partial<AccountGroupItem>) => {- return http.post("accountGroup/create", data);-};+export function createAccountGroupApi(data: Partial<AccountGroupItem>) {+ return http.post('accountGroup/create', data)+}// 更新账户组-export const updateAccountGroupApi = (data: Partial<AccountGroupItem>) => {- return http.post("accountGroup/update", data);-};+export function updateAccountGroupApi(data: Partial<AccountGroupItem>) {+ return http.post('accountGroup/update', data)+}// 删除账户组-export const deleteAccountGroupApi = (ids: string[]) => {- return http.post("accountGroup/deletes", {+export function deleteAccountGroupApi(ids: string[]) {+ return http.post('accountGroup/deletes', {ids,- });-};+ })+}// 获取所有账户组-export const getAccountGroupApi = async () => {- const res:any = await http.get<AccountGroupItem[]>("accountGroup/getList");+export async function getAccountGroupApi() {+ const res: any = await http.get<AccountGroupItem[]>('accountGroup/getList')// res.data.push({// id: "68a6d3e5861d0b23ca010123",// ip: "188.166.188.86",@@ -82,6 +80,6 @@ export const getAccountGroupApi = async () => {// userId: "689aea2a2b50f147c09f01bc",// _id: "68a6d3e5861d0b23ca010123",// });-- return res;-};++ return res+}diff --git a/project/web/src/api/accountSort.ts b/project/web/src/api/accountSort.tsindex 76420638..0489f64d 100644--- a/project/web/src/api/accountSort.ts+++ b/project/web/src/api/accountSort.ts@@ -1,18 +1,18 @@// 账户和分组排序API接口-import http from "@/utils/request";+import http from '@/utils/request'export interface SortRankItem {- id: string;- rank: number;+ id: string+ rank: number}export interface SortRankRequest {- list: SortRankItem[];+ list: SortRankItem[]}export interface AccountSortRankRequest {- groupId: string;- list: SortRankItem[];+ groupId: string+ list: SortRankItem[]}/**@@ -20,15 +20,15 @@ export interface AccountSortRankRequest {* @param data 排序数据* @returns*/-export const apiUpdateAccountGroupSortRank = (data: SortRankRequest) => {- return http.put("accountGroup/sortRank", data);-};+export function apiUpdateAccountGroupSortRank(data: SortRankRequest) {+ return http.put('accountGroup/sortRank', data)+}/*** 更新账户排序* @param data 排序数据* @returns*/-export const apiUpdateAccountSortRank = (data: AccountSortRankRequest) => {- return http.put("account/sortRank", data);-};+export function apiUpdateAccountSortRank(data: AccountSortRankRequest) {+ return http.put('account/sortRank', data)+}diff --git a/project/web/src/api/ai.ts b/project/web/src/api/ai.tsindex 96abaab2..ae95b392 100644--- a/project/web/src/api/ai.ts+++ b/project/web/src/api/ai.ts@@ -1,98 +1,98 @@-import http from "@/utils/request";-import { getOssUrl } from "@/utils/oss";+import { getOssUrl } from '@/utils/oss'+import http from '@/utils/request'// 获取聊天大模型列表-export const getChatModels = () => {- return http.get("ai/models/chat");-};+export function getChatModels() {+ return http.get('ai/models/chat')+}// 保存用户AI配置项(设置默认模型等)-export const putUserAiConfigItem = (data: {- type: "agent" | "edit" | "image" | "video";+export function putUserAiConfigItem(data: {+ type: 'agent' | 'edit' | 'image' | 'video'value: {- defaultModel: string;- option?: Record<string, any>;- [key: string]: any;- };- [key: string]: any;-}) => {- return http.put("user/ai/config/item", data);-};+ defaultModel: string+ option?: Record<string, any>+ [key: string]: any+ }+ [key: string]: any+}) {+ return http.put('user/ai/config/item', data)+}// 文生图 - 异步接口-export const generateImage = (data: {- prompt: string;- model?: string;- n?: number;- quality?: "standard" | "hd";- response_format?: "url" | "b64_json";- size?: string;- style?: "vivid" | "natural";- user?: string;-}) => {- return http.post("ai/image/generate/async", data);-};+export function generateImage(data: {+ prompt: string+ model?: string+ n?: number+ quality?: 'standard' | 'hd'+ response_format?: 'url' | 'b64_json'+ size?: string+ style?: 'vivid' | 'natural'+ user?: string+}) {+ return http.post('ai/image/generate/async', data)+}// 查询图片任务状态-export const getImageTaskStatus = (logId: string) => {- return http.get(`ai/image/task/${logId}`);-};+export function getImageTaskStatus(logId: string) {+ return http.get(`ai/image/task/${logId}`)+}// 流光卡片生成 - 新的接口-export const generateFireflyCard = (data: {- content: string;- temp?: string;- title?: string;+export function generateFireflyCard(data: {+ content: string+ temp?: string+ title?: stringstyle?: {- align?: string;- backgroundName?: string;- backShadow?: string;- font?: string;- width?: number;- ratio?: string;- height?: number;- fontScale?: number;- padding?: string;- borderRadius?: string;- color?: string;- opacity?: number;- blur?: number;- backgroundAngle?: string;+ align?: string+ backgroundName?: string+ backShadow?: string+ font?: string+ width?: number+ ratio?: string+ height?: number+ fontScale?: number+ padding?: string+ borderRadius?: string+ color?: string+ opacity?: number+ blur?: number+ backgroundAngle?: stringlineHeights?: {- content?: string;- title?: string;- };- };-}) => {- return http.post("ai/fireflycard", data);-};+ content?: string+ title?: string+ }+ }+}) {+ return http.post('ai/fireflycard', data)+}// 获取图片生成模型参数-export const getImageGenerationModels = () => {- return http.get("ai/models/image/generation");-};+export function getImageGenerationModels() {+ return http.get('ai/models/image/generation')+}// 获取图片编辑模型参数-export const getImageEditModels = () => {- return http.get("ai/models/image/edit");-};+export function getImageEditModels() {+ return http.get('ai/models/image/edit')+}// 获取视频生成模型参数-export const getVideoGenerationModels = () => {- return http.get("ai/models/video/generation");-};+export function getVideoGenerationModels() {+ return http.get('ai/models/video/generation')+}// 视频生成-export const generateVideo = (data: {- model: string;- prompt: string;- image?: any;- image_tail?: string;- mode?: string;- size?: string;- duration?: number;- metadata?: Record<string, any>;-}) => {+export function generateVideo(data: {+ model: string+ prompt: string+ image?: any+ image_tail?: string+ mode?: string+ size?: string+ duration?: number+ metadata?: Record<string, any>+}) {// if (data.image) {// if (typeof data.image === 'string') {// data.image = getOssUrl(data.image);@@ -103,91 +103,91 @@ export const generateVideo = (data: {// if (data.image_tail) {// data.image_tail = getOssUrl(data.image_tail);// }- return http.post("ai/video/generations", data);-};+ return http.post('ai/video/generations', data)+}// 查询视频任务状态-export const getVideoTaskStatus = (taskId: string) => {- return http.get(`ai/video/generations/${taskId}`);-};+export function getVideoTaskStatus(taskId: string) {+ return http.get(`ai/video/generations/${taskId}`)+}// 获取视频生成历史记录-export const getVideoGenerations = (params?: {- page?: number;- pageSize?: number;-}) => {- return http.get("ai/video/generations", { params });-};+export function getVideoGenerations(params?: {+ page?: number+ pageSize?: number+}) {+ return http.get('ai/video/generations', { params })+}// 保留旧的接口以保持向后兼容性(可选)// 文生图 - 旧接口(已废弃)-export const textToImage = (data: {- prompt: string;- width: number;- height: number;- sessionIds: string[];-}) => {- return http.post("tools/ai/jm/task", data);-};+export function textToImage(data: {+ prompt: string+ width: number+ height: number+ sessionIds: string[]+}) {+ return http.post('tools/ai/jm/task', data)+}// 获取文生图任务结果 - 旧接口(已废弃)-export const getTextToImageTaskResult = (id: string) => {+export function getTextToImageTaskResult(id: string) {return http.get<{- imgList: string[];- status: string;- taskId: string;- }>(`tools/ai/jm/task/${id}`);-};+ imgList: string[]+ status: string+ taskId: string+ }>(`tools/ai/jm/task/${id}`)+}// 文生图文(流光卡片)- 旧接口(已废弃)-export const textToFireflyCard = (data: {- content: string;- temp: string;- title: string;-}) => {- return http.post("tools/ai/fireflycard", data);-};+export function textToFireflyCard(data: {+ content: string+ temp: string+ title: string+}) {+ return http.post('tools/ai/fireflycard', data)+}// Markdown转卡片图片-export const generateMd2Card = (data: {- markdown: string;- theme: string;- themeMode?: string;- width?: number;- height?: number;- splitMode?: string;- mdxMode?: boolean;- overHiddenMode?: boolean;-}) => {- return http.post("ai/md2card", data);-};+export function generateMd2Card(data: {+ markdown: string+ theme: string+ themeMode?: string+ width?: number+ height?: number+ splitMode?: string+ mdxMode?: boolean+ overHiddenMode?: boolean+}) {+ return http.post('ai/md2card', data)+}// AI回复评论-export const createAiReplyTask = (data: {- accountId: string;- postId: string;- prompt: string;- platform: string;- model: string;-}) => {- return http.post("channel/engagement/comment/ai/replies/tasks", data);-};+export function createAiReplyTask(data: {+ accountId: string+ postId: string+ prompt: string+ platform: string+ model: string+}) {+ return http.post('channel/engagement/comment/ai/replies/tasks', data)+}// 图片编辑 - 异步接口-export const editImage = (data: {- model: string;- image: string[];- prompt: string;- mask?: string;- n?: number;- size?: string;- response_format?: "url" | "b64_json";- user?: string;-}) => {- return http.post("ai/image/edit/async", data);-};+export function editImage(data: {+ model: string+ image: string[]+ prompt: string+ mask?: string+ n?: number+ size?: string+ response_format?: 'url' | 'b64_json'+ user?: string+}) {+ return http.post('ai/image/edit/async', data)+}// 查询图片编辑任务状态-export const getImageEditTaskStatus = (logId: string) => {- return http.get(`ai/image/task/${logId}`);-};\ No newline at end of file+export function getImageEditTaskStatus(logId: string) {+ return http.get(`ai/image/task/${logId}`)+}diff --git a/project/web/src/api/apiReq.ts b/project/web/src/api/apiReq.tsindex 34f384d1..67e9ecc5 100644--- a/project/web/src/api/apiReq.ts+++ b/project/web/src/api/apiReq.ts@@ -1,120 +1,118 @@-import http from "@/utils/request";-import { UserInfo } from "@/store/user";-import md5 from "blueimp-md5";+import type { UserInfo } from '@/store/user'+import md5 from 'blueimp-md5'+import http from '@/utils/request'export interface LoginResponse {- type: "regist" | "login"; // 登录类型:regist-需要注册,login-直接登录- token?: string;- registUrl?: string;- code?: string; // 注册码- userInfo?: UserInfo; // 用户信息+ type: 'regist' | 'login' // 登录类型:regist-需要注册,login-直接登录+ token?: string+ registUrl?: string+ code?: string // 注册码+ userInfo?: UserInfo // 用户信息}export interface RegistCheckParams {- code: string;- mail: string;- password: string;- inviteCode: string;+ code: string+ mail: string+ password: string+ inviteCode: string}// 获取用户信息-export const getUserInfoApi = () => {- return http.get<UserInfo>("user/mine");-};+export function getUserInfoApi() {+ return http.get<UserInfo>('user/mine')+}// 更新用户信息-export const updateUserInfoApi = (data: { name: string }) => {- return http.put<UserInfo>("user/info/update", data);-};+export function updateUserInfoApi(data: { name: string }) {+ return http.put<UserInfo>('user/info/update', data)+}-export const getMoneyStampApi = () => {- return http.get<any>("cfg/money/stamp");-};+export function getMoneyStampApi() {+ return http.get<any>('cfg/money/stamp')+}-export const fluxSchnellApi = (data: any) => {- return http.post<any>("experience-ai/text2image/flux_schnell", data);-};+export function fluxSchnellApi(data: any) {+ return http.post<any>('experience-ai/text2image/flux_schnell', data)+}// 邮箱登录接口-export const loginWithMailApi = (data: { mail: string; password: string }) => {- const hash = md5(data.password);- return http.post<LoginResponse>("login/mail", {+export function loginWithMailApi(data: { mail: string, password: string }) {+ const hash = md5(data.password)+ return http.post<LoginResponse>('login/mail', {...data,password: hash,- });-};+ })+}// 获取注册链接-export const getRegistUrlApi = (mail: string) => {- return http.get<LoginResponse>(`login/mail/regist/url?mail=${mail}`);-};+export function getRegistUrlApi(mail: string) {+ return http.get<LoginResponse>(`login/mail/regist/url?mail=${mail}`)+}// 检查注册状态 post!!-export const checkRegistStatusApi = (data: RegistCheckParams) => {- const hash = md5(data.password);+export function checkRegistStatusApi(data: RegistCheckParams) {+ const hash = md5(data.password)return http.post<LoginResponse>(`login/mail/regist/back`, {...data,password: hash,- });-};+ })+}// 邮箱注册接口-export const mailRegistApi = (data: {- mail: string;- code: string;- password: string;- inviteCode?: string;-}) => {- const hash = md5(data.password);- return http.post<LoginResponse>("login/mail/regist", {+export function mailRegistApi(data: {+ mail: string+ code: string+ password: string+ inviteCode?: string+}) {+ const hash = md5(data.password)+ return http.post<LoginResponse>('login/mail/regist', {...data,password: hash,- });-};+ })+}// 发送重置密码邮件-export const sendResetPasswordMailApi = (data: { mail: string }) => {- return http.post<LoginResponse>("login/repassword/mail", data);-};+export function sendResetPasswordMailApi(data: { mail: string }) {+ return http.post<LoginResponse>('login/repassword/mail', data)+}// 重置密码-export const resetPasswordApi = (data: {- code: string;- mail: string;- password: string;-}) => {- const hash = md5(data.password);- return http.post<LoginResponse>("login/repassword/mail", {+export function resetPasswordApi(data: {+ code: string+ mail: string+ password: string+}) {+ const hash = md5(data.password)+ return http.post<LoginResponse>('login/repassword/mail', {...data,password: hash,- });-};+ })+}// Google 登录参数export interface GoogleLoginParams {- clientId: string;- credential: string;+ clientId: string+ credential: string}// Google 登录-export const googleLoginApi = (data: GoogleLoginParams) => {- return http.post<LoginResponse>("login/google", data);-};+export function googleLoginApi(data: GoogleLoginParams) {+ return http.post<LoginResponse>('login/google', data)+}// 积分记录相关API-export const getPointsRecordsApi = async (params: { page: number; pageSize: number }) => {- const res = await http.get<any>(`user/points/records`,- params,- );- return res;-};+export async function getPointsRecordsApi(params: { page: number, pageSize: number }) {+ const res = await http.get<any>(`user/points/records`, params)+ return res+}// 积分充值相关APIexport interface RechargePointsParams {- amount: number; // 充值数量(1000积分为单位)- totalPrice: number; // 总价格+ amount: number // 充值数量(1000积分为单位)+ totalPrice: number // 总价格}-export const rechargePointsApi = (data: RechargePointsParams) => {- return http.post<any>("user/points/recharge", data);-};+export function rechargePointsApi(data: RechargePointsParams) {+ return http.post<any>('user/points/recharge', data)+}diff --git a/project/web/src/api/dataStatistics.ts b/project/web/src/api/dataStatistics.tsindex 90e66f2a..fc288705 100644--- a/project/web/src/api/dataStatistics.ts+++ b/project/web/src/api/dataStatistics.ts@@ -1,21 +1,21 @@-import http from "@/utils/request";-import {+import type {StatisticsPeriodApiParams,StatisticsPeriodModel,-} from "@/api/types/dataStatistics";+} from '@/api/types/dataStatistics'+import http from '@/utils/request'// 获取数据统计信息-export const getStatisticsPeriodApi = (data: StatisticsPeriodApiParams) => {+export function getStatisticsPeriodApi(data: StatisticsPeriodApiParams) {return http.post<StatisticsPeriodModel>(- "statistics/channels/period-batch",+ 'statistics/channels/period-batch',data,- );-};+ )+}// 获取抖音话题-export const getDouyinTopicsApi = (keyword: string) => {- return http.post<string[]>("statistics/channels/douyin/searchTopic", {+export function getDouyinTopicsApi(keyword: string) {+ return http.post<string[]>('statistics/channels/douyin/searchTopic', {topic: keyword,- language: "en",- });-};+ language: 'en',+ })+}diff --git a/project/web/src/api/engagement.ts b/project/web/src/api/engagement.tsindex 031934f4..c735facc 100644--- a/project/web/src/api/engagement.ts+++ b/project/web/src/api/engagement.ts@@ -1,39 +1,36 @@-import http from '@/utils/request';-import { EngagementPostsParams, EngagementPostsResponse, EngagementCommentsParams, EngagementCommentsResponse, EngagementReplyParams, PostCommentsParamsV2, PostCommentsResponseV2, PublishPostCommentParams, PublishCommentReplyParams, CommentRepliesParams, CommentRepliesResponse } from './types/engagement';-+import type { CommentRepliesParams, CommentRepliesResponse, EngagementCommentsParams, EngagementCommentsResponse, EngagementPostsParams, EngagementPostsResponse, EngagementReplyParams, PostCommentsParamsV2, PostCommentsResponseV2, PublishCommentReplyParams, PublishPostCommentParams } from './types/engagement'+import http from '@/utils/request'export async function apiGetEngagementnew(params: any) {- return http.post<EngagementPostsResponse>('channel/engagement/meta/posts', params);+ return http.post<EngagementPostsResponse>('channel/engagement/meta/posts', params)}export async function apiGetEngagementPosts(params: EngagementPostsParams) {- return http.post<EngagementPostsResponse>('statistics/posts/list', params);+ return http.post<EngagementPostsResponse>('statistics/posts/list', params)}export async function apiGetEngagementComments(params: EngagementCommentsParams) {- return http.post<EngagementCommentsResponse>('channel/engagement/comments', params);+ return http.post<EngagementCommentsResponse>('channel/engagement/comments', params)}export async function apiReplyEngagementComment(params: EngagementReplyParams) {- return http.post<{}>('channel/engagement/comment/reply', params);+ return http.post<any>('channel/engagement/comment/reply', params)}// 获取作品一级评论(V2)export async function apiGetPostComments(params: PostCommentsParamsV2) {- return http.post<PostCommentsResponseV2>('channel/engagement/post/comments', params);+ return http.post<PostCommentsResponseV2>('channel/engagement/post/comments', params)}export async function apiPublishPostComment(params: PublishPostCommentParams) {- return http.post<{}>('channel/engagement/post/comments/publish', params);+ return http.post('channel/engagement/post/comments/publish', params)}export async function apiPublishCommentReply(params: PublishCommentReplyParams) {- return http.post<{}>('channel/engagement/comment/replies/publish', params);+ return http.post('channel/engagement/comment/replies/publish', params)}// 获取评论的回复列表export async function apiGetCommentReplies(params: CommentRepliesParams) {- return http.post<CommentRepliesResponse>('channel/engagement/comment/replies', params);+ return http.post<CommentRepliesResponse>('channel/engagement/comment/replies', params)}--diff --git a/project/web/src/api/hot.ts b/project/web/src/api/hot.tsindex de0dbe4a..4d2566c6 100644--- a/project/web/src/api/hot.ts+++ b/project/web/src/api/hot.ts@@ -1,146 +1,146 @@-import { Pagination } from "./types";-import { HotTopic } from "./types/hotTopic";-import { Topic } from "./types/topic";-import { ViralTitle } from "./types/viralTitles";-import { request } from "@/utils/request";-import {+import type { Pagination } from './types'+import type { HotTopic } from './types/hotTopic'+import type {GetAiToolsRankingApiParams,GetAiToolsRankingApiRes,-} from "./types/platform.type";+} from './types/platform.type'+import type { Topic } from './types/topic'+import type { ViralTitle } from './types/viralTitles'+import { request } from '@/utils/request'export interface Platform {- id: string;- _id: string;- name: string;- icon: string;- type: string;- description: string;- status: number;- config: Record<string, any>;- sort: number;- createTime: string;- updateTime: string;+ id: string+ _id: string+ name: string+ icon: string+ type: string+ description: string+ status: number+ config: Record<string, any>+ sort: number+ createTime: string+ updateTime: string}export interface RankingItem {- id: string;- title: string;+ id: string+ title: stringauthor: {- name: string;- avatar: string;- followers: string;- };+ name: string+ avatar: string+ followers: string+ }category: {- name: string;- subCategory: string;- };- duration: string;- views: string;- likes: string;- comments: string;- engagement: string;- thumbnail: string;- createTime: string;+ name: string+ subCategory: string+ }+ duration: string+ views: string+ likes: string+ comments: string+ engagement: string+ thumbnail: string+ createTime: string}export interface PlatformRanking {- _id: string;- id: string;- name: string;- platformId: string;- parentId: string;- platform: Platform;- type: "daily" | "weekly" | "monthly";- description: string;- icon: string;- status: number;- rules: string;- config: Record<string, any>;- sort: number;- updateFrequency: string;- lastUpdateTime: string;- createTime: string;- updateTime: string;- items?: RankingItem[];+ _id: string+ id: string+ name: string+ platformId: string+ parentId: string+ platform: Platform+ type: 'daily' | 'weekly' | 'monthly'+ description: string+ icon: string+ status: number+ rules: string+ config: Record<string, any>+ sort: number+ updateFrequency: string+ lastUpdateTime: string+ createTime: string+ updateTime: string+ items?: RankingItem[]}// 榜单日期export interface RankingDate {- originalQueryDate: string;- queryDate: string;- rankingId: string;- showDate: string;- spiderTime: string;- value: string;+ originalQueryDate: string+ queryDate: string+ rankingId: string+ showDate: string+ spiderTime: string+ value: string}export interface Author {- id: string;- name: string;- avatar: string;- url: string;- fansCount: number;+ id: string+ name: string+ avatar: string+ url: string+ fansCount: number}export interface Stats {- watchCount: number;- viewCount: number;- likeCount: number;- commentCount: number;- shareCount: number;- collectCount: number;+ watchCount: number+ viewCount: number+ likeCount: number+ commentCount: number+ shareCount: number+ collectCount: number}export interface RankingContent {- mid: string;- secUid: string;- id: string;- title: string;- cover: string;- url: string;- photoId: string;- rankingPosition: number;- category: string;- publishTime: string;- subCategory: string;+ mid: string+ secUid: string+ id: string+ title: string+ cover: string+ url: string+ photoId: string+ rankingPosition: number+ category: string+ publishTime: string+ subCategory: stringauthor: {- name: string;- avatar: string;- fansCount: number;- id: string;- };- stats: Stats;- collectCount?: number;- shareCount?: number;+ name: string+ avatar: string+ fansCount: number+ id: string+ }+ stats: Stats+ collectCount?: number+ shareCount?: numberanaAdd: {- addCollectCount: number;- addCommentCount: number;- addInteractiveCount: number;- addLikeCount: number;- addShareCount: number;- addViewCount: number | null;- collectedCount: number;- interactiveCount: number;- pred_readnum: number;- useCollectCount: number;- useCommentCount: number;- useLikeCount: number;- useShareCount: number;- useViewCount: number | null;- };+ addCollectCount: number+ addCommentCount: number+ addInteractiveCount: number+ addLikeCount: number+ addShareCount: number+ addViewCount: number | null+ collectedCount: number+ interactiveCount: number+ pred_readnum: number+ useCollectCount: number+ useCommentCount: number+ useLikeCount: number+ useShareCount: number+ useViewCount: number | null+ }}export interface PaginationMeta {- itemCount: number;- totalItems: number;- itemsPerPage: number;- totalPages: number;- currentPage: number;+ itemCount: number+ totalItems: number+ itemsPerPage: number+ totalPages: number+ currentPage: number}export interface RankingContentsResponse {- items: RankingContent[];- meta: PaginationMeta;+ items: RankingContent[]+ meta: PaginationMeta}export const platformApi = {@@ -148,16 +148,16 @@ export const platformApi = {getPlatformList() {return request<Platform[]>({url: `hotdata/hotinfo/platform`,- method: "GET",- });+ method: 'GET',+ })},// 获取平台榜单列表getPlatformRanking(platformId: string) {return request<PlatformRanking[]>({url: `hotdata/ranking/platform?platformId=${platformId}`,- method: "GET",- });+ method: 'GET',+ })},// 获取榜单内容@@ -171,50 +171,50 @@ export const platformApi = {const params: Record<string, any> = {page,pageSize,- };+ }- if (category && category !== "全部") {- params.category = category;+ if (category && category !== '全部') {+ params.category = category}if (date) {- params.date = date;+ params.date = date}return request<RankingContentsResponse>({url: `hotdata/ranking/${rankingId}/contents`,- method: "GET",+ method: 'GET',params,- });+ })},// 获取榜单分类getRankingLabel(rankingId: string) {return request<string[]>({url: `hotdata/ranking/label/${rankingId}`,- method: "GET",- });+ method: 'GET',+ })},// 获取榜单日期getRankingDates(rankingId: string) {return request<RankingDate[]>({url: `hotdata/ranking/hotinfo/${rankingId}/dates`,- method: "GET",- });+ method: 'GET',+ })},// 获取八大平台热点事件getAllHotTopics() {return request<{- platform: Platform;- topics: HotTopic[];+ platform: Platform+ topics: HotTopic[]}[]>({url: `hotdata/hot-topics/all`,- method: "GET",- });+ method: 'GET',+ })},// ---- 热门专题 ----@@ -223,52 +223,52 @@ export const platformApi = {getTopics() {return request<string[]>({url: `hotdata/topics/topics`,- method: "GET",- });+ method: 'GET',+ })},// 获取所有专题类型1getMsgType() {return request<string[]>({url: `hotdata/topics/msgType`,- method: "GET",- });+ method: 'GET',+ })},// 获取所有专题分类getTopicLabels(msgType: string) {return request<string[]>({url: `hotdata/topics/labels/${msgType}`,- method: "GET",- });+ method: 'GET',+ })},// 获取专题的时间类型getTopicTimeTypes(msgType: string) {return request<string[]>({url: `hotdata/topics/timeType/${msgType}`,- method: "GET",- });+ method: 'GET',+ })},// 获取热门专题列表getAllTopics(params: {- msgType?: string; // 项目类型- timeType?: string; // 时间分类- type?: string; // 类型- platformId?: string; // 平台ID- startTime?: string; // 发布时间开始- endTime?: string; // 发布时间结束- topic?: string; // 话题标签- page?: number;- pageSize?: number;+ msgType?: string // 项目类型+ timeType?: string // 时间分类+ type?: string // 类型+ platformId?: string // 平台ID+ startTime?: string // 发布时间开始+ endTime?: string // 发布时间结束+ topic?: string // 话题标签+ page?: number+ pageSize?: number}) {return request<Pagination<Topic>>({url: `hotdata/topics`,- method: "GET",+ method: 'GET',params,- });+ })},// ---- 爆款标题 ----@@ -276,16 +276,16 @@ export const platformApi = {findPlatformsWithData() {return request<Platform[]>({url: `hotdata/viral-titles/platforms`,- method: "GET",- });+ method: 'GET',+ })},// 获取指定平台的分类列表findCategoriesByPlatform(platformId: string) {return request<string[]>({url: `hotdata/viral-titles/platforms/${platformId}/categories`,- method: "GET",- });+ method: 'GET',+ })},// 获取平台下所有分类的前五条数据@@ -295,45 +295,45 @@ export const platformApi = {) {return request<{- category: string;- titles: ViralTitle[];+ category: string+ titles: ViralTitle[]}[]>({url: `hotdata/viral-titles/platforms/${platformId}/top-by-categories`,- method: "GET",+ method: 'GET',params: {timeType,},- });+ })},// 获取爆款标题平台下指定分类的数据列表(分页)findByPlatformAndCategory(platformId: string,params: {- category?: string;- startTime?: Date;- endTime?: Date;- timeType?: string;- page?: number;- pageSize?: number;+ category?: string+ startTime?: Date+ endTime?: Date+ timeType?: string+ page?: number+ pageSize?: number},) {return request<Pagination<ViralTitle>>({url: `hotdata/viral-titles/platforms/${platformId}`,- method: "GET",+ method: 'GET',params,- });+ })},// 获取爆款标题的时间类型getViralTitleTimeTypes() {return request<string[]>({url: `hotdata/viral-titles/timeType`,- method: "GET",- });+ method: 'GET',+ })},// ---- 话题 ----@@ -341,76 +341,76 @@ export const platformApi = {findTalksPlatforms() {return request<Platform[]>({url: `hotdata/talks/platforms`,- method: "GET",- });+ method: 'GET',+ })},// 获取话题栏目findTalksColumn(platformId: string) {return request<string[]>({url: `hotdata/talks/column`,- method: "GET",+ method: 'GET',params: {platformId,},- });+ })},// 获取小红书话题流量榜、流量扶持日期getXhsDates() {return request<string[]>({url: `hotdata/xhs/dates`,- method: "GET",- });+ method: 'GET',+ })},// 获取小红书话题流量榜、流量扶持分类getXhsCategories() {return request<string[]>({url: `hotdata/xhs/category`,- method: "GET",- });+ method: 'GET',+ })},// 获取小红书话题流量榜getXhsSubjectsRank(data: { phone: string }) {return request<string>({url: `hotdata/xhs/contents`,- method: "POST",+ method: 'POST',data,- });+ })},// 获取抖音榜单日期getDyDates() {return request<string[]>({url: `hotdata/dy/dates`,- method: "GET",- });+ method: 'GET',+ })},// 获取AI工具榜数据getAiToolsRankingApi(data: GetAiToolsRankingApiParams) {return request<GetAiToolsRankingApiRes>({url: `hotdata/products/ranking/ai`,- method: "POST",+ method: 'POST',data: {...data,pageSize: 100,area: +data.area,},- });+ })},// 获取热点数据 公众号 链接getDetailUrl(photoId: string) {return request<string>({url: `hotdata/contents/query/getDetailUrl`,- method: "POST",+ method: 'POST',data: {platform: 0,photoId,},- });+ })},-};+}diff --git a/project/web/src/api/income.ts b/project/web/src/api/income.tsindex dcfb62d1..fae83ef7 100644--- a/project/web/src/api/income.ts+++ b/project/web/src/api/income.ts@@ -1,33 +1,33 @@-import { request } from '@/utils/request';-import { IncomeRecord } from './types/income';+import type { IncomeRecord } from './types/income'+import { request } from '@/utils/request'/*** 获取收入列表*/-export const apiGetIncomeList = (page: {- pageNo: number;- pageSize: number;+export function apiGetIncomeList(page: {+ pageNo: number+ pageSize: number}, params: {type?: string-}) => {+}) {return request<{ list: IncomeRecord[], total: number }>({url: `income/list/${page.pageNo}/${page.pageSize}`,method: 'GET',- params- });-};+ params,+ })+}/*** 提交提现*/-export const apiSubmitWithdraw = (incomeRecordId: string, userWalletAccountId?: string, flowId?: string) => {+export function apiSubmitWithdraw(incomeRecordId: string, userWalletAccountId?: string, flowId?: string) {return request<any>({url: `income/withdraw`,method: 'POST',data: {incomeRecordId,userWalletAccountId,- flowId- }- });-};\ No newline at end of file+ flowId,+ },+ })+}diff --git a/project/web/src/api/material.ts b/project/web/src/api/material.tsindex c9bd4642..0fdbf8dc 100644--- a/project/web/src/api/material.ts+++ b/project/web/src/api/material.ts@@ -1,10 +1,10 @@-import http from "@/utils/request";-import { PubType } from "@/app/config/publishConfig";+import type { PubType } from '@/app/config/publishConfig'+import http from '@/utils/request'export interface MaterialMedia {- url: string;- type: PubType;- content?: string;+ url: string+ type: PubType+ content?: string}export enum MaterialType {@@ -13,120 +13,107 @@ export enum MaterialType {}export interface NewMaterialTask {- groupId: string;- num: number;- aiModelTag: string;- type: MaterialType;- prompt: string;- title?: string;- desc?: string;- location?: number[];- publishTime?: string;- mediaGroups: string[];- coverGroup: string;- option?: Record<string, any>;- textMax?: number;- language?: string;+ groupId: string+ num: number+ aiModelTag: string+ type: MaterialType+ prompt: string+ title?: string+ desc?: string+ location?: number[]+ publishTime?: string+ mediaGroups: string[]+ coverGroup: string+ option?: Record<string, any>+ textMax?: number+ language?: string}// 创建素材草稿组-export const apiCreateMaterialGroup = (data: {- type: PubType;- name: string;- desc?: string;-}) => {- return http.post("material/group", data);-};+export function apiCreateMaterialGroup(data: {+ type: PubType+ name: string+ desc?: string+}) {+ return http.post('material/group', data)+}// 删除草稿素材组-export const apiDeleteMaterialGroup = (id: string) => {- return http.delete(`material/group/${id}`);-};+export function apiDeleteMaterialGroup(id: string) {+ return http.delete(`material/group/${id}`)+}// 更新草稿素材组信息-export const apiUpdateMaterialGroupInfo = (- id: string,- data: {- name?: string;- desc?: string;- },-) => {- return http.post(`material/group/info/${id}`, data);-};+export function apiUpdateMaterialGroupInfo(id: string, data: {+ name?: string+ desc?: string+}) {+ return http.post(`material/group/info/${id}`, data)+}// 获取草稿素材组列表-export const apiGetMaterialGroupList = (pageNo: number, pageSize: number) => {- return http.get<{ list: any[]; total: number }>(+export function apiGetMaterialGroupList(pageNo: number, pageSize: number) {+ return http.get<{ list: any[], total: number }>(`material/group/list/${pageNo}/${pageSize}`,- );-};+ )+}// 创建草稿素材-export const apiCreateMaterial = (data: {- groupId: string;- coverUrl?: string;- mediaList: MaterialMedia[];- title: string;- desc?: string;- option?: Record<string, any>;- location?: number[];-}) => {- return http.post("material", data);-};+export function apiCreateMaterial(data: {+ groupId: string+ coverUrl?: string+ mediaList: MaterialMedia[]+ title: string+ desc?: string+ option?: Record<string, any>+ location?: number[]+}) {+ return http.post('material', data)+}// 创建批量生成草稿任务-export const apiCreateMaterialTask = (data: NewMaterialTask) => {- return http.post<{ _id: string }>("material/task/create", data);-};+export function apiCreateMaterialTask(data: NewMaterialTask) {+ return http.post<{ _id: string }>('material/task/create', data)+}// 预览生成草稿任务-export const apiPreviewMaterialTask = (taskId: string) => {- return http.get(`material/task/preview/${taskId}`);-};+export function apiPreviewMaterialTask(taskId: string) {+ return http.get(`material/task/preview/${taskId}`)+}// 开始批量生成草稿任务-export const apiStartMaterialTask = (taskId: string) => {- return http.get(`material/task/start/${taskId}`);-};+export function apiStartMaterialTask(taskId: string) {+ return http.get(`material/task/start/${taskId}`)+}// 删除草稿素材-export const apiDeleteMaterial = (id: string) => {- return http.delete(`material/${id}`);-};+export function apiDeleteMaterial(id: string) {+ return http.delete(`material/${id}`)+}// 获取草稿素材列表-export const apiGetMaterialList = (- groupId: string,- pageNo: number,- pageSize: number,-) => {+export function apiGetMaterialList(groupId: string, pageNo: number, pageSize: number) {return http.get(`material/list/${pageNo}/${pageSize}`, {groupId,- });-};+ })+}// 更新草稿素材信息-export const apiUpdateMaterialInfo = (- id: string,- data: {- title?: string;- desc?: string;- },-) => {- return http.put(`material/info/${id}`, data);-};+export function apiUpdateMaterialInfo(id: string, data: {+ title?: string+ desc?: string+}) {+ return http.put(`material/info/${id}`, data)+}// 更新草稿素材完整信息-export const apiUpdateMaterial = (- id: string,- data: {- coverUrl?: string;- mediaList?: MaterialMedia[];- title?: string;- desc?: string;- location?: number[];- option?: Record<string, any>;- },-) => {- return http.put(`material/info/${id}`, data);-};+export function apiUpdateMaterial(id: string, data: {+ coverUrl?: string+ mediaList?: MaterialMedia[]+ title?: string+ desc?: string+ location?: number[]+ option?: Record<string, any>+}) {+ return http.put(`material/info/${id}`, data)+}diff --git a/project/web/src/api/mcp.ts b/project/web/src/api/mcp.tsindex 59dc659f..fa2a9a7a 100644--- a/project/web/src/api/mcp.ts+++ b/project/web/src/api/mcp.ts@@ -1,57 +1,55 @@// MCP API接口-import { request } from "@/utils/request";--+import { request } from '@/utils/request'/*** 创建MCP Key* @param data 创建参数* @returns*/-export const apiCreateMCPKey = (data:any) => {+export function apiCreateMCPKey(data: any) {return request({- url: "channel/skKey",- method: "POST",+ url: 'channel/skKey',+ method: 'POST',data,- });-};+ })+}/*** 更新MCP Key* @param data 更新参数* @returns*/-export const apiUpdateMCPKey = (data:any) => {+export function apiUpdateMCPKey(data: any) {return request({- url: "channel/skKey",- method: "PUT",+ url: 'channel/skKey',+ method: 'PUT',data,- });-};+ })+}/*** 删除MCP Key* @param key Key key* @returns*/-export const apiDeleteMCPKey = (key: string) => {+export function apiDeleteMCPKey(key: string) {return request({url: `channel/skKey/${key}`,- method: "DELETE",- });-};+ method: 'DELETE',+ })+}/*** 获取MCP Key详情* @param key Key值* @returns*/-export const apiGetMCPKeyInfo = (key: string) => {+export function apiGetMCPKeyInfo(key: string) {return request({url: `channel/skKey/info/${key}`,- method: "GET",- });-};+ method: 'GET',+ })+}/*** 获取MCP Key列表@@ -59,38 +57,38 @@ export const apiGetMCPKeyInfo = (key: string) => {* @param pageSize 每页大小* @returns*/-export const apiGetMCPKeyList = (pageNo: number, pageSize: number) => {+export function apiGetMCPKeyList(pageNo: number, pageSize: number) {return request({url: `channel/skKey/list/${pageNo}/${pageSize}`,- method: "GET",- });-};+ method: 'GET',+ })+}/*** 创建MCP Key关联* @param data 关联参数* @returns*/-export const apiCreateMCPRef = (data: any) => {+export function apiCreateMCPRef(data: any) {return request({- url: "channel/skKey/ref",- method: "POST",+ url: 'channel/skKey/ref',+ method: 'POST',data,- });-};+ })+}/*** 解除MCP Key关联* @param data 解除关联参数* @returns*/-export const apiDeleteMCPRef = (data: any) => {+export function apiDeleteMCPRef(data: any) {return request({- url: "channel/skKey/ref",- method: "DELETE",+ url: 'channel/skKey/ref',+ method: 'DELETE',data,- });-};+ })+}/*** 获取MCP Key关联列表@@ -98,12 +96,12 @@ export const apiDeleteMCPRef = (data: any) => {* @param pageSize 每页大小* @returns*/-export const apiGetMCPRefList = (pageNo: number, pageSize: number, key: string) => {+export function apiGetMCPRefList(pageNo: number, pageSize: number, key: string) {return request({url: `channel/skKey/ref/list/${pageNo}/${pageSize}`,- method: "GET",+ method: 'GET',params: {key,},- });-};\ No newline at end of file+ })+}diff --git a/project/web/src/api/media.ts b/project/web/src/api/media.tsindex befd507f..d57c3511 100644--- a/project/web/src/api/media.ts+++ b/project/web/src/api/media.ts@@ -1,81 +1,67 @@-import http from "@/utils/request";+import http from '@/utils/request'// 创建媒体资源组-export const createMediaGroup = (data: {- title: string;- desc: string;- type: "video" | "img";-}) => {- return http.post("media/group", data);-};+export function createMediaGroup(data: {+ title: string+ desc: string+ type: 'video' | 'img'+}) {+ return http.post('media/group', data)+}// 删除媒体资源组-export const deleteMediaGroup = (id: string) => {- return http.delete(`media/group/${id}`);-};+export function deleteMediaGroup(id: string) {+ return http.delete(`media/group/${id}`)+}// 获取媒体资源组列表-export const getMediaGroupList = (- pageNo: number,- pageSize: number,- type? : "video" | "img",-) => {- return http.get<{ list: any[]; total: number }>(+export function getMediaGroupList(pageNo: number, pageSize: number, type?: 'video' | 'img') {+ return http.get<{ list: any[], total: number }>(`media/group/list/${pageNo}/${pageSize}`,{type,},- );-};+ )+}// 更新媒体资源组信息-export const updateMediaGroupInfo = (- id: string,- data: {- title?: string;- desc?: string;- type?: "video" | "img";- },-) => {- return http.post(`media/group/info/${id}`, data);-};+export function updateMediaGroupInfo(id: string, data: {+ title?: string+ desc?: string+ type?: 'video' | 'img'+}) {+ return http.post(`media/group/info/${id}`, data)+}// 创建媒体资源-export const createMedia = (data: any) => {- return http.post("media", data);-};+export function createMedia(data: any) {+ return http.post('media', data)+}// 删除媒体资源-export const deleteMedia = (id: string) => {- return http.delete(`media/${id}`);-};+export function deleteMedia(id: string) {+ return http.delete(`media/${id}`)+}// 获取媒体资源列表-export const getMediaList = (- groupId: string,- pageNo: number,- pageSize: number,-) => {+export function getMediaList(groupId: string, pageNo: number, pageSize: number) {return http.get(`media/list/${pageNo}/${pageSize}`, {groupId,- });-};+ })+}// 更新媒体资源信息-export const updateMediaInfo = (- id: string,- data: {- title?: string;- desc?: string;- },-) => {- return http.put(`media/info/${id}`, data);-};+export function updateMediaInfo(id: string, data: {+ title?: string+ desc?: string+}) {+ return http.put(`media/info/${id}`, data)+}-export const apiAddUseCount = (id: string) => {- return http.put(`media/addUseCount`, { data: { id } });-};+export function apiAddUseCount(id: string) {+ return http.put(`media/addUseCount`, { data: { id } })+}-export const apiAddUseCountOfList = (ids: string[]) => {- return http.put(`media/addUseCountOfList`, { data: { ids } });-};\ No newline at end of file+export function apiAddUseCountOfList(ids: string[]) {+ return http.put(`media/addUseCountOfList`, { data: { ids } })+}diff --git a/project/web/src/api/notification.ts b/project/web/src/api/notification.tsindex e8aa320e..992d549c 100644--- a/project/web/src/api/notification.ts+++ b/project/web/src/api/notification.ts@@ -1,111 +1,111 @@-import http from "@/utils/request";+import http from '@/utils/request'export interface NotificationItem {- id: string;- title: string;- content: string;- type: "system" | "user" | "material" | "other" | "task_reminder";- status: "read" | "unread";- readAt?: string;- createdAt: string;- updatedAt: string;- relatedId?: string;- userId?: string;+ id: string+ title: string+ content: string+ type: 'system' | 'user' | 'material' | 'other' | 'task_reminder'+ status: 'read' | 'unread'+ readAt?: string+ createdAt: string+ updatedAt: string+ relatedId?: string+ userId?: string}export interface NotificationListResponse {- list: NotificationItem[];- total: number;- page: number;- pageSize: number;+ list: NotificationItem[]+ total: number+ page: number+ pageSize: number}export interface NotificationDetailResponse {- data: NotificationItem;+ data: NotificationItem}export interface UnreadCountResponse {- count: number;+ count: number}// 获取用户通知列表-export const getNotificationList = (params: {- page?: number;- pageSize?: number;- type?: string;-}) => {- return http.get<NotificationListResponse>("notification", params );-};+export function getNotificationList(params: {+ page?: number+ pageSize?: number+ type?: string+}) {+ return http.get<NotificationListResponse>('notification', params)+}// 获取通知详情-export const getNotificationDetail = (id: string) => {- return http.get(`notification/${id}`);-};+export function getNotificationDetail(id: string) {+ return http.get(`notification/${id}`)+}// 标记通知为已读-export const markNotificationAsRead = (notificationIds: string[]) => {- return http.put(`notification/read`, { notificationIds });-};+export function markNotificationAsRead(notificationIds: string[]) {+ return http.put(`notification/read`, { notificationIds })+}// 全部标记为已读-export const markAllNotificationsAsRead = () => {- return http.put("notification/read-all");-};+export function markAllNotificationsAsRead() {+ return http.put('notification/read-all')+}// 获取未读数量-export const getUnreadCount = () => {- return http.get<UnreadCountResponse>("notification/unread-count", undefined, true);-};+export function getUnreadCount() {+ return http.get<UnreadCountResponse>('notification/unread-count', undefined, true)+}// 删除通知-export const deleteNotifications = (notificationIds: string[]) => {- return http.delete("notification", { notificationIds } );-};+export function deleteNotifications(notificationIds: string[]) {+ return http.delete('notification', { notificationIds })+}// 任务相关类型定义export interface TaskData {- targetWorksId: string;- targetAuthorId: string;- platform: string;+ targetWorksId: string+ targetAuthorId: string+ platform: string}export interface TaskItem {- id: string;- title: string;- description: string;- type: string;- maxRecruits: number;- currentRecruits: number;- deadline: string;- reward: number;- status: string;- accountTypes: string[];- taskData: TaskData;- materials: string[];- createdAt: string;- updatedAt: string;- opportunityId: string;- opportunityStatus: string;- expiredAt: string;- accountId: string;- materialIds: string[];+ id: string+ title: string+ description: string+ type: string+ maxRecruits: number+ currentRecruits: number+ deadline: string+ reward: number+ status: string+ accountTypes: string[]+ taskData: TaskData+ materials: string[]+ createdAt: string+ updatedAt: string+ opportunityId: string+ opportunityStatus: string+ expiredAt: string+ accountId: string+ materialIds: string[]}export interface TaskResponse {- data: TaskItem;+ data: TaskItem}// 获取任务详情-export const getTaskDetail = (opportunityId: string) => {- return http.get<TaskResponse>(`task/task/opportunity/info/${opportunityId}`);-};+export function getTaskDetail(opportunityId: string) {+ return http.get<TaskResponse>(`task/task/opportunity/info/${opportunityId}`)+}// 接受任务-export const acceptTask = (taskId: string, opportunityId: string, accountId?: string) => {- return http.post("task/accept", { taskId, opportunityId, accountId });-};+export function acceptTask(taskId: string, opportunityId: string, accountId?: string) {+ return http.post('task/accept', { taskId, opportunityId, accountId })+}// 提交任务-export const submitTask = (userTaskId: string, materialId: string) => {- return http.post("task/submit", { userTaskId: userTaskId, materialId });-};\ No newline at end of file+export function submitTask(userTaskId: string, materialId: string) {+ return http.post('task/submit', { userTaskId, materialId })+}diff --git a/project/web/src/api/oss.ts b/project/web/src/api/oss.tsindex 9d22908e..81357d76 100644--- a/project/web/src/api/oss.ts+++ b/project/web/src/api/oss.ts@@ -1,95 +1,88 @@-import { request } from "@/utils/request";-import md5 from "blueimp-md5";-import { useUserStore } from "@/store/user";+import md5 from 'blueimp-md5'+import { useUserStore } from '@/store/user'+import { request } from '@/utils/request'export interface UploadToOssOptions {- onProgress?: (prog: number) => void;- signal?: AbortSignal;+ onProgress?: (prog: number) => void+ signal?: AbortSignal}// 获取 AWS S3 presigned post 数据-const getPresignedPostData = async (- fileName: string,- fileSize: number,- contentType: string,-) => {+async function getPresignedPostData(fileName: string, fileSize: number, contentType: string) {const res: any = await request({- url: "file/uploadUrl",- method: "GET",+ url: 'file/uploadUrl',+ method: 'GET',params: {key: fileName,- contentType: contentType,- fileSize: fileSize,+ contentType,+ fileSize,},- });+ })if (res.code !== 0) {- throw new Error("获取上传URL失败");+ throw new Error('获取上传URL失败')}- return res.data;-};+ return res.data+}// 上传文件到OSS (前端直传 AWS S3)-export const uploadToOss = async (- file: File | Blob,- options?: UploadToOssOptions | ((prog: number) => void),-) => {+export async function uploadToOss(file: File | Blob, options?: UploadToOssOptions | ((prog: number) => void)) {try {- const opts: UploadToOssOptions =- typeof options === "function" ? { onProgress: options } : (options ?? {});+ const opts: UploadToOssOptions+ = typeof options === 'function' ? { onProgress: options } : (options ?? {})if (opts.signal?.aborted) {- throw new DOMException("上传已取消", "AbortError");+ throw new DOMException('上传已取消', 'AbortError')}// 获取文件信息- const originalFileName = (file as any).name || `file_${Date.now()}`;+ const originalFileName = (file as any).name || `file_${Date.now()}`// 检查文件名是否包含中文- const hasChinese = /[\u4e00-\u9fa5]/.test(originalFileName);+ const hasChinese = /[\u4E00-\u9FA5]/.test(originalFileName)// 获取文件扩展名- const fileExtension = originalFileName.includes(".")- ? originalFileName.substring(originalFileName.lastIndexOf("."))- : "";+ const fileExtension = originalFileName.includes('.')+ ? originalFileName.substring(originalFileName.lastIndexOf('.'))+ : ''// 如果包含中文,对文件名进行MD5处理;否则使用原文件名const processedFileName = hasChinese- ? md5(originalFileName.replace(fileExtension, "")) + fileExtension- : originalFileName;+ ? md5(originalFileName.replace(fileExtension, '')) + fileExtension+ : originalFileName- const fileName =- useUserStore.getState().userInfo?.id +- "/" +- md5(new Date().getTime().toString()) +- processedFileName;- const fileSize = file.size;- const contentType = file.type || "application/octet-stream";+ const fileName+ = `${useUserStore.getState().userInfo?.id+ }/${+ md5(new Date().getTime().toString())+ }${processedFileName}`+ const fileSize = file.size+ const contentType = file.type || 'application/octet-stream'// 获取 presigned post 数据const presignedData = await getPresignedPostData(fileName,fileSize,contentType,- );+ )// 创建 FormData 用于直传 (按照 AWS S3 presigned post 要求)- const formData = new FormData();+ const formData = new FormData()// 按照官方示例的顺序添加字段// 1. 首先添加 key (文件名)if (presignedData.fields.key) {- formData.append("key", presignedData.fields.key);+ formData.append('key', presignedData.fields.key)}// 2. 添加其他隐藏字段 (按字母顺序)const fieldKeys = Object.keys(presignedData.fields).filter(- (key) => key !== "key",- );+ key => key !== 'key',+ )fieldKeys.sort().forEach((key) => {- formData.append(key, presignedData.fields[key]);- });+ formData.append(key, presignedData.fields[key])+ })// 3. 添加 Content-Type (如果存在)// if (contentType && !presignedData.fields['Content-Type']) {@@ -97,64 +90,67 @@ export const uploadToOss = async (// }// 4. 最后添加文件 (必须是最后一个字段)- formData.append("file", file);+ formData.append('file', file)// 直传文件到 AWS S3 (支持进度回调)if (opts.onProgress) {return new Promise((resolve, reject) => {- const xhr = new XMLHttpRequest();+ const xhr = new XMLHttpRequest()// 监听上传进度- xhr.upload.addEventListener("progress", (event) => {+ xhr.upload.addEventListener('progress', (event) => {if (event.lengthComputable) {- const progress = Math.round((event.loaded / event.total) * 100);- opts.onProgress?.(progress);+ const progress = Math.round((event.loaded / event.total) * 100)+ opts.onProgress?.(progress)}- });+ })const handleAbort = () => {- xhr.abort();- reject(new DOMException("上传失败: 用户取消", "AbortError"));- };+ xhr.abort()+ reject(new DOMException('上传失败: 用户取消', 'AbortError'))+ }- opts.signal?.addEventListener("abort", handleAbort, { once: true });+ opts.signal?.addEventListener('abort', handleAbort, { once: true })// 监听上传完成- xhr.addEventListener("load", () => {- opts.signal?.removeEventListener("abort", handleAbort);+ xhr.addEventListener('load', () => {+ opts.signal?.removeEventListener('abort', handleAbort)if (xhr.status >= 200 && xhr.status < 300) {- resolve(presignedData.fields.key);- } else {- reject(new Error(`上传失败: ${xhr.statusText}`));+ resolve(presignedData.fields.key)+ }+ else {+ reject(new Error(`上传失败: ${xhr.statusText}`))}- });+ })// 监听上传错误- xhr.addEventListener("error", () => {- opts.signal?.removeEventListener("abort", handleAbort);- reject(new Error("上传失败: 网络错误"));- });+ xhr.addEventListener('error', () => {+ opts.signal?.removeEventListener('abort', handleAbort)+ reject(new Error('上传失败: 网络错误'))+ })// 开始上传- xhr.open("POST", presignedData.url);- xhr.send(formData);- });- } else {+ xhr.open('POST', presignedData.url)+ xhr.send(formData)+ })+ }+ else {// 不使用进度回调的简单版本const uploadResponse = await fetch(presignedData.url, {- method: "POST",+ method: 'POST',body: formData,signal: opts.signal,- });+ })if (!uploadResponse.ok) {- throw new Error(`上传失败: ${uploadResponse.statusText}`);+ throw new Error(`上传失败: ${uploadResponse.statusText}`)}- return presignedData.fields.key;+ return presignedData.fields.key}- } catch (error) {- console.error("上传文件失败:", error);- throw error;}-};+ catch (error) {+ console.error('上传文件失败:', error)+ throw error+ }+}diff --git a/project/web/src/api/payment.ts b/project/web/src/api/payment.tsindex a8c9e43e..82abf37c 100644--- a/project/web/src/api/payment.ts+++ b/project/web/src/api/payment.ts@@ -1,75 +1,75 @@-import { request } from '@/utils/request';-import type {- Order,- OrderListParams,+import type {+ Order,+ OrderListParams,+ PaginatedResponse,+ PaymentApiResponse,+ RefundParams,SubscriptionListParams,- RefundParams,UnsubscribeParams,- PaymentApiResponse,- PaginatedResponse-} from './types/payment';+} from './types/payment'+import { request } from '@/utils/request'/*** 获取订单列表*/-export const getOrderListApi = (params: OrderListParams) => {+export function getOrderListApi(params: OrderListParams) {return request<PaginatedResponse<Order>>({url: 'payment/checkout',method: 'GET',- params- });-};+ params,+ })+}/*** 查询单个订单*/-export const getOrderDetailApi = (id: string) => {+export function getOrderDetailApi(id: string) {return request<Order>({url: `payment/checkout/${id}`,- method: 'GET'- });-};+ method: 'GET',+ })+}/*** 获取订阅列表*/-export const getSubscriptionListApi = (params: SubscriptionListParams) => {+export function getSubscriptionListApi(params: SubscriptionListParams) {return request<PaginatedResponse<Order>>({url: 'payment/subscriptions',method: 'GET',- params- });-};+ params,+ })+}/*** 订单退款*/-export const refundOrderApi = (params: RefundParams) => {+export function refundOrderApi(params: RefundParams) {return request<any>({url: 'payment/refund',method: 'POST',- data: params- });-};+ data: params,+ })+}/*** 退订*/-export const unsubscribeApi = (params: any) => {+export function unsubscribeApi(params: any) {return request<any>({url: `payment/subscriptions/${params.id}/cancel`,method: 'POST',- data: params- });-};+ data: params,+ })+}/*** 恢复订阅*/-export const cancelSubscriptionApi = (params: any) => {+export function cancelSubscriptionApi(params: any) {return request<any>({url: `payment/subscriptions/${params.id}/resume`,method: 'POST',- data: params- });-};\ No newline at end of file+ data: params,+ })+}diff --git a/project/web/src/api/pinterest.ts b/project/web/src/api/pinterest.tsindex 07d81f68..c0f4ad9c 100644--- a/project/web/src/api/pinterest.ts+++ b/project/web/src/api/pinterest.ts@@ -1,56 +1,56 @@-import http from "@/utils/request";+import http from '@/utils/request'// 获取广告账户-export const getPinterestAccountApi = (adAccountId: string) => {- return http.get<any>(`plat/pinterest/account/${adAccountId}`);-};+export function getPinterestAccountApi(adAccountId: string) {+ return http.get<any>(`plat/pinterest/account/${adAccountId}`)+}// 创建广告用户-export const createPinterestAdAccountApi = (adAccountId: string) => {- return http.get<any>(`plat/pinterest/AdAccount/${adAccountId}`);-};+export function createPinterestAdAccountApi(adAccountId: string) {+ return http.get<any>(`plat/pinterest/AdAccount/${adAccountId}`)+}// 获取pinterest账户列表-export const getPinterestAccountListApi = () => {- return http.get<any>("plat/pinterest/account");-};+export function getPinterestAccountListApi() {+ return http.get<any>('plat/pinterest/account')+}// 创建board-export const createPinterestBoardApi = (data: any, accountId: string) => {- return http.post<any>("plat/pinterest/board", { ...data, accountId });-};+export function createPinterestBoardApi(data: any, accountId: string) {+ return http.post<any>('plat/pinterest/board', { ...data, accountId })+}// 获取board列表信息-export const getPinterestBoardListApi = (params: any, accountId: string) => {- return http.get<any>("plat/pinterest/board", { ...params, accountId });-};+export function getPinterestBoardListApi(params: any, accountId: string) {+ return http.get<any>('plat/pinterest/board', { ...params, accountId })+}// 获取单个board-export const getPinterestBoardApi = (id: string, accountId: string) => {- return http.get<any>(`plat/pinterest/board/${id}`, { accountId });-};+export function getPinterestBoardApi(id: string, accountId: string) {+ return http.get<any>(`plat/pinterest/board/${id}`, { accountId })+}// 删除单个board-export const deletePinterestBoardApi = (id: string, accountId: string) => {- return http.delete<any>(`plat/pinterest/board/${id}`, { accountId });-};+export function deletePinterestBoardApi(id: string, accountId: string) {+ return http.delete<any>(`plat/pinterest/board/${id}`, { accountId })+}// 创建pin-export const createPinterestPinApi = (data: any, accountId: string) => {- return http.post<any>("plat/pinterest/pin", { ...data, accountId });-};+export function createPinterestPinApi(data: any, accountId: string) {+ return http.post<any>('plat/pinterest/pin', { ...data, accountId })+}// 获取pin列表-export const getPinterestPinListApi = (params: any, accountId: string) => {- return http.get<any>("plat/pinterest/pin", { ...params, accountId });-};+export function getPinterestPinListApi(params: any, accountId: string) {+ return http.get<any>('plat/pinterest/pin', { ...params, accountId })+}// 获取单个pin-export const getPinterestPinApi = (id: string, accountId: string) => {- return http.get<any>(`plat/pinterest/pin/${id}`, { accountId });-};+export function getPinterestPinApi(id: string, accountId: string) {+ return http.get<any>(`plat/pinterest/pin/${id}`, { accountId })+}// 删除pin-export const deletePinterestPinApi = (id: string, accountId: string) => {- return http.delete<any>(`plat/pinterest/pin/${id}`, { accountId });-};\ No newline at end of file+export function deletePinterestPinApi(id: string, accountId: string) {+ return http.delete<any>(`plat/pinterest/pin/${id}`, { accountId })+}diff --git a/project/web/src/api/plat/bilibili.ts b/project/web/src/api/plat/bilibili.tsindex 2f12f03a..55e6579d 100644--- a/project/web/src/api/plat/bilibili.ts+++ b/project/web/src/api/plat/bilibili.ts@@ -1,6 +1,6 @@+import type { BiblPartItem } from '@/components/PublishDialog/publishDialog.type'// 创建或更新账户-import http from "@/utils/request";-import { BiblPartItem } from "@/components/PublishDialog/publishDialog.type";+import http from '@/utils/request'/*** 获取B站登录地址@@ -8,43 +8,43 @@ import { BiblPartItem } from "@/components/PublishDialog/publishDialog.type";* @param spaceId 空间ID(可选)* @returns*/-export const apiGetBilibiliLoginUrl = (type: "h5" | "pc", spaceId?: string) => {- const params = spaceId ? { spaceId } : {};- return http.get<{ code: number; data: { taskId: string; url: string } }>(+export function apiGetBilibiliLoginUrl(type: 'h5' | 'pc', spaceId?: string) {+ const params = spaceId ? { spaceId } : {}+ return http.get<{ code: number, data: { taskId: string, url: string } }>(`plat/bilibili/auth/url/${type}`,- params- );-};+ params,+ )+}/*** 检查B站授权状态* @param accointId 账号ID* @returns*/-export const apiCheckAccountAuthStatus = (accointId: string) => {- return http.get<{ code: number; data: boolean }>(+export function apiCheckAccountAuthStatus(accointId: string) {+ return http.get<{ code: number, data: boolean }>(`plat/bilibili/auth/status/${accointId}`,- );-};+ )+}/*** 获取B站授权状态* @param taskId 任务ID* @returns*/-export const apiCheckBilibiliAuth = (taskId: string) => {- return http.post<{ code: number; data: any }>(+export function apiCheckBilibiliAuth(taskId: string) {+ return http.post<{ code: number, data: any }>(`plat/bilibili/auth/create-account/${taskId}`,- );-};+ )+}/*** 获取B站分区列表* @param accountId 账户ID* @returns*/-export const apiGetBilibiliPartitions = (accountId: string) => {+export function apiGetBilibiliPartitions(accountId: string) {return http.get<BiblPartItem[]>(`plat/bilibili/archive/type/list/${accountId}`,- );-};+ )+}diff --git a/project/web/src/api/plat/dataCube.ts b/project/web/src/api/plat/dataCube.tsindex db3ce2fd..2237a84e 100644--- a/project/web/src/api/plat/dataCube.ts+++ b/project/web/src/api/plat/dataCube.ts@@ -1,22 +1,22 @@// 渠道数据-import http from "@/utils/request";+import http from '@/utils/request'/*** 获取账号统计数据* @returns*/-export const apiGetAccountDataCube = (accountId: string) => {- return http.get<{ code: number; data: any }>(+export function apiGetAccountDataCube(accountId: string) {+ return http.get<{ code: number, data: any }>(`channel/dataCube/accountDataCube/${accountId}`,- );-};+ )+}/*** 获取账号增量数据* @returns*/-export const apiGetAccountDataBulk = (accountId: string) => {- return http.get<{ code: number; data: any }>(+export function apiGetAccountDataBulk(accountId: string) {+ return http.get<{ code: number, data: any }>(`channel/dataCube/getAccountDataBulk/${accountId}`,- );-};\ No newline at end of file+ )+}diff --git a/project/web/src/api/plat/facebook.ts b/project/web/src/api/plat/facebook.tsindex 19f1e56d..5c92225d 100644--- a/project/web/src/api/plat/facebook.ts+++ b/project/web/src/api/plat/facebook.ts@@ -1,16 +1,16 @@// Facebook API接口-import http from "@/utils/request";+import http from '@/utils/request'export interface FacebookPageItem {- id: string;- name: string;+ id: string+ name: string}export interface FacebookPagesResponse {- data: FacebookPageItem[];- code: number;- message: string;- url: string;+ data: FacebookPageItem[]+ code: number+ message: string+ url: string}/**@@ -18,19 +18,19 @@ export interface FacebookPagesResponse {* @param accountId 账户ID* @returns*/-export const apiGetFacebookPages = (accountId: string) => {+export function apiGetFacebookPages(accountId: string) {return http.get<FacebookPagesResponse>(`plat/meta/facebook/pages`,- );-};+ )+}/*** 提交Facebook页面选择* @param pageIds 选择的页面ID数组* @returns*/-export const apiSubmitFacebookPages = (pageIds: string[]) => {+export function apiSubmitFacebookPages(pageIds: string[]) {return http.post(`plat/meta/facebook/pages`, {pageIds,- });-};\ No newline at end of file+ })+}diff --git a/project/web/src/api/plat/interact.ts b/project/web/src/api/plat/interact.tsindex cc040bbf..b62be060 100644--- a/project/web/src/api/plat/interact.ts+++ b/project/web/src/api/plat/interact.ts@@ -1,67 +1,64 @@// 渠道互动-import http from "@/utils/request";+import http from '@/utils/request'/*** 创建作品评论* @returns*/-export const apiAddArcComment = (data: {- accountId: string;- dataId: string;- content: string;-}) => {- return http.post<{ code: number; data: any }>(+export function apiAddArcComment(data: {+ accountId: string+ dataId: string+ content: string+}) {+ return http.post<{ code: number, data: any }>(`channel/interact/addArcComment`,data,- );-};+ )+}/*** 获取作品的评论列表* @returns*/-export const apiGetArcCommentList = (- page: {- pageNo: number;- pageSize: number;- },- recordId: string,-) => {- return http.get<{ code: number; data: any }>(+export function apiGetArcCommentList(page: {+ pageNo: number+ pageSize: number+}, recordId: string) {+ return http.get<{ code: number, data: any }>(`channel/interact/getArcCommentList/${page.pageNo}/${page.pageSize}`,{params: {recordId,},},- );-};+ )+}/*** 回复评论* @returns*/-export const apiReplyComment = (data: {- accountId: string;- commentId: string;- content: string;-}) => {- return http.post<{ code: number; data: any }>(+export function apiReplyComment(data: {+ accountId: string+ commentId: string+ content: string+}) {+ return http.post<{ code: number, data: any }>(`channel/interact/replyComment`,data,- );-};+ )+}/*** 删除评论* @returns*/-export const apiDelComment = (data: {- accountId: string;- commentId: string;-}) => {- return http.delete<{ code: number; data: any }>(+export function apiDelComment(data: {+ accountId: string+ commentId: string+}) {+ return http.delete<{ code: number, data: any }>(`channel/interact/delComment`,data,- );-};+ )+}diff --git a/project/web/src/api/plat/kwai.ts b/project/web/src/api/plat/kwai.tsindex 3e233b29..45acb686 100644--- a/project/web/src/api/plat/kwai.ts+++ b/project/web/src/api/plat/kwai.ts@@ -1,5 +1,5 @@-import http from "@/utils/request";-import { GetKwaiAuthStatusRes } from "@/api/plat/types/kwai.types";+import type { GetKwaiAuthStatusRes } from '@/api/plat/types/kwai.types'+import http from '@/utils/request'/*** 创建快手授权@@ -7,17 +7,17 @@ import { GetKwaiAuthStatusRes } from "@/api/plat/types/kwai.types";* @param spaceId 空间ID(可选)* @returns*/-export const createKwaiAuth = (type: "h5" | "pc", spaceId?: string) => {- const params = spaceId ? { spaceId } : {};+export function createKwaiAuth(type: 'h5' | 'pc', spaceId?: string) {+ const params = spaceId ? { spaceId } : {}return http.get<{- url: string;- taskId: string;- }>(`plat/kwai/auth/url/${type}`, params);-};+ url: string+ taskId: string+ }>(`plat/kwai/auth/url/${type}`, params)+}// 获取账号授权状态-export const getKwaiAuthStatus = (taskId: string) => {+export function getKwaiAuthStatus(taskId: string) {return http.post<GetKwaiAuthStatusRes>(`plat/kwai/auth/create-account/${taskId}`,- );-};+ )+}diff --git a/project/web/src/api/plat/publish.ts b/project/web/src/api/plat/publish.tsindex 194150d5..b02626fe 100644--- a/project/web/src/api/plat/publish.ts+++ b/project/web/src/api/plat/publish.ts@@ -1,82 +1,80 @@-// 创建发布-import { request } from "@/utils/request";-import {+import type {GetPublishListParams,PublishParams,PublishRecordItem,-} from "@/api/plat/types/publish.types";-import { parseTopicString } from "@/utils";-import { PlatType } from "@/app/config/platConfig";-import { IPlatOption } from "@/components/PublishDialog/publishDialog.type";+} from '@/api/plat/types/publish.types'+import type { PlatType } from '@/app/config/platConfig'+import type { IPlatOption } from '@/components/PublishDialog/publishDialog.type'+import { parseTopicString } from '@/utils'+// 创建发布+import { request } from '@/utils/request'// 根据平台类型过滤option参数-const filterOptionByPlatform = (- option: IPlatOption,- accountType: PlatType,-): IPlatOption => {- if (!option) return {};- const key = accountType as keyof IPlatOption;- return option[key] ? ({ [key]: option[key] } as IPlatOption) : {};-};+function filterOptionByPlatform(option: IPlatOption, accountType: PlatType): IPlatOption {+ if (!option)+ return {}+ const key = accountType as keyof IPlatOption+ return option[key] ? ({ [key]: option[key] } as IPlatOption) : {}+}// 创建发布-export const apiCreatePublish = (data: PublishParams) => {- const { topics, cleanedString } = parseTopicString(data.desc || "");- data.topics = [...new Set(data.topics?.concat(topics))];- data.desc = cleanedString;+export function apiCreatePublish(data: PublishParams) {+ const { topics, cleanedString } = parseTopicString(data.desc || '')+ data.topics = [...new Set(data.topics?.concat(topics))]+ data.desc = cleanedString// 根据accountType过滤option参数- data.option = filterOptionByPlatform(data.option, data.accountType);+ data.option = filterOptionByPlatform(data.option, data.accountType)return request({- url: "plat/publish/create",- method: "POST",+ url: 'plat/publish/create',+ method: 'POST',data,- });-};+ })+}// 查询发布列表-export const getPublishList = (data: GetPublishListParams) => {+export function getPublishList(data: GetPublishListParams) {return request<PublishRecordItem[]>({- url: "plat/publish/posts",- method: "POST",+ url: 'plat/publish/posts',+ method: 'POST',data,- });-};+ })+}// 查询发布队列(列表模式使用的新接口)-export const getPublishQueue = (data: any) => {+export function getPublishQueue(data: any) {return request<PublishRecordItem[]>({- url: "plat/publish/statuses/queued/posts",- method: "POST",+ url: 'plat/publish/statuses/queued/posts',+ method: 'POST',data,- });-};+ })+}// 修改发布任务时间-export const updatePublishRecordTimeApi = (data: {- id: string;- publishTime: string;-}) => {+export function updatePublishRecordTimeApi(data: {+ id: string+ publishTime: string+}) {return request({- url: "plat/publish/updateTaskTime",- method: "POST",+ url: 'plat/publish/updateTaskTime',+ method: 'POST',data,- });-};+ })+}// 删除发布任务-export const deletePublishRecordApi = (id: string) => {+export function deletePublishRecordApi(id: string) {return request({url: `plat/publish/delete/${id}`,- method: "DELETE",- });-};+ method: 'DELETE',+ })+}// 立即发布任务-export const nowPubTaskApi = (id: string) => {+export function nowPubTaskApi(id: string) {return request({url: `plat/publish/nowPubTask/${id}`,- method: "POST",- });-};+ method: 'POST',+ })+}diff --git a/project/web/src/api/plat/threads.ts b/project/web/src/api/plat/threads.tsindex d156dbf3..5f63c596 100644--- a/project/web/src/api/plat/threads.ts+++ b/project/web/src/api/plat/threads.ts@@ -1,14 +1,14 @@// Threads API接口-import http from "@/utils/request";+import http from '@/utils/request'export interface ThreadsLocationItem {- id: string;- label: string;+ id: string+ label: string}export interface ThreadsLocationsResponse {- data: ThreadsLocationItem[];- code: number;+ data: ThreadsLocationItem[]+ code: number}/**@@ -17,13 +17,13 @@ export interface ThreadsLocationsResponse {* @param keyword 搜索关键词(可选)* @returns*/-export const apiGetThreadsLocations = (accountId: string, keyword?: string) => {- const params: any = { accountId };+export function apiGetThreadsLocations(accountId: string, keyword?: string) {+ const params: any = { accountId }if (keyword) {- params.keyword = keyword;+ params.keyword = keyword}return http.get<ThreadsLocationsResponse>(`plat/meta/threads/locations`,- params- );-};+ params,+ )+}diff --git a/project/web/src/api/plat/types/kwai.types.ts b/project/web/src/api/plat/types/kwai.types.tsindex 6ec5cfb7..186b6d47 100644--- a/project/web/src/api/plat/types/kwai.types.ts+++ b/project/web/src/api/plat/types/kwai.types.ts@@ -1,10 +1,10 @@export interface GetKwaiAuthStatusRes {- taskId: string;- transpond?: string;- accountAddPath?: string;+ taskId: string+ transpond?: string+ accountAddPath?: stringdata?: {- userId: string;- };- status: -1 | 0 | 1;- error?: string;+ userId: string+ }+ status: -1 | 0 | 1+ error?: string}diff --git a/project/web/src/api/plat/types/publish.types.ts b/project/web/src/api/plat/types/publish.types.tsindex 1d4d80c2..92fd9448 100644--- a/project/web/src/api/plat/types/publish.types.ts+++ b/project/web/src/api/plat/types/publish.types.ts@@ -1,5 +1,5 @@-import { PubType } from "@/app/config/publishConfig";-import { PlatType } from "@/app/config/platConfig";+import type { PlatType } from '@/app/config/platConfig'+import type { PubType } from '@/app/config/publishConfig'export enum PublishStatus {FAIL = -1, // 发布失败@@ -11,71 +11,71 @@ export enum PublishStatus {// 创建发布入参export interface PublishParams {// 传入账号UID- flowId: string;- type: PubType;- title: string;- desc?: string;+ flowId: string+ type: PubType+ title: string+ desc?: string// 传入 account- accountId: string;- accountType: PlatType;- videoUrl?: string;- coverUrl?: string;+ accountId: string+ accountType: PlatType+ videoUrl?: string+ coverUrl?: string// 图片列表- imgUrlList?: string[];+ imgUrlList?: string[]// 话题- topics?: string[];- publishTime?: string;- option?: any;- userTaskId?: string;- materialId?: string;+ topics?: string[]+ publishTime?: string+ option?: any+ userTaskId?: string+ materialId?: string}// 查询发布列表入参export interface GetPublishListParams {- accountId?: string;- accountType?: PlatType;- type?: PubType;- status?: PublishStatus;- time?: [string, string];+ accountId?: string+ accountType?: PlatType+ type?: PubType+ status?: PublishStatus+ time?: [string, string]// internal=平台发布,native=原生发布 不转则为混合- publishingChannel?: "internal" | "native";+ publishingChannel?: 'internal' | 'native'}// 发布记录item数据export interface PublishRecordItem {- userId: string;- flowId: string;- userTaskId: string;- taskId: string;- taskMaterialId: string;- type: string;- title: string;- desc: string;- accountId: string;- topics: string[];- accountType: PlatType;- uid: string;- videoUrl: string;- coverUrl: string;- imgUrlList: string[];- publishTime: Date;- status: PublishStatus;- inQueue: boolean;- dataId: string;- workLink: string;- createdAt: string;- updatedAt: string;- id: string;- errorMsg: string;- engagement?: PublishRecordEngagement;+ userId: string+ flowId: string+ userTaskId: string+ taskId: string+ taskMaterialId: string+ type: string+ title: string+ desc: string+ accountId: string+ topics: string[]+ accountType: PlatType+ uid: string+ videoUrl: string+ coverUrl: string+ imgUrlList: string[]+ publishTime: Date+ status: PublishStatus+ inQueue: boolean+ dataId: string+ workLink: string+ createdAt: string+ updatedAt: string+ id: string+ errorMsg: string+ engagement?: PublishRecordEngagement}export interface PublishRecordEngagement {- viewCount: number;- commentCount: number;- likeCount: number;- shareCount: number;- clickCount: number;- impressionCount: number;- favoriteCount: number;+ viewCount: number+ commentCount: number+ likeCount: number+ shareCount: number+ clickCount: number+ impressionCount: number+ favoriteCount: number}diff --git a/project/web/src/api/plat/youtube.ts b/project/web/src/api/plat/youtube.tsindex 916d4328..af3a909d 100644--- a/project/web/src/api/plat/youtube.ts+++ b/project/web/src/api/plat/youtube.ts@@ -1,25 +1,25 @@-import { request } from "@/utils/request";-import { YouTubeCategoryItem } from "@/components/PublishDialog/publishDialog.type";+import type { YouTubeCategoryItem } from '@/components/PublishDialog/publishDialog.type'+import { request } from '@/utils/request'// 获取YouTube国区参数-export const apiGetYouTubeRegions = (account: string) => {+export function apiGetYouTubeRegions(account: string) {return request({- url: "plat/youtube/common/params",- method: "GET",+ url: 'plat/youtube/common/params',+ method: 'GET',params: {- account- }- });-};+ account,+ },+ })+}// 获取YouTube视频分类-export const apiGetYouTubeCategories = (accountId: string, regionCode: string) => {+export function apiGetYouTubeCategories(accountId: string, regionCode: string) {return request<YouTubeCategoryItem[]>({- url: "plat/youtube/video/categories",- method: "GET",+ url: 'plat/youtube/video/categories',+ method: 'GET',params: {- accountId,- regionCode- }- });-};\ No newline at end of file+ accountId,+ regionCode,+ },+ })+}diff --git a/project/web/src/api/platAuth.ts b/project/web/src/api/platAuth.tsindex c1cda848..56da7be1 100644--- a/project/web/src/api/platAuth.ts+++ b/project/web/src/api/platAuth.ts@@ -1,63 +1,59 @@-import http from "@/utils/request";-import { request } from "@/utils/request";+import http, { request } from '@/utils/request'// 获取 YouTube 授权 URL-export const getYouTubeAuthUrlApi = (mail: string, spaceId?: string) => {- const params: any = { type: 'pc' };+export function getYouTubeAuthUrlApi(mail: string, spaceId?: string) {+ const params: any = { type: 'pc' }if (spaceId) {- params.spaceId = spaceId;+ params.spaceId = spaceId}return request({url: 'plat/youtube/auth/url',method: 'GET',params,- });-};-+ })+}/*** 获取youtube授权状态* @param taskId 任务ID* @returns*/-export const apiCheckYoutubeAuth = (taskId: string) => {- return http.post<{ code: number; data: any }>(+export function apiCheckYoutubeAuth(taskId: string) {+ return http.post<{ code: number, data: any }>(`plat/youtube/auth/create-account/${taskId}`,- );-};+ )+}-export const checkYouTubeAuthApi = ( data:any ) => {+export function checkYouTubeAuthApi(data: any) {return request({url: `plat/youtube/auth/status/${data.accountId}`,method: 'GET',- });-};+ })+}-export const uploadYouTubeVideoApi = (data: FormData) => {+export function uploadYouTubeVideoApi(data: FormData) {return request({url: 'plat/youtube/videos/upload',method: 'POST',body: data,- });-};-+ })+}-export const uploadYouTubeVideoSmallApi = (data: FormData) => {+export function uploadYouTubeVideoSmallApi(data: FormData) {return request({url: 'plat/youtube/video/upload/small',method: 'POST',body: data,- });-};+ })+}-export const getYouTubeListApi = (data: any) => {+export function getYouTubeListApi(data: any) {return request({url: 'plat/youtube/videos/list',method: 'GET',params: data,- });-};-+ })+}/*** 获取facebook授权状态@@ -65,30 +61,26 @@ export const getYouTubeListApi = (data: any) => {* @param spaceId 空间ID(可选)* @returns*/-export const getFacebookAuthUrlApi = (mail: string, spaceId?: string) => {+export function getFacebookAuthUrlApi(mail: string, spaceId?: string) {const data: any = {platform: 'facebook',- };+ }if (spaceId) {- data.spaceId = spaceId;+ data.spaceId = spaceId}return request({url: 'plat/meta/auth/url',method: 'POST',data,- });-};-+ })+}---export const checkMetaAuthApi = ( taskId:any ) => {+export function checkMetaAuthApi(taskId: any) {return request({url: `plat/meta/auth/info/${taskId}`,method: 'GET',- });-};-+ })+}/*** 获取instagram授权状态@@ -96,21 +88,19 @@ export const checkMetaAuthApi = ( taskId:any ) => {* @param spaceId 空间ID(可选)* @returns*/-export const getInstagramAuthUrlApi = (mail: string, spaceId?: string) => {+export function getInstagramAuthUrlApi(mail: string, spaceId?: string) {const data: any = {platform: 'instagram',- };+ }if (spaceId) {- data.spaceId = spaceId;+ data.spaceId = spaceId}return request({url: 'plat/meta/auth/url',method: 'POST',data,- });-};--+ })+}/*** 获取threads授权状态@@ -118,19 +108,19 @@ export const getInstagramAuthUrlApi = (mail: string, spaceId?: string) => {* @param spaceId 空间ID(可选)* @returns*/-export const getThreadsAuthUrlApi = (mail: string, spaceId?: string) => {+export function getThreadsAuthUrlApi(mail: string, spaceId?: string) {const data: any = {platform: 'threads',- };+ }if (spaceId) {- data.spaceId = spaceId;+ data.spaceId = spaceId}return request({url: 'plat/meta/auth/url',method: 'POST',data,- });-};+ })+}/*** 获取linkedin授权链接@@ -138,20 +128,19 @@ export const getThreadsAuthUrlApi = (mail: string, spaceId?: string) => {* @param mail 邮箱* @param spaceId 空间ID(可选)*/-export const getLinkedInAuthUrlApi = (mail: string, spaceId?: string) => {+export function getLinkedInAuthUrlApi(mail: string, spaceId?: string) {const data: any = {platform: 'linkedin',- };+ }if (spaceId) {- data.spaceId = spaceId;+ data.spaceId = spaceId}return request({url: 'plat/meta/auth/url',method: 'POST',data,- });-};-+ })+}/*** 获取tiktok授权状态@@ -159,46 +148,44 @@ export const getLinkedInAuthUrlApi = (mail: string, spaceId?: string) => {* @param spaceId 空间ID(可选)* @returns*/-export const getTiktokAuthUrlApi = (mail: string, spaceId?: string) => {- const data: any = { type: 'pc' };+export function getTiktokAuthUrlApi(mail: string, spaceId?: string) {+ const data: any = { type: 'pc' }if (spaceId) {- data.spaceId = spaceId;+ data.spaceId = spaceId}return request({url: 'plat/tiktok/auth/url',- method: 'POST',+ method: 'POST',data,- });-};+ })+}-export const checkTiktokAuthApi = ( taskId:any ) => {+export function checkTiktokAuthApi(taskId: any) {return request({url: `plat/tiktok/auth/info/${taskId}`,method: 'GET',- });-};-+ })+}// 微信授权-export const getWxGzhAuthUrlApi = (mail: string, spaceId?: string) => {- const params: any = { type: 'pc' };+export function getWxGzhAuthUrlApi(mail: string, spaceId?: string) {+ const params: any = { type: 'pc' }if (spaceId) {- params.spaceId = spaceId;+ params.spaceId = spaceId}return request({url: 'plat/wxGzh/auth/url/pc',- method: 'GET',+ method: 'GET',params,- });-};+ })+}-export const checkWxGzAuthApi = ( taskId:any ) => {+export function checkWxGzAuthApi(taskId: any) {return request({url: `plat/wxGzh/auth/create-account/${taskId}`,method: 'GET',- });-};-+ })+}/*** 获取pinterest授权状态@@ -206,25 +193,24 @@ export const checkWxGzAuthApi = ( taskId:any ) => {* @param spaceId 空间ID(可选)* @returns*/-export const getPinterestAuthUrlApi = (mail: string, spaceId?: string) => {- const params: any = {};+export function getPinterestAuthUrlApi(mail: string, spaceId?: string) {+ const params: any = {}if (spaceId) {- params.spaceId = spaceId;+ params.spaceId = spaceId}return request({url: 'plat/pinterest/getAuth',method: 'GET',params,- });-};-+ })+}-export const checkPinterestAuthApi = ( taskId:any ) => {+export function checkPinterestAuthApi(taskId: any) {return request({url: `plat/pinterest/checkAuth`,method: 'GET',params: {- taskId: taskId,+ taskId,},- });-};+ })+}diff --git a/project/web/src/api/sent.ts b/project/web/src/api/sent.tsindex 629cc0cc..78379dcb 100644--- a/project/web/src/api/sent.ts+++ b/project/web/src/api/sent.ts@@ -1,17 +1,11 @@-import { request } from "@/utils/request";-import { SentPostsParams, SentPostsResponse } from "./types/sent.types";--// 获取已发布帖子列表-export const getSentPosts = (params: any) => {- // return request<SentPostsResponse>({- // url: "channel/engagement/posts",- // method: "POST",- // data: params,- // });+import type { SentPostsResponse } from './types/sent.types'+import { request } from '@/utils/request'+// Get published posts list+export function getSentPosts(params: any) {return request<SentPostsResponse>({- url: "plat/publish/posts",- method: "POST",+ url: 'plat/publish/statuses/published/posts',+ method: 'POST',data: params,- });-};+ })+}diff --git a/project/web/src/api/signIn.ts b/project/web/src/api/signIn.tsindex 44220f15..db466201 100644--- a/project/web/src/api/signIn.ts+++ b/project/web/src/api/signIn.ts@@ -5,45 +5,45 @@* @LastEditors: nevin* @Description: feedback*/-import http from "@/utils/request";+import http from '@/utils/request'export enum SignInType {- PUL_VIDEO = "pul_video",+ PUL_VIDEO = 'pul_video',}export interface SignInResponse {- success: boolean;- message?: string;- score?: number; // 签到后更新的积分- data?: any;+ success: boolean+ message?: string+ score?: number // 签到后更新的积分+ data?: any}export interface PublishDayInfo {- _id: string;- userId: string;- publishTotal: number;- createdAt: string;- updatedAt: string;+ _id: string+ userId: string+ publishTotal: number+ createdAt: string+ updatedAt: string}export interface PublishDayInfoResponse {- total: number;- list: PublishDayInfo[];+ total: number+ list: PublishDayInfo[]}export interface PublishInfoData {- _id: string;- userId: string;- days: number; // 连续签到天数- createdAt: string;- updatedAt: string;- upInfoDate: string;- id: string;+ _id: string+ userId: string+ days: number // 连续签到天数+ createdAt: string+ updatedAt: string+ upInfoDate: string+ id: string}export interface PublishInfoResponse {- code: number;- data: PublishInfoData;+ code: number+ data: PublishInfoData}export const signInApi = {@@ -53,28 +53,27 @@ export const signInApi = {async createSignInRecord(type: SignInType = SignInType.PUL_VIDEO): Promise<SignInResponse> {const res = await http.post<SignInResponse>(`reward/signIn`, {type,- });- return res!.data;+ })+ return res!.data},/*** 获取签到日历数据*/async getSignInCalendar(year: number, month: number): Promise<PublishDayInfoResponse> {- const res = await http.get<PublishDayInfoResponse>(`plat/publish/publishDayInfo/list/1/99`);- return res!.data;+ const res = await http.get<PublishDayInfoResponse>(`plat/publish/publishDayInfo/list/1/99`)+ return res!.data},/*** 获取连续签到天数*/async getConsecutiveDays(): Promise<PublishInfoResponse> {- const res:any = await http.get<PublishInfoResponse>(`plat/publish/publishInfo/data`);- return res;+ const res: any = await http.get<PublishInfoResponse>(`plat/publish/publishInfo/data`)+ return res},--};+}/*** 注销账户相关接口@@ -84,15 +83,15 @@ export const cancelAccountApi = {* 获取注销验证码*/async getCancelCode(): Promise<any> {- const res = await http.get<any>(`login/cancel/code`);- return res;+ const res = await http.get<any>(`login/cancel/code`)+ return res},/*** 注销账户*/async cancelAccount(data: { code: string }): Promise<any> {- const res = await http.delete<any>(`login/cancel`, data);- return res;+ const res = await http.delete<any>(`login/cancel`, data)+ return res},-};\ No newline at end of file+}diff --git a/project/web/src/api/statistics.ts b/project/web/src/api/statistics.tsindex 78ed03fa..3d7f94f3 100644--- a/project/web/src/api/statistics.ts+++ b/project/web/src/api/statistics.ts@@ -1,20 +1,20 @@-import http from '@/utils/request';+import http from '@/utils/request'// 导入发布记录到草稿箱export async function apiImportPostsRecord(records: Array<{- accountId: string;- platform: string;- userId: string;- uid: string;- postId: string;+ accountId: string+ platform: string+ userId: string+ uid: string+ postId: string}>) {- return http.post("statistics/channels/posts/postsRecord", {- records- });+ return http.post('statistics/channels/posts/postsRecord', {+ records,+ })}// 获取发布记录状态export async function apiGetPostsRecordStatus() {- return http.post("statistics/channels/posts/recordStatus", {- });+ return http.post('statistics/channels/posts/recordStatus', {+ })}diff --git a/project/web/src/api/task.ts b/project/web/src/api/task.tsindex 5a5aae05..3281f7a9 100644--- a/project/web/src/api/task.ts+++ b/project/web/src/api/task.ts@@ -1,5 +1,5 @@-import http from "@/utils/request";-import { AccountType } from "./types/account.type";+import type { AccountType } from './types/account.type'+import http from '@/utils/request'export enum TaskOpportunityStatus {PENDING = 'pending', // 待接取@@ -8,8 +8,8 @@ export enum TaskOpportunityStatus {}export interface TaskOpportunity {- _id: string;- id: string;+ _id: string+ id: stringtaskId: stringaccountId: stringuserId: string@@ -35,8 +35,8 @@ interface UserTaskAutoData {}export interface UserTask {- _id: string;- id: string;+ _id: string+ id: stringuserId: stringtaskId: stringaccountId: string@@ -61,64 +61,61 @@ export interface UserTask {}// 获取待接受的任务列表-export const apiGetTaskOpportunityList = (params: {- page?: number;- pageSize?: number;-}) => {- return http.get<{list: TaskOpportunity[]}>(`task/opportunity/list/${params.page}/${params.pageSize}` );-};+export function apiGetTaskOpportunityList(params: {+ page?: number+ pageSize?: number+}) {+ return http.get<{ list: TaskOpportunity[] }>(`task/opportunity/list/${params.page}/${params.pageSize}`)+}/*** 接取任务- * @param opportunityId- * @returns+ * @param opportunityId+ * @returns*/-export const apiAcceptTask = (opportunityId: string) => {- return http.post<any>(`task/accept`, { opportunityId });-};-+export function apiAcceptTask(opportunityId: string) {+ return http.post<any>(`task/accept`, { opportunityId })+}// 获取已接受的任务列表-export const apiGetUserTaskList = (params: {- page?: number;- pageSize?: number;-}) => {- return http.get<{list: UserTask[]}>(`task/userTask/list/${params.page}/${params.pageSize}` );--};-+export function apiGetUserTaskList(params: {+ page?: number+ pageSize?: number+}) {+ return http.get<{ list: UserTask[] }>(`task/userTask/list/${params.page}/${params.pageSize}`)+}/*** 已接受的任务详情- * @param id- * @returns+ * @param id+ * @returns*/-export const apiGetUserTaskDetail = (id: string) => {- return http.get<any>(`task/userTask/info/${id}`);-};+export function apiGetUserTaskDetail(id: string) {+ return http.get<any>(`task/userTask/info/${id}`)+}/*** 接取任务- * @param userTaskId- * @returns+ * @param userTaskId+ * @returns*/-export const apiSubmitTask = (userTaskId: string, submissionUrl: string) => {- return http.post<any>(`task/submit`, { userTaskId, submissionUrl });-};+export function apiSubmitTask(userTaskId: string, submissionUrl: string) {+ return http.post<any>(`task/submit`, { userTaskId, submissionUrl })+}/*** 获取未读任务数量* @returns 未读任务数量*/-export const apiGetNotViewCount = () => {- return http.put<{ count: number }>('task/opportunity/getNotViewCount');-};+export function apiGetNotViewCount() {+ return http.put<{ count: number }>('task/opportunity/getNotViewCount')+}/*** 标记任务为已读* @param opportunityId 任务机会ID- * @returns+ * @returns*/-export const apiMarkTaskAsViewed = (opportunityId: string) => {- return http.put<any>(`task/opportunity/doView/${opportunityId}`);-};\ No newline at end of file+export function apiMarkTaskAsViewed(opportunityId: string) {+ return http.put<any>(`task/opportunity/doView/${opportunityId}`)+}diff --git a/project/web/src/api/tools.ts b/project/web/src/api/tools.tsindex 86dc6e76..9d1695c6 100644--- a/project/web/src/api/tools.ts+++ b/project/web/src/api/tools.ts@@ -1,3 +1,4 @@+import type { AiCreateType } from './types/tools'/** @Author: nevin* @Date: 2025-02-22 12:02:55@@ -5,8 +6,7 @@* @LastEditors: nevin* @Description: 工具*/-import http, { request } from "@/utils/request";-import { AiCreateType } from "./types/tools";+import http, { request } from '@/utils/request'export const toolsApi = {/**@@ -16,56 +16,56 @@ export const toolsApi = {* @param max*/async apiVideoAiTitle(url: string, type: AiCreateType, max: number) {- const res = await http.post<string>("tools/ai/video/title", {+ const res = await http.post<string>('tools/ai/video/title', {url,type,max: max - 10,- });- return res!.data;+ })+ return res!.data},/*** 智能图文*/async apiReviewImgAi(data: {- imgUrl: string;- title?: string;- desc?: string;- max?: number;+ imgUrl: string+ title?: string+ desc?: string+ max?: number}) {- const res = await http.post<string>("tools/ai/reviewImg", data);- return res!.data;+ const res = await http.post<string>('tools/ai/reviewImg', data)+ return res!.data},/*** 智能评论*/- async apiReviewAi(data: { title: string; desc?: string; max?: number }) {- const res = await http.post<string>("tools/ai/review", data);- return res!.data;+ async apiReviewAi(data: { title: string, desc?: string, max?: number }) {+ const res = await http.post<string>('tools/ai/review', data)+ return res!.data},/*** 智能评论回复*/async apiReviewAiRecover(data: {- content: string;- title?: string;- desc?: string;- max?: number;+ content: string+ title?: string+ desc?: string+ max?: number}) {- const res = await http.post<string>("tools/ai/recover/review", data);- return res!.data;+ const res = await http.post<string>('tools/ai/recover/review', data)+ return res!.data},/*** 生成AI的html图文 弃用: 时间太长得走sse*/async aiArticleHtml(content: string) {- const res = await http.post<string>("tools/ai/article/html", {+ const res = await http.post<string>('tools/ai/article/html', {content,- });- return res!.data;+ })+ return res!.data},// TODO: sse生成AI的html图文@@ -74,9 +74,9 @@ export const toolsApi = {* 文本内容安全*/async textModeration(content: string) {- const res = await http.post<string>("aliGreen/textGreen", {+ const res = await http.post<string>('aliGreen/textGreen', {content,- });- return res;+ })+ return res},-};+}diff --git a/project/web/src/api/twitter.ts b/project/web/src/api/twitter.tsindex ec4eb758..3376146f 100644--- a/project/web/src/api/twitter.ts+++ b/project/web/src/api/twitter.ts@@ -1,29 +1,25 @@-import http from "@/utils/request";-import { request } from "@/utils/request";+import http, { request } from '@/utils/request'// 获取 Twitter 授权 URL-export const getTwitterAuthUrlApi = (mail: string, spaceId?: string) => {- const data: any = {};+export function getTwitterAuthUrlApi(mail: string, spaceId?: string) {+ const data: any = {}if (spaceId) {- data.spaceId = spaceId;+ data.spaceId = spaceId}return request({url: 'plat/twitter/auth/url',method: 'POST',data,- });-};-+ })+}/*** 获取youtube授权状态* @param taskId 任务ID* @returns*/-export const apiCheckTwitterAuth = (taskId: string) => {- return http.get<{ code: number; data: any }>(+export function apiCheckTwitterAuth(taskId: string) {+ return http.get<{ code: number, data: any }>(`plat/twitter/auth/info/${taskId}`,- );-};--+ )+}diff --git a/project/web/src/api/types/account.type.ts b/project/web/src/api/types/account.type.tsindex 2c1fc7ff..c9d267ad 100644--- a/project/web/src/api/types/account.type.ts+++ b/project/web/src/api/types/account.type.ts@@ -1,4 +1,4 @@-import { PlatType } from "@/app/config/platConfig";+import type { PlatType } from '@/app/config/platConfig'export enum AccountType {Douyin = 'douyin', // 抖音@@ -17,51 +17,51 @@ export enum AccountType {// 三方账户类型定义export interface SocialAccount {- id: string;- type: PlatType;- loginCookie?: string;- access_token?: string;- refresh_token?: string;- loginTime: string;- uid: string;- account: string;- avatar: string;- nickname: string;- fansCount: number;- readCount: number;- likeCount: number;- collectCount: number;- forwardCount: number;- commentCount: number;- lastStatsTime: string;- workCount: number;- income: number;- status: number;- createTime: string;- updateTime: string;- rank: number;- groupId: string;+ id: string+ type: PlatType+ loginCookie?: string+ access_token?: string+ refresh_token?: string+ loginTime: string+ uid: string+ account: string+ avatar: string+ nickname: string+ fansCount: number+ readCount: number+ likeCount: number+ collectCount: number+ forwardCount: number+ commentCount: number+ lastStatsTime: string+ workCount: number+ income: number+ status: number+ createTime: string+ updateTime: string+ rank: number+ groupId: string}// 更新账户统计数据export interface UpdateAccountStatisticsParams {- id: number;- fansCount: number;- readCount: number;- likeCount: number;- collectCount: number;- commentCount: number;- income: number;- workCount: number;+ id: number+ fansCount: number+ readCount: number+ likeCount: number+ collectCount: number+ commentCount: number+ income: number+ workCount: number}// 账户组 item 数据export interface AccountGroupItem {- id: string;- name: string;- rank: number;- isDefault: boolean;- proxyIp?: string;- ip?: string;- location?: string;+ id: string+ name: string+ rank: number+ isDefault: boolean+ proxyIp?: string+ ip?: string+ location?: string}diff --git a/project/web/src/api/types/dataStatistics.ts b/project/web/src/api/types/dataStatistics.tsindex 31438ad5..0844c139 100644--- a/project/web/src/api/types/dataStatistics.ts+++ b/project/web/src/api/types/dataStatistics.ts@@ -1,72 +1,72 @@// getStatisticsPeriodApi 入参-import { PlatType } from "@/app/config/platConfig";+import type { PlatType } from '@/app/config/platConfig'export interface StatisticsPeriodApiParams {- startDate: string;- endDate: string;+ startDate: string+ endDate: stringqueries: {- platform: string;- uid: string;- }[];+ platform: string+ uid: string+ }[]}export interface StatisticsPeriodModel {- items?: StatisticsPeriodItems[];- queryCount: number;- successCount: number;- groupedByDate: GroupedByDate[];+ items?: StatisticsPeriodItems[]+ queryCount: number+ successCount: number+ groupedByDate: GroupedByDate[]}export interface StatisticsPeriodItems {- platform: PlatType;- uid: string;- items?: StatisticsPeriodItems2[];+ platform: PlatType+ uid: string+ items?: StatisticsPeriodItems2[]}export interface StatisticsPeriodItems2 {- id: string;- platform: string;- snapshotDate: string;- uid: string;- accountId: string;- commentCount?: number;- createdAt: string;- followingCount?: number;- likeCount?: number;- status: number;- updatedAt: string;- userId: string;- snapshotDateAsDate: string;- fansCount: number;- readCount?: number;- collectCount?: number;- forwardCount?: number;- workCount: number;+ id: string+ platform: string+ snapshotDate: string+ uid: string+ accountId: string+ commentCount?: number+ createdAt: string+ followingCount?: number+ likeCount?: number+ status: number+ updatedAt: string+ userId: string+ snapshotDateAsDate: string+ fansCount: number+ readCount?: number+ collectCount?: number+ forwardCount?: number+ workCount: number}export interface GroupedByDate {- date: string;- records: Records[];- count: number;+ date: string+ records: Records[]+ count: number}export interface Records {- id: string;- platform: string;- snapshotDate: string;- uid: string;- accountId: string;- commentCount: number;- createdAt: string;- followingCount: number;- likeCount: number;- status: number;- updatedAt: string;- userId: string;- snapshotDateAsDate: string;- fansCount: number;- readCount: number;- collectCount: number;- forwardCount: number;- workCount: number;+ id: string+ platform: string+ snapshotDate: string+ uid: string+ accountId: string+ commentCount: number+ createdAt: string+ followingCount: number+ likeCount: number+ status: number+ updatedAt: string+ userId: string+ snapshotDateAsDate: string+ fansCount: number+ readCount: number+ collectCount: number+ forwardCount: number+ workCount: number}diff --git a/project/web/src/api/types/engagement.ts b/project/web/src/api/types/engagement.tsindex 12e8d14a..899a47cd 100644--- a/project/web/src/api/types/engagement.ts+++ b/project/web/src/api/types/engagement.ts@@ -1,153 +1,151 @@-export type EngagementPlatform =- | 'bilibili'- | 'douyin'- | 'facebook'- | 'wxGzh'- | 'instagram'- | 'KWAI'- | 'pinterest'- | 'threads'- | 'tiktok'- | 'twitter'- | 'xhs'- | 'youtube';--export type EngagementMediaType = 'video' | 'image' | 'article';+export type EngagementPlatform+ = | 'bilibili'+ | 'douyin'+ | 'facebook'+ | 'wxGzh'+ | 'instagram'+ | 'KWAI'+ | 'pinterest'+ | 'threads'+ | 'tiktok'+ | 'twitter'+ | 'xhs'+ | 'youtube'++export type EngagementMediaType = 'video' | 'image' | 'article'export interface EngagementPostsParams {- platform: EngagementPlatform;- uid: string;- page: number;- pageSize: number;+ platform: EngagementPlatform+ uid: string+ page: number+ pageSize: number}export interface EngagementPostItem {- postId?: string;- id: string;- platform: EngagementPlatform;- title: string;- content: string;- thumbnail: string;- mediaType: EngagementMediaType;- permaLink: string;- publishTime: number; // ms timestamp- viewCount: number;- commentCount: number;- likeCount: number;- shareCount: number;- clickCount: number;- impressionCount: number;- favoriteCount: number;+ postId?: string+ id: string+ platform: EngagementPlatform+ title: string+ content: string+ thumbnail: string+ mediaType: EngagementMediaType+ permaLink: string+ publishTime: number // ms timestamp+ viewCount: number+ commentCount: number+ likeCount: number+ shareCount: number+ clickCount: number+ impressionCount: number+ favoriteCount: number}export interface EngagementPostsResponse {- total?: number;- posts: EngagementPostItem[];- hasMore?: boolean;+ total?: number+ posts: EngagementPostItem[]+ hasMore?: booleancursor?: {- before?: string;- after?: string;- };+ before?: string+ after?: string+ }}export interface EngagementCommentItem {- id: string;- postId: string;- userId: string;- userName?: string;- userAvatar?: string;- content: string;- likeCount: number;- createdAt: number; // ms timestamp- parentId?: string; // 回复时存在+ id: string+ postId: string+ userId: string+ userName?: string+ userAvatar?: string+ content: string+ likeCount: number+ createdAt: number // ms timestamp+ parentId?: string // 回复时存在}export interface EngagementCommentsParams {- postId: string;- page: number;- pageSize: number;+ postId: string+ page: number+ pageSize: number}export interface EngagementCommentsResponse {- total: number;- comments: EngagementCommentItem[];- hasMore: boolean;+ total: number+ comments: EngagementCommentItem[]+ hasMore: boolean}export interface EngagementReplyParams {- postId: string;- parentId?: string;- content: string;+ postId: string+ parentId?: string+ content: string}// 新版:平台一级评论(支持 keyset/offset 分页)-export type PostCommentPlatform = 'facebook' | 'instagram' | 'twitter' | 'youtube' | 'tiktok';+export type PostCommentPlatform = 'facebook' | 'instagram' | 'twitter' | 'youtube' | 'tiktok'export interface PostCommentsAuthor {- id?: string;- name?: string;- avatar?: string;+ id?: string+ name?: string+ avatar?: string}export interface PostCommentItemV2 {- id: string;- message: string;- author: PostCommentsAuthor;- createdAt: string; // ISO 8601- hasReplies: boolean;+ id: string+ message: string+ author: PostCommentsAuthor+ createdAt: string // ISO 8601+ hasReplies: boolean}export interface PostCommentsParamsV2 {- accountId: string;- platform: PostCommentPlatform;- postId: string;+ accountId: string+ platform: PostCommentPlatform+ postId: stringpagination?: {- before?: string;- after?: string;- limit?: number;- };+ before?: string+ after?: string+ limit?: number+ }}export interface PostCommentsResponseV2 {- comments: PostCommentItemV2[];- total?: number; // offset 模式才会返回+ comments: PostCommentItemV2[]+ total?: number // offset 模式才会返回cursor?: {- before?: string;- after?: string;- };+ before?: string+ after?: string+ }}export interface PublishPostCommentParams {- accountId: string;- platform: PostCommentPlatform;- postId: string;- message: string; // 1-500 chars+ accountId: string+ platform: PostCommentPlatform+ postId: string+ message: string // 1-500 chars}export interface PublishCommentReplyParams {- accountId: string;- platform: PostCommentPlatform;- commentId: string;- message: string; // 1-500 chars+ accountId: string+ platform: PostCommentPlatform+ commentId: string+ message: string // 1-500 chars}export interface CommentRepliesParams {- accountId: string;- platform: PostCommentPlatform;- commentId: string;+ accountId: string+ platform: PostCommentPlatform+ commentId: stringpagination?: {- before?: string;- after?: string;- limit?: number;- };+ before?: string+ after?: string+ limit?: number+ }}export interface CommentRepliesResponse {- comments: PostCommentItemV2[];+ comments: PostCommentItemV2[]cursor?: {- before?: string;- after?: string;- };+ before?: string+ after?: string+ }}--diff --git a/project/web/src/api/types/finance.ts b/project/web/src/api/types/finance.tsindex e865be33..d8a6a260 100644--- a/project/web/src/api/types/finance.ts+++ b/project/web/src/api/types/finance.ts@@ -5,7 +5,7 @@* @LastEditors: nevin* @Description: 财务相关*/-import { UserWalletAccount } from './userWalletAccount';+import type { UserWalletAccount } from './userWalletAccount'export enum UserWalletRecordType {TASK_COMMISSION = 'TASK_COMMISSION', // 任务佣金@@ -19,16 +19,16 @@ export enum UserWalletRecordStatus {}export interface UserWalletRecord {- id: string;- userId: string;- account: UserWalletAccount;- dataId: string; // 关联数据的ID- type: UserWalletRecordType;- balance: number;- status: UserWalletRecordStatus;- payTime?: string;- des?: string;- imgUrl?: string; // 反馈截图- createdAt: string;- updatedAt: string;+ id: string+ userId: string+ account: UserWalletAccount+ dataId: string // 关联数据的ID+ type: UserWalletRecordType+ balance: number+ status: UserWalletRecordStatus+ payTime?: string+ des?: string+ imgUrl?: string // 反馈截图+ createdAt: string+ updatedAt: string}diff --git a/project/web/src/api/types/hotTopic.ts b/project/web/src/api/types/hotTopic.tsindex d233a9e0..fda12a1e 100644--- a/project/web/src/api/types/hotTopic.ts+++ b/project/web/src/api/types/hotTopic.ts@@ -1,21 +1,21 @@-import { Platform } from '../hot';+import type { Platform } from '../hot'export interface HotValueHistory {- updateTime: string; // 记录时间- hotValue: number; // 热度值+ updateTime: string // 记录时间+ hotValue: number // 热度值}export interface HotTopic {- _id: string;- platformId: Platform; // 关联平台ID- title: string; // 话题标题- hotValue: number; // 当前热度值- url: string; // 话题链接- rank: number; // 当前排名- rankChange: number; // 排名变化值(正数表示上升,负数表示下降)- isRising: boolean; // 是否上升趋势- hotValueHistory: HotValueHistory[]; // 热度值历史记录- fetchTime: Date; // 数据抓取时间- createTime: Date;- updateTime: Date;+ _id: string+ platformId: Platform // 关联平台ID+ title: string // 话题标题+ hotValue: number // 当前热度值+ url: string // 话题链接+ rank: number // 当前排名+ rankChange: number // 排名变化值(正数表示上升,负数表示下降)+ isRising: boolean // 是否上升趋势+ hotValueHistory: HotValueHistory[] // 热度值历史记录+ fetchTime: Date // 数据抓取时间+ createTime: Date+ updateTime: Date}diff --git a/project/web/src/api/types/income.ts b/project/web/src/api/types/income.tsindex fd7465a0..139d200c 100644--- a/project/web/src/api/types/income.ts+++ b/project/web/src/api/types/income.ts@@ -6,10 +6,10 @@ export enum IncomeType {// 订单类型 (根据实际API返回结构)export interface IncomeRecord {- _id: string;- id: string;- userId: string;- amount: number;+ _id: string+ id: string+ userId: string+ amount: numberrelId?: stringtype: IncomeTypedesc?: stringdiff --git a/project/web/src/api/types/index.ts b/project/web/src/api/types/index.tsindex 2a0d72df..5765cbf2 100644--- a/project/web/src/api/types/index.ts+++ b/project/web/src/api/types/index.ts@@ -6,16 +6,16 @@* @Description:*/export interface ApiCorrectQuery {- pageSize: number;- pageNo: number;+ pageSize: number+ pageNo: number}export interface IPaginationMeta {- itemCount: number;- totalItems?: number;- itemsPerPage: number;- totalPages?: number;- currentPage: number;+ itemCount: number+ totalItems?: number+ itemsPerPage: number+ totalPages?: number+ currentPage: number}export class Pagination<T> {@@ -26,4 +26,4 @@ export class Pagination<T> {}// 导出支付相关类型-export * from './payment';+export * from './payment'diff --git a/project/web/src/api/types/operate.ts b/project/web/src/api/types/operate.tsindex 6781404d..6037ed6d 100644--- a/project/web/src/api/types/operate.ts+++ b/project/web/src/api/types/operate.ts@@ -1,12 +1,12 @@export interface Banner {- _id: string;- id: string;- dataId: string;- desc: string;- url: string;- imgUrl: string;- tag: string;- isPublish: 0 | 1;- createTime: string;- updateTime: string;+ _id: string+ id: string+ dataId: string+ desc: string+ url: string+ imgUrl: string+ tag: string+ isPublish: 0 | 1+ createTime: string+ updateTime: string}diff --git a/project/web/src/api/types/payment.ts b/project/web/src/api/types/payment.tsindex b13d36bd..80588bfd 100644--- a/project/web/src/api/types/payment.ts+++ b/project/web/src/api/types/payment.ts@@ -1,114 +1,114 @@// 订单状态枚举 (根据实际API返回)export enum OrderStatus {- OPEN = 'open', // 待支付+ OPEN = 'open', // 待支付COMPLETE = 'complete', // 已完成- EXPIRED = 'expired' // 已过期+ EXPIRED = 'expired', // 已过期}// 支付模式枚举export enum PaymentMode {- PAYMENT = 'payment', // 一次性支付- SUBSCRIPTION = 'subscription' // 订阅+ PAYMENT = 'payment', // 一次性支付+ SUBSCRIPTION = 'subscription', // 订阅}// 订阅状态枚举export enum SubscriptionStatus {- ACTIVE = 'active', // 活跃- CANCELED = 'canceled', // 已取消- PAST_DUE = 'past_due', // 逾期- TRIALING = 'trialing' // 试用中+ ACTIVE = 'active', // 活跃+ CANCELED = 'canceled', // 已取消+ PAST_DUE = 'past_due', // 逾期+ TRIALING = 'trialing', // 试用中}// 订阅计划类型枚举export enum SubscriptionPlan {- MONTH = 'month', // 月度订阅- CLOUD_SPACE_MONTH = 'cloudSpaceMonth' // 云空间月度订阅+ MONTH = 'month', // 月度订阅+ CLOUD_SPACE_MONTH = 'cloudSpaceMonth', // 云空间月度订阅}// 套餐类型枚举export enum PaymentType {- MONTH = 'month', // 月度订阅- YEAR = 'year', // 年度订阅+ MONTH = 'month', // 月度订阅+ YEAR = 'year', // 年度订阅ONCE_MONTH = 'onceMonth', // 一次性月度- ONCE_YEAR = 'onceYear' // 一次性年度+ ONCE_YEAR = 'onceYear', // 一次性年度}// 订阅信息类型 (根据新的API返回结构)export interface Subscription {- id: string; // 订阅 ID (必需)- userId: string; // 用户 ID (必需)- stripeCustomerId: string; // Stripe 客户 ID (必需)- plan: SubscriptionPlan; // 订阅计划类型 (必需)- status: SubscriptionStatus; // 订阅状态 (必需)- cancelAtPeriodEnd: boolean; // 是否在当前计费周期结束时取消 (必需)- createdAt: string; // 订阅创建时间 (必需, ISO 8601格式)- canceledAt?: string; // 订阅取消时间 (可选, ISO 8601格式)- trialEndAt?: string; // 试用期结束时间 (可选, ISO 8601格式)+ id: string // 订阅 ID (必需)+ userId: string // 用户 ID (必需)+ stripeCustomerId: string // Stripe 客户 ID (必需)+ plan: SubscriptionPlan // 订阅计划类型 (必需)+ status: SubscriptionStatus // 订阅状态 (必需)+ cancelAtPeriodEnd: boolean // 是否在当前计费周期结束时取消 (必需)+ createdAt: string // 订阅创建时间 (必需, ISO 8601格式)+ canceledAt?: string // 订阅取消时间 (可选, ISO 8601格式)+ trialEndAt?: string // 试用期结束时间 (可选, ISO 8601格式)}// 订单类型 (根据实际API返回结构)export interface Order {- _id: string;- amount: number;- amount_refunded: number;- created: number; // 时间戳- currency: string;- customer: any;- customer_details: any;- expires_at: number;- id: string; // stripe checkout session id- info: any;+ _id: string+ amount: number+ amount_refunded: number+ created: number // 时间戳+ currency: string+ customer: any+ customer_details: any+ expires_at: number+ id: string // stripe checkout session id+ info: anymetadata: {- userId: string;- payment: string;- mode: string;- };- mode: PaymentMode; // 支付模式 (必需)- payment_intent: string | null;- price: string;- quantity: number; // 购买数量 (必需)- status: OrderStatus; // 支付状态 (必需)- subscription: any;- success_url: string;- url: string;- userId: string;+ userId: string+ payment: string+ mode: string+ }+ mode: PaymentMode // 支付模式 (必需)+ payment_intent: string | null+ price: string+ quantity: number // 购买数量 (必需)+ status: OrderStatus // 支付状态 (必需)+ subscription: any+ success_url: string+ url: string+ userId: string}// 订单查询参数export interface OrderListParams {- price?: string;- page: number;- size: number;+ price?: string+ page: number+ size: number}// 订阅列表查询参数export interface SubscriptionListParams {- page: number;- size: number;+ page: number+ size: number}// 退款参数export interface RefundParams {- charge: string;- payment_intent: string;- userId: string;+ charge: string+ payment_intent: string+ userId: string}// 退订参数export interface UnsubscribeParams {- id: string;- userId: string;+ id: string+ userId: string}// API响应类型export interface PaymentApiResponse<T> {- code: number;- message: string;- data: T;+ code: number+ message: string+ data: T}// 分页响应 (根据实际API返回结构: data.count 和 data.list)export interface PaginatedResponse<T> {- count: number;- list: T[];-}\ No newline at end of file+ count: number+ list: T[]+}diff --git a/project/web/src/api/types/pinterest.ts b/project/web/src/api/types/pinterest.tsindex 79053287..cdd4fc72 100644--- a/project/web/src/api/types/pinterest.ts+++ b/project/web/src/api/types/pinterest.ts@@ -1 +1 @@-// Pinterest API 相关类型定义 - 最少化类型使用,多使用any\ No newline at end of file+// Pinterest API 相关类型定义 - 最少化类型使用,多使用anydiff --git a/project/web/src/api/types/platform.type.ts b/project/web/src/api/types/platform.type.tsindex fcfd5604..b0817083 100644--- a/project/web/src/api/types/platform.type.ts+++ b/project/web/src/api/types/platform.type.ts@@ -1,61 +1,61 @@-export type AiToolsRankingItemType = {- _id: string;- rankingId: string;- col_name: string;- status: number;- videoDuration: number;- anaAdd: null | string;- url: string;- category: string;- subCategory: string;- type: null | string;- shareCount: number;- collectCount: null | number;- cover: string;- description: string;- title: string;- createTime: string;- updateTime: string;+export interface AiToolsRankingItemType {+ _id: string+ rankingId: string+ col_name: string+ status: number+ videoDuration: number+ anaAdd: null | string+ url: string+ category: string+ subCategory: string+ type: null | string+ shareCount: number+ collectCount: null | number+ cover: string+ description: string+ title: string+ createTime: string+ updateTime: stringauthor: {- id: null | string;- name: null | string;- fansCount: null | number;- avatar: null | string;- };+ id: null | string+ name: null | string+ fansCount: null | number+ avatar: null | string+ }stats: {- viewCount: string;- likeCount: number;- commentCount: number;- };- publishTime: string;- rankingPosition: number;- spider_time: null | string;- platformId: string;- originalId: string;- downCount: string;- referCount: number;- volumeCount: number;- exponentCount: number;- intro: string;- rankChange: number;+ viewCount: string+ likeCount: number+ commentCount: number+ }+ publishTime: string+ rankingPosition: number+ spider_time: null | string+ platformId: string+ originalId: string+ downCount: string+ referCount: number+ volumeCount: number+ exponentCount: number+ intro: string+ rankChange: numberdetail: {- 公众号: number;- 抖音: number;- 视频号: number;- 小红书: number;- 快手: number;- 哔哩哔哩: number;- };- area: number;- id: string;-};+ 公众号: number+ 抖音: number+ 视频号: number+ 小红书: number+ 快手: number+ 哔哩哔哩: number+ }+ area: number+ id: string+}export interface GetAiToolsRankingApiRes {- items: AiToolsRankingItemType[];+ items: AiToolsRankingItemType[]}export interface GetAiToolsRankingApiParams {- dateType: string;- startDate: string;- area: string;+ dateType: string+ startDate: string+ area: string}diff --git a/project/web/src/api/types/sent.types.ts b/project/web/src/api/types/sent.types.tsindex d1d515f4..e014030f 100644--- a/project/web/src/api/types/sent.types.ts+++ b/project/web/src/api/types/sent.types.ts@@ -1,47 +1,47 @@// Sent界面相关的类型定义export interface SentPost {- id: string;- accountId: string; // 账户ID,用于映射头像和平台信息- accountType: string; // 平台类型- dataId: string; // 数据ID- title: string;- desc: string; // 描述内容- coverUrl: string; // 封面图片- imgUrlList: string[]; // 图片列表- type: string; // 类型:video, image, carousel_album 等- workLink: string; // 作品链接- publishTime: string; // 发布时间 ISO格式- publishingChannel: string; // 发布渠道- status: number; // 状态- uid: string;- flowId: string;- errorMsg: string;+ id: string+ accountId: string // 账户ID,用于映射头像和平台信息+ accountType: string // 平台类型+ dataId: string // 数据ID+ title: string+ desc: string // 描述内容+ coverUrl: string // 封面图片+ imgUrlList: string[] // 图片列表+ type: string // 类型:video, image, carousel_album 等+ workLink: string // 作品链接+ publishTime: string // 发布时间 ISO格式+ publishingChannel: string // 发布渠道+ status: number // 状态+ uid: string+ flowId: string+ errorMsg: stringengagement: {- viewCount: number;- commentCount: number;- likeCount: number;- shareCount: number;- clickCount: number;- impressionCount: number;- favoriteCount: number;- };+ viewCount: number+ commentCount: number+ likeCount: number+ shareCount: number+ clickCount: number+ impressionCount: number+ favoriteCount: number+ }}export interface SentPostsResponse {- code: number;- message: string;- url: string;+ code: number+ message: string+ url: stringdata: {- total: number;- posts: SentPost[];- hasMore: boolean;- };+ total: number+ posts: SentPost[]+ hasMore: boolean+ }}export interface SentPostsParams {- platform?: string;- uid?: string;- page: number;- pageSize: number;+ platform?: string+ uid?: string+ page: number+ pageSize: number}diff --git a/project/web/src/api/types/topic.ts b/project/web/src/api/types/topic.tsindex 74c98dcd..65018d24 100644--- a/project/web/src/api/types/topic.ts+++ b/project/web/src/api/types/topic.ts@@ -1,25 +1,25 @@export interface Topic {- _id: string;- title: string; // 话题标题- description?: string;- category: string;- subCategory: string;- url: string; // 作品链接- author?: string; // 作者- topics: string[]; // 话题标签- rank: number;- coverUrl?: string;- shareCount: number;- likeCount: number;- watchingCount: number;- commentCount: number;- collectCount: number;- readCount: number;- publishTime?: string;- fans: number;- cover: string;- avatar: string;- createTime: Date;- authorUrl: string;- updateTime: Date;+ _id: string+ title: string // 话题标题+ description?: string+ category: string+ subCategory: string+ url: string // 作品链接+ author?: string // 作者+ topics: string[] // 话题标签+ rank: number+ coverUrl?: string+ shareCount: number+ likeCount: number+ watchingCount: number+ commentCount: number+ collectCount: number+ readCount: number+ publishTime?: string+ fans: number+ cover: string+ avatar: string+ createTime: Date+ authorUrl: string+ updateTime: Date}diff --git a/project/web/src/api/types/user-t.ts b/project/web/src/api/types/user-t.tsindex aa0edead..84dbb620 100644--- a/project/web/src/api/types/user-t.ts+++ b/project/web/src/api/types/user-t.ts@@ -1,24 +1,24 @@export interface PhoneLoginParams {- phone: string;- code: string;- openId?: string; // 微信公众号的openId- inviteCode?: string;+ phone: string+ code: string+ openId?: string // 微信公众号的openId+ inviteCode?: string}export interface IUserInfo {- _id: string;- id: string;- name: string;- phone?: string;- gender?: number;- avatar?: string;- desc?: string;- wxOpenId?: string;+ _id: string+ id: string+ name: string+ phone?: string+ gender?: number+ avatar?: string+ desc?: string+ wxOpenId?: string}export interface IRefreshToken {- token: string;- userInfo: IUserInfo;+ token: string+ userInfo: IUserInfo// 过期时间。秒- exp: number;+ exp: number}diff --git a/project/web/src/api/types/userWalletAccount.ts b/project/web/src/api/types/userWalletAccount.tsindex 58bd9c1c..7b886150 100644--- a/project/web/src/api/types/userWalletAccount.ts+++ b/project/web/src/api/types/userWalletAccount.ts@@ -11,25 +11,25 @@ export enum WalletAccountType {}export interface UserWallet {- userId: string;- balance: number;- income: number;+ userId: string+ balance: number+ income: number}export interface UserWalletAccount {- id: string;- account: string; // 账户号- userId: string;- userName: string; // 真实姓名- cardNum: string; // 身份证号- phone: string; // 绑定的手机号- type: WalletAccountType;+ id: string+ account: string // 账户号+ userId: string+ userName: string // 真实姓名+ cardNum: string // 身份证号+ phone: string // 绑定的手机号+ type: WalletAccountType}export interface CreateUserWalletAccountParams {- account: string; // 账户号- userName: string; // 真实姓名- cardNum: string; // 身份证号- phone: string; // 绑定的手机号- type: WalletAccountType;+ account: string // 账户号+ userName: string // 真实姓名+ cardNum: string // 身份证号+ phone: string // 绑定的手机号+ type: WalletAccountType}diff --git a/project/web/src/api/types/viralTitles.ts b/project/web/src/api/types/viralTitles.tsindex 25e41c17..68937e2f 100644--- a/project/web/src/api/types/viralTitles.ts+++ b/project/web/src/api/types/viralTitles.ts@@ -1,15 +1,15 @@-import { Platform } from "@/api/hot";+import type { Platform } from '@/api/hot'export interface ViralTitle {- _id: string;- platformId: Platform;- category: string;- title: string;- url: string; // 链接- rank: number; // 排名- engagement: number; // 互动量- publishTime?: Date;- createTime: Date;- updateTime: Date;- timeType: string;+ _id: string+ platformId: Platform+ category: string+ title: string+ url: string // 链接+ rank: number // 排名+ engagement: number // 互动量+ publishTime?: Date+ createTime: Date+ updateTime: Date+ timeType: string}diff --git a/project/web/src/api/types/withdraw.ts b/project/web/src/api/types/withdraw.tsindex f27882b8..3747fc87 100644--- a/project/web/src/api/types/withdraw.ts+++ b/project/web/src/api/types/withdraw.ts@@ -11,12 +11,12 @@ export enum WithdrawRecordStatus {}export interface WithdrawRecord {- _id: string;- id: string;- userId: string;+ _id: string+ id: string+ userId: stringflowId?: stringtype: WithdrawRecordType- amount: number;+ amount: numberincomeRecordId?: stringrelId?: stringdesc?: stringdiff --git a/project/web/src/api/userWalletAccount.ts b/project/web/src/api/userWalletAccount.tsindex dbabbb0c..81e55f1e 100644--- a/project/web/src/api/userWalletAccount.ts+++ b/project/web/src/api/userWalletAccount.ts@@ -1,43 +1,41 @@-import http from "@/utils/request";+import http from '@/utils/request'-export type WalletType = "ZFB" | "WX_PAY";+export type WalletType = 'ZFB' | 'WX_PAY'export interface UserWalletAccountCreateDto {- userId: string;- mail: string; // email- userName?: string;- account: string;- cardNum?: string;- phone?: string;- type: WalletType;+ userId: string+ mail: string // email+ userName?: string+ account: string+ cardNum?: string+ phone?: string+ type: WalletType}export interface UserWalletAccount extends UserWalletAccountCreateDto {- _id: string;- createdAt?: string;- updatedAt?: string;+ _id: string+ createdAt?: string+ updatedAt?: string}export function createUserWalletAccount(data: UserWalletAccountCreateDto) {- return http.post<UserWalletAccount>("userWalletAccount", data);+ return http.post<UserWalletAccount>('userWalletAccount', data)}export function updateUserWalletAccount(id: string, data: Partial<UserWalletAccountCreateDto>) {- return http.put<UserWalletAccount>("userWalletAccount", { id, ...data });+ return http.put<UserWalletAccount>('userWalletAccount', { id, ...data })}export function deleteUserWalletAccount(id: string) {- return http.delete<null>(`userWalletAccount/${id}`);+ return http.delete<null>(`userWalletAccount/${id}`)}export function getUserWalletAccountInfo(id: string) {- return http.get<UserWalletAccount>(`userWalletAccount/info/${id}`);+ return http.get<UserWalletAccount>(`userWalletAccount/info/${id}`)}export function getUserWalletAccountList(pageNo: number, pageSize: number) {- return http.get<{ list: UserWalletAccount[]; total: number }>(`userWalletAccount/list/${pageNo}/${pageSize}`);+ return http.get<{ list: UserWalletAccount[], total: number }>(`userWalletAccount/list/${pageNo}/${pageSize}`)}-export const EMAIL_REGEX = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;--+export const EMAIL_REGEX = /^(?!\.)(?!.*\.\.)([\w'+\-.]*)[\w+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/idiff --git a/project/web/src/api/vip.ts b/project/web/src/api/vip.tsindex 8d335e60..8de6b364 100644--- a/project/web/src/api/vip.ts+++ b/project/web/src/api/vip.ts@@ -1,48 +1,48 @@-import { request } from '@/utils/request';+import { request } from '@/utils/request'// 会员类型枚举export enum VipCycleType {- MONTH = 1, // 月卡会员- YEAR = 2, // 年卡会员+ MONTH = 1, // 月卡会员+ YEAR = 2, // 年卡会员}// 支付类型枚举export enum PaymentType {- MONTH = 'month', // 月度订阅- YEAR = 'year', // 年度订阅+ MONTH = 'month', // 月度订阅+ YEAR = 'year', // 年度订阅ONCE_MONTH = 'onceMonth', // 一次性月度- ONCE_YEAR = 'onceYear', // 一次性年度- POINTS = 'points' // 积分购买+ ONCE_YEAR = 'onceYear', // 一次性年度+ POINTS = 'points', // 积分购买}// 创建支付订单参数接口export interface CreatePaymentOrderParams {- success_url?: string;- returnTo?: string;- mode: string;- payment: PaymentType;- quantity?: number; // 购买数量,用于积分购买+ success_url?: string+ returnTo?: string+ mode: string+ payment: PaymentType+ quantity?: number // 购买数量,用于积分购买metadata: {- userId: string;- };+ userId: string+ }}// 创建支付订单-export const createPaymentOrderApi = (params: CreatePaymentOrderParams) => {+export function createPaymentOrderApi(params: CreatePaymentOrderParams) {return request({url: 'payment/checkout',method: 'POST',- data: params- });-};+ data: params,+ })+}// 设置会员类型-export const setVipApi = (cycleType: VipCycleType) => {+export function setVipApi(cycleType: VipCycleType) {return request({url: 'user/vip/set',method: 'PUT',data: {- cycleType- }- });-};\ No newline at end of file+ cycleType,+ },+ })+}diff --git a/project/web/src/api/withdraw.ts b/project/web/src/api/withdraw.tsindex 62a57159..d8b276c0 100644--- a/project/web/src/api/withdraw.ts+++ b/project/web/src/api/withdraw.ts@@ -1,13 +1,13 @@-import { request } from '@/utils/request';-import { WithdrawRecord } from './types/withdraw';+import type { WithdrawRecord } from './types/withdraw'+import { request } from '@/utils/request'/*** 获取提现列表*/-export const apiGetWithdrawRecordList = (page: {pageNo: number, pageSize: number}, params: { status?: number }) => {- return request<{list: WithdrawRecord[], total: number}>({+export function apiGetWithdrawRecordList(page: { pageNo: number, pageSize: number }, params: { status?: number }) {+ return request<{ list: WithdrawRecord[], total: number }>({url: `withdraw/list/${page.pageNo}/${page.pageSize}`,method: 'GET',- params- });-};+ params,+ })+}diff --git a/project/web/src/app/[lng]/accounts/accountCore.tsx b/project/web/src/app/[lng]/accounts/accountCore.tsxindex 09397d25..840ad671 100644--- a/project/web/src/app/[lng]/accounts/accountCore.tsx+++ b/project/web/src/app/[lng]/accounts/accountCore.tsx@@ -1,101 +1,102 @@-"use client";+'use client'-import styles from "./accounts.module.scss";-import { useAccountStore } from "@/store/account";-import { useShallow } from "zustand/react/shallow";-import { useEffect, useState } from "react";-import { NoSSR } from "@kwooshung/react-no-ssr";-import AccountSidebar from "@/app/[lng]/accounts/components/AccountSidebar/AccountSidebar";-import CalendarTiming from "@/app/[lng]/accounts/components/CalendarTiming";-import AddAccountModal from "@/app/[lng]/accounts/components/AddAccountModal";-import { PlatType } from "@/app/config/platConfig";-import { SocialAccount } from "@/api/types/account.type";-import AllPlatIcon from "@/app/[lng]/accounts/components/CalendarTiming/AllPlatIcon";-import { useTransClient } from "@/app/i18n/client";-import { useUserStore } from "@/store/user";-import Image from "next/image";-import VipContentModal from "@/components/modals/VipContentModal";+import type { SocialAccount } from '@/api/types/account.type'+import { NoSSR } from '@kwooshung/react-no-ssr'+import Image from 'next/image'+import { useEffect, useState } from 'react'+import { useShallow } from 'zustand/react/shallow'+import AccountSidebar from '@/app/[lng]/accounts/components/AccountSidebar/AccountSidebar'+import AddAccountModal from '@/app/[lng]/accounts/components/AddAccountModal'+import CalendarTiming from '@/app/[lng]/accounts/components/CalendarTiming'+import AllPlatIcon from '@/app/[lng]/accounts/components/CalendarTiming/AllPlatIcon'+import { PlatType } from '@/app/config/platConfig'+import { useTransClient } from '@/app/i18n/client'+import rightArrow from '@/assets/images/jiantou.png'+import VipContentModal from '@/components/modals/VipContentModal'+import { useAccountStore } from '@/store/account'+import { useUserStore } from '@/store/user'-import rightArrow from "@/assets/images/jiantou.png";+import styles from './accounts.module.scss'interface AccountPageCoreProps {searchParams?: {- platform?: string;- spaceId?: string;- showVip?: string;- };+ platform?: string+ spaceId?: string+ showVip?: string+ }}export default function AccountPageCore({searchParams,}: AccountPageCoreProps) {- const { accountInit, accountActive, setAccountActive, accountGroupList } =- useAccountStore(- useShallow((state) => ({+ const { accountInit, accountActive, setAccountActive, accountGroupList }+ = useAccountStore(+ useShallow(state => ({accountInit: state.accountInit,setAccountActive: state.setAccountActive,accountActive: state.accountActive,accountGroupList: state.accountGroupList,})),- );+ )// 添加账号弹窗状态- const [addAccountModalOpen, setAddAccountModalOpen] = useState(false);- const [targetPlatform, setTargetPlatform] = useState<PlatType | undefined>();- const [targetSpaceId, setTargetSpaceId] = useState<string | undefined>();- const { t } = useTransClient("account");- const userStore = useUserStore();+ const [addAccountModalOpen, setAddAccountModalOpen] = useState(false)+ const [targetPlatform, setTargetPlatform] = useState<PlatType | undefined>()+ const [targetSpaceId, setTargetSpaceId] = useState<string | undefined>()+ const { t } = useTransClient('account')+ const userStore = useUserStore()// 移动端下载提示弹窗开关- const [showMobileDownload, setShowMobileDownload] = useState(false);+ const [showMobileDownload, setShowMobileDownload] = useState(false)// 微信浏览器提示弹窗开关- const [showWechatBrowserTip, setShowWechatBrowserTip] = useState(false);+ const [showWechatBrowserTip, setShowWechatBrowserTip] = useState(false)// VIP弹窗状态- const [vipModalOpen, setVipModalOpen] = useState(false);+ const [vipModalOpen, setVipModalOpen] = useState(false)useEffect(() => {- accountInit();- }, []);+ accountInit()+ }, [])// 处理URL参数useEffect(() => {// 处理显示VIP弹窗的参数if (searchParams?.showVip === 'true') {- setVipModalOpen(true);+ setVipModalOpen(true)// 清除URL参数- if (typeof window !== "undefined") {- const url = new URL(window.location.href);- url.searchParams.delete("showVip");- window.history.replaceState({}, "", url.toString());+ if (typeof window !== 'undefined') {+ const url = new URL(window.location.href)+ url.searchParams.delete('showVip')+ window.history.replaceState({}, '', url.toString())}}if (searchParams?.platform || searchParams?.spaceId) {// 验证平台类型是否有效- const platform = searchParams.platform as PlatType;- const validPlatforms = Object.values(PlatType);+ const platform = searchParams.platform as PlatType+ const validPlatforms = Object.values(PlatType)if (searchParams.platform && validPlatforms.includes(platform)) {- setTargetPlatform(platform);+ setTargetPlatform(platform)}if (searchParams.spaceId) {- setTargetSpaceId(searchParams.spaceId);+ setTargetSpaceId(searchParams.spaceId)}// 打开添加账号弹窗- setAddAccountModalOpen(true);+ setAddAccountModalOpen(true)}- }, [searchParams]);+ }, [searchParams])/*** 检测是否为微信浏览器*/const isWechatBrowser = () => {- if (typeof window === "undefined") return false;- const ua = window.navigator.userAgent.toLowerCase();- return ua.includes('micromessenger');- };+ if (typeof window === 'undefined')+ return false+ const ua = window.navigator.userAgent.toLowerCase()+ return ua.includes('micromessenger')+ }/*** 在移动端首次进入 accounts 页面时,展示下载提示弹窗@@ -104,135 +105,135 @@ export default function AccountPageCore({* - 如果是微信浏览器,先显示微信浏览器提示*/useEffect(() => {- if (typeof window === "undefined") return;- const isMobile = window.innerWidth <= 768;- const hasShown = sessionStorage.getItem("accountsMobileDownloadShown");- const hasShownWechatTip = sessionStorage.getItem("accountsWechatTipShown");-+ if (typeof window === 'undefined')+ return+ const isMobile = window.innerWidth <= 768+ const hasShown = sessionStorage.getItem('accountsMobileDownloadShown')+ const hasShownWechatTip = sessionStorage.getItem('accountsWechatTipShown')+if (isMobile) {// 如果是微信浏览器且未显示过微信提示,先显示微信提示if (isWechatBrowser() && !hasShownWechatTip) {- setShowWechatBrowserTip(true);- sessionStorage.setItem("accountsWechatTipShown", "1");- } else if (!hasShown) {+ setShowWechatBrowserTip(true)+ sessionStorage.setItem('accountsWechatTipShown', '1')+ }+ else if (!hasShown) {// 非微信浏览器或已显示过微信提示,显示下载提示- setShowMobileDownload(true);- sessionStorage.setItem("accountsMobileDownloadShown", "1");+ setShowMobileDownload(true)+ sessionStorage.setItem('accountsMobileDownloadShown', '1')}--}- }, []);+ }, [])/*** 关闭下载提示弹窗*/- const closeMobileDownload = () => setShowMobileDownload(false);+ const closeMobileDownload = () => setShowMobileDownload(false)/*** 关闭微信浏览器提示弹窗*/const closeWechatBrowserTip = () => {- setShowWechatBrowserTip(false);+ setShowWechatBrowserTip(false)// 关闭微信提示后,显示下载提示- const hasShown = sessionStorage.getItem("accountsMobileDownloadShown");+ const hasShown = sessionStorage.getItem('accountsMobileDownloadShown')if (!hasShown) {- setShowMobileDownload(true);- sessionStorage.setItem("accountsMobileDownloadShown", "1");+ setShowMobileDownload(true)+ sessionStorage.setItem('accountsMobileDownloadShown', '1')}- };+ }/*** 生成下载链接(根据语言)*/const getDownloadHref = () => {- const lang = userStore.lang;- return lang === "en"- ? "https://docs.aitoearn.ai/en/downloads"- : "https://docs.aitoearn.ai/zh/downloads";- };+ const lang = userStore.lang+ return lang === 'en'+ ? 'https://docs.aitoearn.ai/en/downloads'+ : 'https://docs.aitoearn.ai/zh/downloads'+ }const downloadTexts = (() => {- const lang = userStore.lang;- if (lang === "zh-CN") {+ const lang = userStore.lang+ if (lang === 'zh-CN') {return {- title: "欢迎使用 AitoEarn",- desc: "为了获得完整体验,请在设备上下载 App",- cta: "下载 App",- };+ title: '欢迎使用 AitoEarn',+ desc: '为了获得完整体验,请在设备上下载 App',+ cta: '下载 App',+ }}return {- title: "Welcome to AitoEarn",- desc: "To enjoy the full experience, please download the app on your device",- cta: "Download App",- };- })();+ title: 'Welcome to AitoEarn',+ desc: 'To enjoy the full experience, please download the app on your device',+ cta: 'Download App',+ }+ })()const wechatBrowserTexts = (() => {- const lang = userStore.lang;- if (lang === "zh-CN") {+ const lang = userStore.lang+ if (lang === 'zh-CN') {return {- title: "请在浏览器中打开",- desc: "请点击右上角,通过浏览器打开",- cta: "我知道了",- };+ title: '请在浏览器中打开',+ desc: '请点击右上角,通过浏览器打开',+ cta: '我知道了',+ }}return {- title: "Please open in browser",- desc: "Please click the top-right corner to open via browser",- cta: "I understand",- };- })();+ title: 'Please open in browser',+ desc: 'Please click the top-right corner to open via browser',+ cta: 'I understand',+ }+ })()const handleAddAccountSuccess = (accountInfo: SocialAccount) => {- setAddAccountModalOpen(false);+ setAddAccountModalOpen(false)// 可以在这里添加成功提示或其他逻辑- };+ }const handleAddAccountClose = () => {- setAddAccountModalOpen(false);+ setAddAccountModalOpen(false)// 清除URL参数(可选)- if (typeof window !== "undefined") {- const url = new URL(window.location.href);- url.searchParams.delete("platform");- url.searchParams.delete("spaceId");- window.history.replaceState({}, "", url.toString());+ if (typeof window !== 'undefined') {+ const url = new URL(window.location.href)+ url.searchParams.delete('platform')+ url.searchParams.delete('spaceId')+ window.history.replaceState({}, '', url.toString())}- };+ }return (<NoSSR><div className={styles.accounts}><AccountSidebar- activeAccountId={accountActive?.id || ""}+ activeAccountId={accountActive?.id || ''}onAccountChange={(account) => {- setAccountActive(account);+ setAccountActive(account)}}- sidebarTopExtra={+ sidebarTopExtra={(<><divclassName={[- "accountList-item",- `${!accountActive?.id ? "accountList-item--active" : ""}`,- ].join(" ")}+ 'accountList-item',+ `${!accountActive?.id ? 'accountList-item--active' : ''}`,+ ].join(' ')}style={{- border: "1px solid #d9d9d9",- borderRight: "none",- borderLeft: "none",+ border: '1px solid #d9d9d9',+ borderRight: 'none',+ borderLeft: 'none',}}onClick={async () => {- setAccountActive(undefined);+ setAccountActive(undefined)}}><AllPlatIcon size={38} /><div className="accountList-item-right"><div className="accountList-item-right-name">- {t("allPlatforms")}+ {t('allPlatforms')}</div></div></div></>- }+ )}/><CalendarTiming />@@ -258,17 +259,17 @@ export default function AccountPageCore({<div className={styles.wechatTipStep}><span className={styles.stepNumber}>1</span><span className={styles.stepText}>- {userStore.lang === "zh-CN" ? "点击右上角的" : "Click the top-right corner's"}+ {userStore.lang === 'zh-CN' ? '点击右上角的' : 'Click the top-right corner\'s'}<span className={styles.dotsButton}>⋯</span>- {userStore.lang === "zh-CN" ? "按钮" : "button"}+ {userStore.lang === 'zh-CN' ? '按钮' : 'button'}</span></div><div className={styles.wechatTipStep}><span className={styles.stepNumber}>2</span><span className={styles.stepText}>- {userStore.lang === "zh-CN" ? "选择" : "Select"}+ {userStore.lang === 'zh-CN' ? '选择' : 'Select'}<span className={styles.browserButton}>🌐</span>- {userStore.lang === "zh-CN" ? "在浏览器中打开" : "Open in browser"}+ {userStore.lang === 'zh-CN' ? '在浏览器中打开' : 'Open in browser'}</span></div></div>@@ -276,7 +277,7 @@ export default function AccountPageCore({{wechatBrowserTexts.cta}</button></div>-+</div></>)}@@ -284,10 +285,14 @@ export default function AccountPageCore({{/* 移动端下载提示(遮罩 + 底部弹窗) */}{showMobileDownload && (<>- <div className={styles.mobileDownloadOverlay} />+ <div className={styles.mobileDownloadOverlay} /><div className={styles.mobileDownloadSheet} role="dialog" aria-modal="true"><div className={styles.sheetHeader}>- <div className={styles.sheetTitle}>{downloadTexts.title} 👋</div>+ <div className={styles.sheetTitle}>+ {downloadTexts.title}+ {' '}+ 👋+ </div><button className={styles.sheetClose} aria-label="Close" onClick={closeMobileDownload}>×</button>@@ -311,11 +316,11 @@ export default function AccountPageCore({)}{/* VIP弹窗 */}- <VipContentModal- open={vipModalOpen}- onClose={() => setVipModalOpen(false)}+ <VipContentModal+ open={vipModalOpen}+ onClose={() => setVipModalOpen(false)}/></div></NoSSR>- );+ )}diff --git a/project/web/src/app/[lng]/accounts/accounts.module.scss b/project/web/src/app/[lng]/accounts/accounts.module.scssindex 341fae9d..cfebf427 100644--- a/project/web/src/app/[lng]/accounts/accounts.module.scss+++ b/project/web/src/app/[lng]/accounts/accounts.module.scss@@ -96,8 +96,12 @@}@keyframes fadeIn {- from { opacity: 0; }- to { opacity: 1; }+ from {+ opacity: 0;+ }+ to {+ opacity: 1;+ }}// 微信浏览器提示:容器@@ -207,14 +211,15 @@right: 20px;z-index: 1002;pointer-events: none;- background-color: #E9F6FF;+ background-color: #e9f6ff;animation: arrowPulse 2s ease-in-out infinite;border-radius: 50%;padding: 10px;}@keyframes arrowPulse {- 0%, 100% {+ 0%,+ 100% {opacity: 0.8;transform: translateY(-50%) scale(1);}@@ -233,4 +238,4 @@opacity: 1;transform: scale(1);}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/accounts/auth/page.tsx b/project/web/src/app/[lng]/accounts/auth/page.tsxindex a1c4411c..5066c862 100644--- a/project/web/src/app/[lng]/accounts/auth/page.tsx+++ b/project/web/src/app/[lng]/accounts/auth/page.tsx@@ -1,3 +1,3 @@export default function Page() {- return <p>Hello, auth res</p>;+ return <p>Hello, auth res</p>}diff --git a/project/web/src/app/[lng]/accounts/components/AccountSidebar/AccountSidebar.module.scss b/project/web/src/app/[lng]/accounts/components/AccountSidebar/AccountSidebar.module.scssindex a343b6e9..c206a438 100644--- a/project/web/src/app/[lng]/accounts/components/AccountSidebar/AccountSidebar.module.scss+++ b/project/web/src/app/[lng]/accounts/components/AccountSidebar/AccountSidebar.module.scss@@ -69,7 +69,7 @@.accountSidebar-ipType {display: inline-block;background-color: var(--grayColor2);- color: #8A5BF2;+ color: #8a5bf2;padding: 1px 2px;border-radius: 4px;font-size: 10px;@@ -77,13 +77,13 @@margin-right: 4px;}- .accountSidebar-ipType[data-type="direct"] {+ .accountSidebar-ipType[data-type='direct'] {background-color: #e6f7ff;color: #1890ff;// border: 1px solid #91d5ff;}- .accountSidebar-ipType[data-type="proxy"] {+ .accountSidebar-ipType[data-type='proxy'] {background-color: #fff7e6;color: #fa8c16;// border: 1px solid #ffd591;@@ -113,7 +113,7 @@background: var(--grayColor2);border-radius: 4px;transition: all 0.2s ease;-+&:hover {background: var(--grayColor3);color: var(--grayColor7);@@ -271,7 +271,7 @@justify-content: center;z-index: 10;cursor: pointer;-+&-text {color: white;font-size: 12px;@@ -408,7 +408,8 @@width: 100%;}}- &-allUser, .userManage-sidebar-list-item {+ &-allUser,+ .userManage-sidebar-list-item {display: flex;justify-content: space-between;padding-right: 10px;@@ -480,7 +481,6 @@justify-content: space-between;margin-bottom: 10px;&-proxy {-}}@@ -558,4 +558,4 @@white-space: nowrap;margin-right: 10px;}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/accounts/components/AccountSidebar/AccountSidebar.tsx b/project/web/src/app/[lng]/accounts/components/AccountSidebar/AccountSidebar.tsxindex 04b44e81..adecb0b3 100644--- a/project/web/src/app/[lng]/accounts/components/AccountSidebar/AccountSidebar.tsx+++ b/project/web/src/app/[lng]/accounts/components/AccountSidebar/AccountSidebar.tsx@@ -1,138 +1,149 @@-import {+import type {ForwardedRef,- forwardRef,- memo,- useCallback,- useEffect,- useMemo,- useRef,- useState,-} from "react";-import styles from "./AccountSidebar.module.scss";+} from 'react'+import type { IMCPManagerModalRef } from './MCPManagerModal'+import type { IUserManageModalRef } from './UserManageModal'+import type { SocialAccount } from '@/api/types/account.type'+import type {+ IpLocationInfo,+} from '@/utils/ipLocation'++// import { accountLogin, acpAccountLoginCheck } from "@/icp/account";+import {+ CheckCircleOutlined,+ DeleteOutlined,+ DownOutlined,+ DragOutlined,+ PlusOutlined,+ UpOutlined,+ UserOutlined,+ WarningOutlined,+} from '@ant-design/icons'import {Avatar,Button,Collapse,+ Input,+ message,+ Modal,Popover,Skeleton,Tooltip,- Modal,- Input,- message,-} from "antd";-import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";--// 六点拖拽图标组件-const SixDotsIcon = () => (- <svg width="12" height="12" viewBox="0 0 12 12" fill="none">- <circle cx="2" cy="2" r="1" fill="currentColor" />- <circle cx="6" cy="2" r="1" fill="currentColor" />- <circle cx="10" cy="2" r="1" fill="currentColor" />- <circle cx="2" cy="6" r="1" fill="currentColor" />- <circle cx="6" cy="6" r="1" fill="currentColor" />- <circle cx="10" cy="6" r="1" fill="currentColor" />- </svg>-);--// import { accountLogin, acpAccountLoginCheck } from "@/icp/account";+} from 'antd'import {- CheckCircleOutlined,- PlusOutlined,- UserOutlined,- WarningOutlined,- DeleteOutlined,- UpOutlined,- DownOutlined,- DragOutlined,-} from "@ant-design/icons";-import { useShallow } from "zustand/react/shallow";-import { useAccountStore } from "@/store/account";-import UserManageModal, { IUserManageModalRef } from "./UserManageModal";-import MCPManagerModal, { IMCPManagerModalRef } from "./MCPManagerModal";-import { AccountPlatInfoMap, PlatType } from "@/app/config/platConfig";-import { AccountStatus } from "@/app/config/accountConfig";-import { SocialAccount } from "@/api/types/account.type";-import { getOssUrl } from "@/utils/oss";-import { useTransClient } from "@/app/i18n/client";+ forwardRef,+ memo,+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react'+import { DragDropContext, Draggable, Droppable } from 'react-beautiful-dnd'+import { useShallow } from 'zustand/react/shallow'+import { createAccountGroupApi, updateAccountApi } from '@/api/account'+import { apiUpdateAccountGroupSortRank, apiUpdateAccountSortRank } from '@/api/accountSort'+import { bilibiliSkip } from '@/app/[lng]/accounts/plat/BilibiliLogin'+import { FacebookPagesModal, facebookSkip } from '@/app/[lng]/accounts/plat/FacebookLogin'+import { instagramSkip } from '@/app/[lng]/accounts/plat/InstagramLogin'+// 导入各平台授权函数+import { kwaiSkip } from '@/app/[lng]/accounts/plat/kwaiLogin'+import { linkedinSkip } from '@/app/[lng]/accounts/plat/LinkedinLogin'+import { pinterestSkip } from '@/app/[lng]/accounts/plat/PinterestLogin'+import { threadsSkip } from '@/app/[lng]/accounts/plat/ThreadsLogin'+import { tiktokSkip } from '@/app/[lng]/accounts/plat/TiktokLogin'+import { twitterSkip } from '@/app/[lng]/accounts/plat/TwtterLogin'+import { wxGzhSkip } from '@/app/[lng]/accounts/plat/WxGzh'+import { youtubeSkip } from '@/app/[lng]/accounts/plat/YoutubeLogin'+import { AccountStatus } from '@/app/config/accountConfig'+import { AccountPlatInfoMap, PlatType } from '@/app/config/platConfig'+import { useTransClient } from '@/app/i18n/client'+import DownloadAppModal from '@/components/common/DownloadAppModal'+import { useAccountStore } from '@/store/account'import {- getIpLocation,- IpLocationInfo,- formatLocationInfo,extractCountry,-} from "@/utils/ipLocation";-import { createAccountGroupApi, updateAccountApi } from "@/api/account";-import { apiUpdateAccountGroupSortRank, apiUpdateAccountSortRank } from "@/api/accountSort";-import AddAccountModal from "../AddAccountModal";-import DeleteUserConfirmModal from "./DeleteUserConfirmModal";-// 导入各平台授权函数-import { kwaiSkip } from "@/app/[lng]/accounts/plat/kwaiLogin";-import { bilibiliSkip } from "@/app/[lng]/accounts/plat/BilibiliLogin";-import { youtubeSkip } from "@/app/[lng]/accounts/plat/YoutubeLogin";-import { twitterSkip } from "@/app/[lng]/accounts/plat/TwtterLogin";-import { tiktokSkip } from "@/app/[lng]/accounts/plat/TiktokLogin";-import { facebookSkip, FacebookPagesModal } from "@/app/[lng]/accounts/plat/FacebookLogin";-import { instagramSkip } from "@/app/[lng]/accounts/plat/InstagramLogin";-import { threadsSkip } from "@/app/[lng]/accounts/plat/ThreadsLogin";-import { wxGzhSkip } from "@/app/[lng]/accounts/plat/WxGzh";-import { pinterestSkip } from "@/app/[lng]/accounts/plat/PinterestLogin";-import { linkedinSkip } from "@/app/[lng]/accounts/plat/LinkedinLogin";-import DownloadAppModal from "@/components/common/DownloadAppModal";+ formatLocationInfo,+ getIpLocation,+} from '@/utils/ipLocation'+import { getOssUrl } from '@/utils/oss'+import AddAccountModal from '../AddAccountModal'+import styles from './AccountSidebar.module.scss'+import DeleteUserConfirmModal from './DeleteUserConfirmModal'+import MCPManagerModal from './MCPManagerModal'+import UserManageModal from './UserManageModal'++// 六点拖拽图标组件+function SixDotsIcon() {+ return (+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none">+ <circle cx="2" cy="2" r="1" fill="currentColor" />+ <circle cx="6" cy="2" r="1" fill="currentColor" />+ <circle cx="10" cy="2" r="1" fill="currentColor" />+ <circle cx="2" cy="6" r="1" fill="currentColor" />+ <circle cx="6" cy="6" r="1" fill="currentColor" />+ <circle cx="10" cy="6" r="1" fill="currentColor" />+ </svg>+ )+}export interface IAccountSidebarRef {}export interface IAccountSidebarProps {// 选择的账户id- activeAccountId: string;+ activeAccountId: string// 切换选择的账户- onAccountChange: (info: SocialAccount) => void;+ onAccountChange: (info: SocialAccount) => void// 排除的平台类型- excludePlatforms?: PlatType[];+ excludePlatforms?: PlatType[]// 侧边栏内容顶部扩展内容- sidebarTopExtra?: React.ReactNode;+ sidebarTopExtra?: React.ReactNode// 是否在interactive页面(用于应用特殊的平台过滤和蒙层效果)- isInteractivePage?: boolean;+ isInteractivePage?: boolean}-const AccountStatusView = ({ account }: { account: SocialAccount }) => {- const { t } = useTransClient("account");+function AccountStatusView({ account }: { account: SocialAccount }) {+ const { t } = useTransClient('account')if (account.status === AccountStatus.USABLE) {return (<>- <CheckCircleOutlined style={{ color: "var(--successColor)" }} />- {t("online")}+ <CheckCircleOutlined style={{ color: 'var(--successColor)' }} />+ {t('online')}</>- );+ )}return (<>- <WarningOutlined style={{ color: "var(--warningColor)" }} />- {t("offline")}+ <WarningOutlined style={{ color: 'var(--warningColor)' }} />+ {t('offline')}</>- );-};+ )+}-const AccountPopoverInfo = ({+function AccountPopoverInfo({accountInfo,onDeleteClick,}: {- accountInfo: SocialAccount;- onDeleteClick?: (account: SocialAccount) => void;-}) => {- const { t } = useTransClient("account");- const platInfo = AccountPlatInfoMap.get(accountInfo.type)!;- const [detLoading, setDetLoading] = useState(false);+ accountInfo: SocialAccount+ onDeleteClick?: (account: SocialAccount) => void+}) {+ const { t } = useTransClient('account')+ const platInfo = AccountPlatInfoMap.get(accountInfo.type)!+ const [detLoading, setDetLoading] = useState(false)return (<divclassName={styles.accountPopoverInfo}- onClick={(e) => e.stopPropagation()}+ onClick={e => e.stopPropagation()}><div className="accountPopoverInfo_top"><Avatar src={getOssUrl(accountInfo.avatar)} size="large" /><div className="accountPopoverInfo_top-right"><div className="accountPopoverInfo-item">- <p>{t("nickname")}:</p>+ <p>+ {t('nickname')}+ :+ </p><p>{accountInfo.nickname}</p></div>{/* <div className="accountPopoverInfo-item">@@ -143,14 +154,20 @@ const AccountPopoverInfo = ({</p></div> */}<div className="accountPopoverInfo-item">- <p>{t("fansCount")}:</p>+ <p>+ {t('fansCount')}+ :+ </p><p>{accountInfo.fansCount ?? 0}</p></div></div></div><div className="accountPopoverInfo-item">- <p>{t("loginStatus")}:</p>+ <p>+ {t('loginStatus')}+ :+ </p><p><AccountStatusView account={accountInfo} />@@ -160,16 +177,16 @@ const AccountPopoverInfo = ({ghostsize="small"icon={<DeleteOutlined />}- style={{ marginLeft: 18, border: "none" }}+ style={{ marginLeft: 18, border: 'none' }}onClick={() => onDeleteClick?.(accountInfo)}>- {t("deleteAccount" as any)}+ {t('deleteAccount' as any)}</Button></p></div></div>- );-};+ )+}const AccountSidebar = memo(forwardRef(@@ -183,8 +200,8 @@ const AccountSidebar = memo(}: IAccountSidebarProps,ref: ForwardedRef<IAccountSidebarRef>,) => {- const { t } = useTransClient("account");- const pubAccountDetModuleRef = useRef<any>(null);+ const { t } = useTransClient('account')+ const pubAccountDetModuleRef = useRef<any>(null)const {accountList: fullAccountList,getAccountList,@@ -192,68 +209,68 @@ const AccountSidebar = memo(accountGroupList,accountLoading,} = useAccountStore(- useShallow((state) => ({+ useShallow(state => ({accountList: state.accountList,getAccountList: state.getAccountList,getAccountGroup: state.getAccountGroup,accountGroupList: state.accountGroupList,accountLoading: state.accountLoading,})),- );- const [userManageModalOpen, setUserManageModalOpen] = useState(false);- const userManageModalRef = useRef<IUserManageModalRef>(null);- const [mcpManagerModalOpen, setMcpManagerModalOpen] = useState(false);- const mcpManagerModalRef = useRef<IMCPManagerModalRef>(null);- const [deleteHitOpen, setDeleteHitOpen] = useState(false);- const [deleteLoading, setDeleteLoading] = useState(false);+ )+ const [userManageModalOpen, setUserManageModalOpen] = useState(false)+ const userManageModalRef = useRef<IUserManageModalRef>(null)+ const [mcpManagerModalOpen, setMcpManagerModalOpen] = useState(false)+ const mcpManagerModalRef = useRef<IMCPManagerModalRef>(null)+ const [deleteHitOpen, setDeleteHitOpen] = useState(false)+ const [deleteLoading, setDeleteLoading] = useState(false)const [deleteTarget, setDeleteTarget] = useState<SocialAccount | null>(null,- );+ )// IP地理位置信息状态- const [ipLocationInfo, setIpLocationInfo] =- useState<IpLocationInfo | null>(null);- const [ipLocationLoading, setIpLocationLoading] = useState(false);+ const [ipLocationInfo, setIpLocationInfo]+ = useState<IpLocationInfo | null>(null)+ const [ipLocationLoading, setIpLocationLoading] = useState(false)// 新建空间状态- const [openCreateGroup, setOpenCreateGroup] = useState(false);- const [groupName, setGroupName] = useState("");- const [createGroupLoading, setCreateGroupLoading] = useState(false);+ const [openCreateGroup, setOpenCreateGroup] = useState(false)+ const [groupName, setGroupName] = useState('')+ const [createGroupLoading, setCreateGroupLoading] = useState(false)// 新建空间相关函数const createGroupCancel = () => {- setOpenCreateGroup(false);- setGroupName("");- };+ setOpenCreateGroup(false)+ setGroupName('')+ }// 添加账号相关状态- const [isAddAccountOpen, setIsAddAccountOpen] = useState(false);- const preAccountIds = useRef<Set<string>>(new Set());- const pendingGroupIdRef = useRef<string | null>(null);- const isAssigningRef = useRef(false);- const snapshotReadyRef = useRef(false);- const allUser = useRef("-1");+ const [isAddAccountOpen, setIsAddAccountOpen] = useState(false)+ const preAccountIds = useRef<Set<string>>(new Set())+ const pendingGroupIdRef = useRef<string | null>(null)+ const isAssigningRef = useRef(false)+ const snapshotReadyRef = useRef(false)+ const allUser = useRef('-1')// 掉线账号重新登录确认弹窗状态- const [showReauthConfirm, setShowReauthConfirm] = useState(false);- const [reauthAccount, setReauthAccount] = useState<SocialAccount | null>(null);+ const [showReauthConfirm, setShowReauthConfirm] = useState(false)+ const [reauthAccount, setReauthAccount] = useState<SocialAccount | null>(null)// Facebook页面选择弹窗状态- const [showFacebookPagesModal, setShowFacebookPagesModal] = useState(false);-+ const [showFacebookPagesModal, setShowFacebookPagesModal] = useState(false)+// App下载提示弹窗状态- const [showAppDownloadModal, setShowAppDownloadModal] = useState(false);- const [mobileOnlyPlatform, setMobileOnlyPlatform] = useState<string>("");+ const [showAppDownloadModal, setShowAppDownloadModal] = useState(false)+ const [mobileOnlyPlatform, setMobileOnlyPlatform] = useState<string>('')// 排序相关状态- const [isGroupSorting, setIsGroupSorting] = useState(false);- const [isAccountSorting, setIsAccountSorting] = useState(false);-+ const [isGroupSorting, setIsGroupSorting] = useState(false)+ const [isAccountSorting, setIsAccountSorting] = useState(false)+// 本地账户排序状态,用于临时存储拖拽后的顺序- const [localAccountSort, setLocalAccountSort] = useState<Record<string, string[]>>({});-+ const [localAccountSort, setLocalAccountSort] = useState<Record<string, string[]>>({})+// 自动保存定时器引用- const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);+ const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null)// 在组件内部过滤账号列表,根据页面类型决定过滤逻辑const accountList = useMemo(() => {@@ -261,199 +278,210 @@ const AccountSidebar = memo(// 在interactive页面,只显示指定的平台const allowedPlatforms = [PlatType.Facebook,- PlatType.Instagram,+ PlatType.Instagram,PlatType.Threads,PlatType.Douyin,- PlatType.Xhs- ];+ PlatType.Xhs,+ ]return fullAccountList.filter(- (account) => !excludePlatforms.includes(account.type) && allowedPlatforms.includes(account.type),- );- } else {+ account => !excludePlatforms.includes(account.type) && allowedPlatforms.includes(account.type),+ )+ }+ else {// 在其他页面,正常过滤return fullAccountList.filter(- (account) => !excludePlatforms.includes(account.type),- );+ account => !excludePlatforms.includes(account.type),+ )}- }, [fullAccountList, excludePlatforms, isInteractivePage]);+ }, [fullAccountList, excludePlatforms, isInteractivePage])const defaultActiveKey = useMemo(() => {- return accountGroupList.find((v) => v.isDefault)?.id;- }, [accountGroupList]);+ return accountGroupList.find(v => v.isDefault)?.id+ }, [accountGroupList])// 获取IP地理位置信息useEffect(() => {const fetchIpLocation = async () => {try {- setIpLocationLoading(true);- const info = await getIpLocation();- setIpLocationInfo(info);- } catch (error) {- console.error(t("messages.ipLocationError" as any), error);- } finally {- setIpLocationLoading(false);+ setIpLocationLoading(true)+ const info = await getIpLocation()+ setIpLocationInfo(info)+ }+ catch (error) {+ console.error(t('messages.ipLocationError' as any), error)+ }+ finally {+ setIpLocationLoading(false)}- };+ }// 只在组件挂载时获取一次IP信息- fetchIpLocation();- }, []);+ fetchIpLocation()+ }, [])// 处理离线账户点击,显示确认弹窗const handleOfflineAccountClick = useCallback((account: SocialAccount) => {- setReauthAccount(account);- setShowReauthConfirm(true);- }, []);+ setReauthAccount(account)+ setShowReauthConfirm(true)+ }, [])// 确认重新登录const handleConfirmReauth = useCallback(async () => {- if (!reauthAccount) return;-- const platform = reauthAccount.type;- const targetSpaceId = reauthAccount.groupId; // 使用账户原本的空间ID-- setShowReauthConfirm(false);-+ if (!reauthAccount)+ return++ const platform = reauthAccount.type+ const targetSpaceId = reauthAccount.groupId // 使用账户原本的空间ID++ setShowReauthConfirm(false)+try {// 根据平台类型调用对应的授权函数,传递目标空间IDswitch (platform) {case PlatType.KWAI:- await kwaiSkip(platform, targetSpaceId);- break;+ await kwaiSkip(platform, targetSpaceId)+ breakcase PlatType.BILIBILI:- await bilibiliSkip(platform, targetSpaceId);- break;+ await bilibiliSkip(platform, targetSpaceId)+ breakcase PlatType.YouTube:- await youtubeSkip(platform, targetSpaceId);- break;+ await youtubeSkip(platform, targetSpaceId)+ breakcase PlatType.Twitter:- await twitterSkip(platform, targetSpaceId);- break;+ await twitterSkip(platform, targetSpaceId)+ breakcase PlatType.Tiktok:- await tiktokSkip(platform, targetSpaceId);- break;+ await tiktokSkip(platform, targetSpaceId)+ breakcase PlatType.Facebook:try {- await facebookSkip(platform, targetSpaceId);+ await facebookSkip(platform, targetSpaceId)// Facebook授权成功后显示页面选择弹窗- setShowFacebookPagesModal(true);- } catch (error) {- console.error(t('messages.facebookAuthFailed' as any), error);+ setShowFacebookPagesModal(true)}- break;+ catch (error) {+ console.error(t('messages.facebookAuthFailed' as any), error)+ }+ breakcase PlatType.Instagram:- await instagramSkip(platform, targetSpaceId);- break;+ await instagramSkip(platform, targetSpaceId)+ breakcase PlatType.Threads:- await threadsSkip(platform, targetSpaceId);- break;+ await threadsSkip(platform, targetSpaceId)+ breakcase PlatType.WxGzh:- await wxGzhSkip(platform, targetSpaceId);- break;+ await wxGzhSkip(platform, targetSpaceId)+ breakcase PlatType.Pinterest:- await pinterestSkip(platform, targetSpaceId);- break;+ await pinterestSkip(platform, targetSpaceId)+ breakcase PlatType.LinkedIn:- await linkedinSkip(platform, targetSpaceId);- break;+ await linkedinSkip(platform, targetSpaceId)+ breakdefault:- console.warn(`${t('messages.unsupportedPlatform' as any)}: ${platform}`);- message.warning(t('messages.platformNotSupported' as any, { platform }));- return;+ console.warn(`${t('messages.unsupportedPlatform' as any)}: ${platform}`)+ message.warning(t('messages.platformNotSupported' as any, { platform }))+ return}// 授权完成后刷新账号列表setTimeout(async () => {try {- await getAccountList();- console.log(t('messages.accountListRefreshed' as any));- } catch (error) {- console.error(t('messages.refreshAccountListFailed' as any), error);+ await getAccountList()+ console.log(t('messages.accountListRefreshed' as any))+ }+ catch (error) {+ console.error(t('messages.refreshAccountListFailed' as any), error)}- }, 3000); // 等待3秒让授权完成- } catch (error) {- console.error(t('messages.authFailed' as any), error);- message.error(t('messages.authFailed' as any) + ',' + t('messages.pleaseRetry' as any));- } finally {- setReauthAccount(null);+ }, 3000) // 等待3秒让授权完成+ }+ catch (error) {+ console.error(t('messages.authFailed' as any), error)+ message.error(`${t('messages.authFailed' as any)},${t('messages.pleaseRetry' as any)}`)+ }+ finally {+ setReauthAccount(null)}- }, [reauthAccount, getAccountList, t]);+ }, [reauthAccount, getAccountList, t])// 处理Facebook页面选择成功const handleFacebookPagesSuccess = () => {- setShowFacebookPagesModal(false);+ setShowFacebookPagesModal(false)// 可以在这里添加成功提示或其他逻辑- };+ }// 分组排序函数const handleGroupSort = async (groupId: string, direction: 'up' | 'down') => {- const sortedGroups = [...accountGroupList].sort((a, b) => (a.rank || 0) - (b.rank || 0));- const currentIndex = sortedGroups.findIndex(g => g.id === groupId);-- if (currentIndex === -1) return;-- const newIndex = direction === 'up' ? currentIndex - 1 : currentIndex + 1;- if (newIndex < 0 || newIndex >= sortedGroups.length) return;-+ const sortedGroups = [...accountGroupList].sort((a, b) => (a.rank || 0) - (b.rank || 0))+ const currentIndex = sortedGroups.findIndex(g => g.id === groupId)++ if (currentIndex === -1)+ return++ const newIndex = direction === 'up' ? currentIndex - 1 : currentIndex + 1+ if (newIndex < 0 || newIndex >= sortedGroups.length)+ return;+// 交换位置- [sortedGroups[currentIndex], sortedGroups[newIndex]] = [sortedGroups[newIndex], sortedGroups[currentIndex]];-+ [sortedGroups[currentIndex], sortedGroups[newIndex]] = [sortedGroups[newIndex], sortedGroups[currentIndex]]+// 更新rankconst updateList = sortedGroups.map((group, index) => ({id: group.id,- rank: index- }));-+ rank: index,+ }))+try {- await apiUpdateAccountGroupSortRank({ list: updateList });- await getAccountGroup();- message.success(t("messages.sortSuccess" as any));- } catch (error) {- message.error(t("messages.sortFailed" as any));+ await apiUpdateAccountGroupSortRank({ list: updateList })+ await getAccountGroup()+ message.success(t('messages.sortSuccess' as any))}- };+ catch (error) {+ message.error(t('messages.sortFailed' as any))+ }+ }// 账户拖拽排序const handleAccountDragEnd = (result: any) => {- if (!result.destination) return;-- const { source, destination } = result;- const groupId = source.droppableId;-+ if (!result.destination)+ return++ const { source, destination } = result+ const groupId = source.droppableId+// 获取该分组的账户列表- const groupAccounts = isInteractivePage ?- accountList.filter(account => account.groupId === groupId) :- accountGroupList.find(g => g.id === groupId)?.children || [];-+ const groupAccounts = isInteractivePage+ ? accountList.filter(account => account.groupId === groupId)+ : accountGroupList.find(g => g.id === groupId)?.children || []+// 获取当前分组的本地排序,如果没有则使用原始排序const currentSort = localAccountSort[groupId] || groupAccounts.sort((a, b) => (a.rank || 0) - (b.rank || 0))- .map(account => account.id);-+ .map(account => account.id)+// 创建新的排序数组- const newSort = [...currentSort];- const [movedId] = newSort.splice(source.index, 1);- newSort.splice(destination.index, 0, movedId);-+ const newSort = [...currentSort]+ const [movedId] = newSort.splice(source.index, 1)+ newSort.splice(destination.index, 0, movedId)+// 更新本地排序状态setLocalAccountSort(prev => ({...prev,- [groupId]: newSort- }));-+ [groupId]: newSort,+ }))const updateList = newSort.map((accountId, index) => ({id: accountId,- rank: index- }));+ rank: index,+ }))- apiUpdateAccountSortRank({ groupId, list: updateList });+ apiUpdateAccountSortRank({ groupId, list: updateList })// // 清除之前的定时器// if (saveTimeoutRef.current) {// clearTimeout(saveTimeoutRef.current);// }-+// // 设置新的定时器,2秒后自动保存// saveTimeoutRef.current = setTimeout(async () => {// try {@@ -461,7 +489,7 @@ const AccountSidebar = memo(// id: accountId,// rank: index// }));-+// await apiUpdateAccountSortRank({ groupId, list: updateList });// // 保存成功后清除本地排序状态,让界面使用服务器数据// setLocalAccountSort(prev => {@@ -475,65 +503,71 @@ const AccountSidebar = memo(// message.error(t("messages.sortFailed" as any));// }// }, 2000);- };+ }// 添加账号流程const openAddAccountFlow = async () => {if (accountGroupList.length === 0) {- message.error(t("messages.createSpaceFirst" as any));- return;+ message.error(t('messages.createSpaceFirst' as any))+ return}// 直接打开AddAccountModal,让用户选择空间if ((useAccountStore.getState().accountList || []).length === 0) {- await getAccountList();+ await getAccountList()}preAccountIds.current = new Set(- (useAccountStore.getState().accountList || []).map((v) => v.id),- );- snapshotReadyRef.current = true;- setIsAddAccountOpen(true);- };+ (useAccountStore.getState().accountList || []).map(v => v.id),+ )+ snapshotReadyRef.current = true+ setIsAddAccountOpen(true)+ }// 监听账号列表变化,自动分配新账号到当前空间useEffect(() => {const maybeAssign = async () => {- if (!pendingGroupIdRef.current) return;- if (isAssigningRef.current) return;- if (!snapshotReadyRef.current) return;- const currList = fullAccountList || [];+ if (!pendingGroupIdRef.current)+ return+ if (isAssigningRef.current)+ return+ if (!snapshotReadyRef.current)+ return+ const currList = fullAccountList || []const newAccounts = currList.filter(- (a) => !preAccountIds.current.has(a.id),- );- if (newAccounts.length === 0) return;- isAssigningRef.current = true;+ a => !preAccountIds.current.has(a.id),+ )+ if (newAccounts.length === 0)+ return+ isAssigningRef.current = truetry {- const targetGroupId = pendingGroupIdRef.current!;+ const targetGroupId = pendingGroupIdRef.current!for (const acc of newAccounts) {try {- await updateAccountApi({ id: acc.id, groupId: targetGroupId });- } catch {}+ await updateAccountApi({ id: acc.id, groupId: targetGroupId })+ }+ catch {}}- await getAccountList();- message.success(t("accountAddedToSpace"));- } finally {- pendingGroupIdRef.current = null;- preAccountIds.current = new Set();- isAssigningRef.current = false;- snapshotReadyRef.current = false;+ await getAccountList()+ message.success(t('accountAddedToSpace'))}- };- maybeAssign();- }, [fullAccountList]);+ finally {+ pendingGroupIdRef.current = null+ preAccountIds.current = new Set()+ isAssigningRef.current = false+ snapshotReadyRef.current = false+ }+ }+ maybeAssign()+ }, [fullAccountList])// 组件卸载时清理定时器useEffect(() => {return () => {if (saveTimeoutRef.current) {- clearTimeout(saveTimeoutRef.current);+ clearTimeout(saveTimeoutRef.current)}- };- }, []);+ }+ }, [])return (<>@@ -551,7 +585,7 @@ const AccountSidebar = memo(<AddAccountModalopen={isAddAccountOpen}onClose={async () => {- setIsAddAccountOpen(false);+ setIsAddAccountOpen(false)}}onAddSuccess={async (acc) => {try {@@ -559,12 +593,13 @@ const AccountSidebar = memo(await updateAccountApi({id: acc.id,groupId: pendingGroupIdRef.current,- });- message.success(t("accountAddedToSpace"));+ })+ message.success(t('accountAddedToSpace'))}- } finally {- pendingGroupIdRef.current = null;- await getAccountList();+ }+ finally {+ pendingGroupIdRef.current = null+ await getAccountList()}}}showSpaceSelector={true}@@ -573,66 +608,69 @@ const AccountSidebar = memo({/* 新建空间Modal */}<Modalopen={openCreateGroup}- title={t("createSpace.title")}+ title={t('createSpace.title')}onCancel={createGroupCancel}- footer={+ footer={(<><Button onClick={createGroupCancel}>- {t("createSpace.cancel")}+ {t('createSpace.cancel')}</Button><Buttontype="primary"onClick={async () => {if (!groupName.trim()) {- message.error(t("createSpace.nameRequired"));- return;+ message.error(t('createSpace.nameRequired'))+ return}- setCreateGroupLoading(true);+ setCreateGroupLoading(true)try {await createAccountGroupApi({name: groupName.trim(),- });- await getAccountGroup();+ })+ await getAccountGroup()// message.success(t("createSpace.success"));- createGroupCancel();-- } catch (error) {- message.error(t("createSpace.failed"));- } finally {- setCreateGroupLoading(false);+ createGroupCancel()+ }+ catch (error) {+ message.error(t('createSpace.failed'))+ }+ finally {+ setCreateGroupLoading(false)}}}loading={createGroupLoading}>- {t("createSpace.save")}+ {t('createSpace.save')}</Button></>- }+ )}><div className={styles.createGroup}>- <label>{t("createSpace.name")}</label>+ <label>{t('createSpace.name')}</label><Inputvalue={groupName}- placeholder={t("createSpace.namePlaceholder")}- onChange={(e) => setGroupName(e.target.value)}+ placeholder={t('createSpace.namePlaceholder')}+ onChange={e => setGroupName(e.target.value)}onPressEnter={async () => {if (!groupName.trim()) {- message.error(t("createSpace.nameRequired"));+ message.error(t('createSpace.nameRequired'))- return;+ return}- setCreateGroupLoading(true);+ setCreateGroupLoading(true)try {await createAccountGroupApi({name: groupName.trim(),- });- await getAccountGroup();- message.success(t("createSpace.success"));- createGroupCancel();- } catch (error) {- message.error(t("createSpace.failed"));- } finally {- setCreateGroupLoading(false);+ })+ await getAccountGroup()+ message.success(t('createSpace.success'))+ createGroupCancel()+ }+ catch (error) {+ message.error(t('createSpace.failed'))+ }+ finally {+ setCreateGroupLoading(false)}}}/>@@ -644,11 +682,11 @@ const AccountSidebar = memo(<div className="accountSidebar-top-box"><ButtononClick={() => {- setUserManageModalOpen(true);+ setUserManageModalOpen(true)}}><UserOutlined />- {t("accountManager")}+ {t('accountManager')}</Button></div>{/* mcp 按钮 */}@@ -658,11 +696,11 @@ const AccountSidebar = memo(type="primary"style={{background:- "linear-gradient(90deg, #625BF2 0%, #925BF2 100%)",+ 'linear-gradient(90deg, #625BF2 0%, #925BF2 100%)',}}onClick={() => setMcpManagerModalOpen(true)}>- {t("mcpManager")}+ {t('mcpManager')}</Button></div></div>@@ -683,246 +721,255 @@ const AccountSidebar = memo(items={accountGroupList.sort((a, b) => (a.rank || 0) - (b.rank || 0)).map((v) => {- // 为默认分组添加IP和地址信息- const isDefaultGroup = v.isDefault;- const showIpInfo = isDefaultGroup && ipLocationInfo;-- // 计算过滤后的账户数量和在线数量- const groupAccounts = isInteractivePage ?- accountList.filter(account => account.groupId === v.id) :- v.children || [];- const totalCount = groupAccounts.length;- const onlineCount = groupAccounts.filter(account => account.status === AccountStatus.USABLE).length;-- return {- key: v.id,- label: (- <>- <div className="accountSidebar-groupLabel">- <span className="accountSidebar-groupName">- {v.name}- </span>- <span className="accountSidebar-userCount">- {onlineCount}/{totalCount}- </span>- {/* 根据proxyIp判断显示IP信息 */}- {!v.proxyIp || v.proxyIp === "" ? (- // 本地IP显示- <div className="accountSidebar-ipInfo">- <span className="accountSidebar-ipType" data-type="direct">{t("ipType.direct")}</span>- {ipLocationLoading ? (- <span className="accountSidebar-ipLoading">- {t("ipInfo.loading")}- </span>- ) : ipLocationInfo ? (- <Tooltip- title={t("ipInfo.tooltip", {- asn: ipLocationInfo.asn,- org: ipLocationInfo.org,- })}- >- <span className="accountSidebar-ipText">- {formatLocationInfo(ipLocationInfo)}- </span>- </Tooltip>+ // 为默认分组添加IP和地址信息+ const isDefaultGroup = v.isDefault+ const showIpInfo = isDefaultGroup && ipLocationInfo++ // 计算过滤后的账户数量和在线数量+ const groupAccounts = isInteractivePage+ ? accountList.filter(account => account.groupId === v.id)+ : v.children || []+ const totalCount = groupAccounts.length+ const onlineCount = groupAccounts.filter(account => account.status === AccountStatus.USABLE).length++ return {+ key: v.id,+ label: (+ <>+ <div className="accountSidebar-groupLabel">+ <span className="accountSidebar-groupName">+ {v.name}+ </span>+ <span className="accountSidebar-userCount">+ {onlineCount}+ /+ {totalCount}+ </span>+ {/* 根据proxyIp判断显示IP信息 */}+ {!v.proxyIp || v.proxyIp === '' ? (+ // 本地IP显示+ <div className="accountSidebar-ipInfo">+ <span className="accountSidebar-ipType" data-type="direct">{t('ipType.direct')}</span>+ {ipLocationLoading+ ? (+ <span className="accountSidebar-ipLoading">+ {t('ipInfo.loading')}+ </span>+ )+ : ipLocationInfo+ ? (+ <Tooltip+ title={t('ipInfo.tooltip', {+ asn: ipLocationInfo.asn,+ org: ipLocationInfo.org,+ })}+ >+ <span className="accountSidebar-ipText">+ {formatLocationInfo(ipLocationInfo)}+ </span>+ </Tooltip>+ )+ : (+ <span className="accountSidebar-ipError">+ {t('ipInfo.error')}+ </span>+ )}+ </div>) : (- <span className="accountSidebar-ipError">- {t("ipInfo.error")}- </span>+ // 数据中的IP显示+ v.ip+ && v.location && (+ <div className="accountSidebar-ipInfo">+ <span className="accountSidebar-ipType" data-type="proxy">{t('ipType.proxy')}</span>+ <Tooltip+ title={`IP: ${v.ip}\n位置: ${v.location}`}+ >+ <span className="accountSidebar-ipText">+ {extractCountry(v.location)}+ {' '}+ |+ {v.ip}+ </span>+ </Tooltip>+ </div>+ ))}- </div>- ) : (- // 数据中的IP显示- v.ip &&- v.location && (- <div className="accountSidebar-ipInfo">- <span className="accountSidebar-ipType" data-type="proxy">{t("ipType.proxy")}</span>- <Tooltip- title={`IP: ${v.ip}\n位置: ${v.location}`}- >- <span className="accountSidebar-ipText">- {extractCountry(v.location)} | {v.ip}- </span>+ {/* 分组排序按钮 */}+ <div className="accountSidebar-groupSort">+ <Tooltip title="上移">+ <Button+ type="text"+ size="small"+ icon={<UpOutlined />}+ onClick={(e) => {+ e.stopPropagation()+ handleGroupSort(v.id, 'up')+ }}+ />+ </Tooltip>+ <Tooltip title="下移">+ <Button+ type="text"+ size="small"+ icon={<DownOutlined />}+ onClick={(e) => {+ e.stopPropagation()+ handleGroupSort(v.id, 'down')+ }}+ /></Tooltip></div>- )- )}- {/* 分组排序按钮 */}- <div className="accountSidebar-groupSort">- <Tooltip title="上移">- <Button- type="text"- size="small"- icon={<UpOutlined />}- onClick={(e) => {- e.stopPropagation();- handleGroupSort(v.id, 'up');- }}- />- </Tooltip>- <Tooltip title="下移">- <Button- type="text"- size="small"- icon={<DownOutlined />}- onClick={(e) => {- e.stopPropagation();- handleGroupSort(v.id, 'down');- }}- />- </Tooltip>- </div>- </div>- </>- ),- children: (- <Droppable droppableId={v.id}>- {(provided) => (- <ul- key={v.id}- className="accountList"- {...provided.droppableProps}- ref={provided.innerRef}- >- {(() => {- // 获取该分组的账户列表- const groupAccounts = isInteractivePage ?- accountList.filter(account => account.groupId === v.id) :- v.children || [];-- // 获取本地排序,如果没有则使用原始排序- const localSort = localAccountSort[v.id];- let sortedAccounts = groupAccounts.sort((a, b) => (a.rank || 0) - (b.rank || 0));-- // 如果有本地排序,则按照本地排序重新排列- if (localSort && localSort.length > 0) {- const accountMap = new Map(sortedAccounts.map(account => [account.id, account]));- sortedAccounts = localSort- .map(id => accountMap.get(id))- .filter(Boolean) as typeof sortedAccounts;- }-- return sortedAccounts.map((account, index) => {- if (excludePlatforms.includes(account.type))- return "";- const platInfo = AccountPlatInfoMap.get(- account.type,- )!;-- // 检查是否为需要蒙层的平台(仅在interactive页面)- const isMobileOnlyPlatform = isInteractivePage && (account.type === PlatType.Douyin || account.type === PlatType.Xhs);-- return (- <Draggable key={account.id} draggableId={account.id} index={index}>- {(provided, snapshot) => (- <li- className={[- "accountList-item",- `${activeAccountId === account.id ? "accountList-item--active" : ""}`,- // 失效状态- account.status === AccountStatus.DISABLE &&- "accountList-item--disable",- // 移动端平台蒙层状态(仅在interactive页面)- isMobileOnlyPlatform && "accountList-item--mobile-only",- // 拖拽状态- snapshot.isDragging && "accountList-item--dragging",- ].join(" ")}- ref={provided.innerRef}- {...provided.draggableProps}+ </div>+ </>+ ),+ children: (+ <Droppable droppableId={v.id}>+ {provided => (+ <ul+ key={v.id}+ className="accountList"+ {...provided.droppableProps}+ ref={provided.innerRef}>- {/* 拖拽手柄 */}- <div- className="accountList-item-dragHandle"- {...provided.dragHandleProps}- onClick={(e) => e.stopPropagation()}- >- <SixDotsIcon />- </div>- <Avatar- style={{backgroundColor: 'aliceblue'}}- src={getOssUrl(account.avatar)}- size="large"- >- {account.nickname?.charAt(0)}- </Avatar>- <div- className="accountList-item-right"- onClick={async () => {- // 如果是移动端平台,显示下载提示- if (isMobileOnlyPlatform) {- setMobileOnlyPlatform(account.type === PlatType.Douyin ? "抖音" : "小红书");- setShowAppDownloadModal(true);- return;- }-- if (- account.status === AccountStatus.DISABLE- ) {- // 小红书平台即使是掉线状态也显示下载App弹窗- if (account.type === PlatType.Xhs) {- setMobileOnlyPlatform("小红书");- setShowAppDownloadModal(true);- return;- }- // 其他平台的掉线账户直接触发重新授权- await handleOfflineAccountClick(account);- return;- }- onAccountChange(account);- }}- >- <div- className="accountList-item-right-name"- title={account.nickname}- >- <Tooltip title={undefined}>- {account.nickname}- </Tooltip>- </div>- <div className="accountList-item-right-footer">- <p className="accountList-item-right-plat">- <img src={platInfo?.icon} />- <span>{platInfo?.name}</span>- </p>- <Popover- content={- <AccountPopoverInfo- accountInfo={account}- onDeleteClick={(acc) => {- setDeleteTarget(acc);- setDeleteHitOpen(true);- }}- />- }- placement="right"- >- ...- </Popover>- </div>- </div>-- {/* 移动端平台蒙层(仅在interactive页面) */}- {isMobileOnlyPlatform && (- <div className="accountList-item-overlay">- <div className="accountList-item-overlay-text">- {t('mobileOnlySupport' as any)}- </div>- </div>- )}- </li>- )}- </Draggable>- );- });- })()}- {provided.placeholder}- </ul>- )}- </Droppable>- ),- };- })}- />+ {(() => {+ // 获取该分组的账户列表+ const groupAccounts = isInteractivePage+ ? accountList.filter(account => account.groupId === v.id)+ : v.children || []++ // 获取本地排序,如果没有则使用原始排序+ const localSort = localAccountSort[v.id]+ let sortedAccounts = groupAccounts.sort((a, b) => (a.rank || 0) - (b.rank || 0))++ // 如果有本地排序,则按照本地排序重新排列+ if (localSort && localSort.length > 0) {+ const accountMap = new Map(sortedAccounts.map(account => [account.id, account]))+ sortedAccounts = localSort+ .map(id => accountMap.get(id))+ .filter(Boolean) as typeof sortedAccounts+ }++ return sortedAccounts.map((account, index) => {+ if (excludePlatforms.includes(account.type))+ return ''+ const platInfo = AccountPlatInfoMap.get(+ account.type,+ )!++ // 检查是否为需要蒙层的平台(仅在interactive页面)+ const isMobileOnlyPlatform = isInteractivePage && (account.type === PlatType.Douyin || account.type === PlatType.Xhs)++ return (+ <Draggable key={account.id} draggableId={account.id} index={index}>+ {(provided, snapshot) => (+ <li+ className={[+ 'accountList-item',+ `${activeAccountId === account.id ? 'accountList-item--active' : ''}`,+ // 失效状态+ account.status === AccountStatus.DISABLE+ && 'accountList-item--disable',+ // 移动端平台蒙层状态(仅在interactive页面)+ isMobileOnlyPlatform && 'accountList-item--mobile-only',+ // 拖拽状态+ snapshot.isDragging && 'accountList-item--dragging',+ ].join(' ')}+ ref={provided.innerRef}+ {...provided.draggableProps}+ >+ {/* 拖拽手柄 */}+ <div+ className="accountList-item-dragHandle"+ {...provided.dragHandleProps}+ onClick={e => e.stopPropagation()}+ >+ <SixDotsIcon />+ </div>+ <Avatar+ style={{ backgroundColor: 'aliceblue' }}+ src={getOssUrl(account.avatar)}+ size="large"+ >+ {account.nickname?.charAt(0)}+ </Avatar>+ <div+ className="accountList-item-right"+ onClick={async () => {+ // 如果是移动端平台,显示下载提示+ if (isMobileOnlyPlatform) {+ setMobileOnlyPlatform(account.type === PlatType.Douyin ? '抖音' : '小红书')+ setShowAppDownloadModal(true)+ return+ }++ if (+ account.status === AccountStatus.DISABLE+ ) {+ // 小红书平台即使是掉线状态也显示下载App弹窗+ if (account.type === PlatType.Xhs) {+ setMobileOnlyPlatform('小红书')+ setShowAppDownloadModal(true)+ return+ }+ // 其他平台的掉线账户直接触发重新授权+ await handleOfflineAccountClick(account)+ return+ }+ onAccountChange(account)+ }}+ >+ <div+ className="accountList-item-right-name"+ title={account.nickname}+ >+ <Tooltip title={undefined}>+ {account.nickname}+ </Tooltip>+ </div>+ <div className="accountList-item-right-footer">+ <p className="accountList-item-right-plat">+ <img src={platInfo?.icon} />+ <span>{platInfo?.name}</span>+ </p>+ <Popover+ content={(+ <AccountPopoverInfo+ accountInfo={account}+ onDeleteClick={(acc) => {+ setDeleteTarget(acc)+ setDeleteHitOpen(true)+ }}+ />+ )}+ placement="right"+ >+ ...+ </Popover>+ </div>+ </div>++ {/* 移动端平台蒙层(仅在interactive页面) */}+ {isMobileOnlyPlatform && (+ <div className="accountList-item-overlay">+ <div className="accountList-item-overlay-text">+ {t('mobileOnlySupport' as any)}+ </div>+ </div>+ )}+ </li>+ )}+ </Draggable>+ )+ })+ })()}+ {provided.placeholder}+ </ul>+ )}+ </Droppable>+ ),+ }+ })}+ /></DragDropContext></div>)}@@ -932,20 +979,20 @@ const AccountSidebar = memo(type="default"icon={<PlusOutlined />}onClick={openAddAccountFlow}- style={{ width: "100%", marginBottom: "10px" }}+ style={{ width: '100%', marginBottom: '10px' }}>- {t("addAccount")}+ {t('addAccount')}</Button><Buttontype="primary"icon={<PlusOutlined />}onClick={() => {- setOpenCreateGroup(true);+ setOpenCreateGroup(true)}}- style={{ width: "100%" }}+ style={{ width: '100%' }}>- {t("createSpace.button")}+ {t('createSpace.button')}</Button></div>{/* 删除账户确认弹窗(复用组件) */}@@ -953,12 +1000,12 @@ const AccountSidebar = memo(open={deleteHitOpen}deleteUsers={deleteTarget ? [deleteTarget] : []}onClose={() => {- setDeleteHitOpen(false);+ setDeleteHitOpen(false)}}onDeleteSuccess={async () => {- await getAccountList();- setDeleteTarget(null);- message.success(t("messages.deleteSuccess" as any));+ await getAccountList()+ setDeleteTarget(null)+ message.success(t('messages.deleteSuccess' as any))}}/>@@ -968,7 +1015,7 @@ const AccountSidebar = memo(onClose={() => setShowFacebookPagesModal(false)}onSuccess={handleFacebookPagesSuccess}/>-+{/* App下载提示弹窗(仅在interactive页面显示) */}{isInteractivePage && (<DownloadAppModal@@ -982,28 +1029,28 @@ const AccountSidebar = memo({/* 掉线账号重新登录确认弹窗 */}<Modalopen={showReauthConfirm}- title={t("reauthConfirm.title" as any)}+ title={t('reauthConfirm.title' as any)}onCancel={() => {- setShowReauthConfirm(false);- setReauthAccount(null);+ setShowReauthConfirm(false)+ setReauthAccount(null)}}- footer={+ footer={(<Buttontype="primary"onClick={handleConfirmReauth}>- {t("reauthConfirm.loginAgain" as any)}+ {t('reauthConfirm.loginAgain' as any)}</Button>- }+ )}><div className={styles.reauthConfirm}>{reauthAccount && (<div><p style={{ marginBottom: '16px' }}>- {t("reauthConfirm.content" as any, {+ {t('reauthConfirm.content' as any, {platformName: AccountPlatInfoMap.get(reauthAccount.type)?.name || reauthAccount.type,nickname: reauthAccount.nickname,- spaceName: accountGroupList.find(group => group.id === reauthAccount.groupId)?.name || t("defaultSpace")+ spaceName: accountGroupList.find(group => group.id === reauthAccount.groupId)?.name || t('defaultSpace'),})}</p></div>@@ -1012,10 +1059,10 @@ const AccountSidebar = memo(</Modal></div></>- );+ )},),-);-AccountSidebar.displayName = "AccountSidebar";+)+AccountSidebar.displayName = 'AccountSidebar'-export default AccountSidebar;+export default AccountSidebardiff --git a/project/web/src/app/[lng]/accounts/components/AccountSidebar/DeleteUserConfirmModal.tsx b/project/web/src/app/[lng]/accounts/components/AccountSidebar/DeleteUserConfirmModal.tsxindex df9afe35..40657762 100644--- a/project/web/src/app/[lng]/accounts/components/AccountSidebar/DeleteUserConfirmModal.tsx+++ b/project/web/src/app/[lng]/accounts/components/AccountSidebar/DeleteUserConfirmModal.tsx@@ -1,18 +1,19 @@-import { ForwardedRef, forwardRef, memo, useState } from "react";-import styles from "@/app/[lng]/accounts/components/AccountSidebar/AccountSidebar.module.scss";-import { Button, Modal } from "antd";-import { deleteAccountsApi } from "@/api/account";-import AvatarPlat from "@/components/AvatarPlat";-import { SocialAccount } from "@/api/types/account.type";-import { useTransClient } from "@/app/i18n/client";+import type { ForwardedRef } from 'react'+import type { SocialAccount } from '@/api/types/account.type'+import { Button, Modal } from 'antd'+import { forwardRef, memo, useState } from 'react'+import { deleteAccountsApi } from '@/api/account'+import styles from '@/app/[lng]/accounts/components/AccountSidebar/AccountSidebar.module.scss'+import { useTransClient } from '@/app/i18n/client'+import AvatarPlat from '@/components/AvatarPlat'export interface IDeleteUserConfirmModalRef {}export interface IDeleteUserConfirmModalProps {- open: boolean;- onClose: () => void;- onDeleteSuccess: () => void;- deleteUsers: SocialAccount[];+ open: boolean+ onClose: () => void+ onDeleteSuccess: () => void+ deleteUsers: SocialAccount[]}const DeleteUserConfirmModal = memo(@@ -26,56 +27,57 @@ const DeleteUserConfirmModal = memo(}: IDeleteUserConfirmModalProps,ref: ForwardedRef<IDeleteUserConfirmModalRef>,) => {- const [deleteLoading, setDeleteLoading] = useState(false);- const { t } = useTransClient("account");+ const [deleteLoading, setDeleteLoading] = useState(false)+ const { t } = useTransClient('account')return (<Modalopen={open}- title={t("deleteConfirm.title" as any)}+ title={t('deleteConfirm.title' as any)}width={500}zIndex={1002}onCancel={() => onClose()}rootClassName={styles.userManageDeleteHitModal}- footer={+ footer={(<>- <Button onClick={() => onClose()}>{t("deleteConfirm.cancel" as any)}</Button>+ <Button onClick={() => onClose()}>{t('deleteConfirm.cancel' as any)}</Button><Buttontype="primary"loading={deleteLoading}onClick={async () => {- setDeleteLoading(true);+ setDeleteLoading(true)const res = await deleteAccountsApi(- deleteUsers.map((v) => v.id),- );- setDeleteLoading(false);- if (!res) return setDeleteLoading(false);- onDeleteSuccess();- onClose();+ deleteUsers.map(v => v.id),+ )+ setDeleteLoading(false)+ if (!res)+ return setDeleteLoading(false)+ onDeleteSuccess()+ onClose()}}>- {t("deleteConfirm.confirm" as any)}+ {t('deleteConfirm.confirm' as any)}</Button></>- }+ )}><p>- {t("deleteConfirm.content" as any, { count: deleteUsers.length } as any)}+ {t('deleteConfirm.content' as any, { count: deleteUsers.length } as any)}</p>- <div className={styles["userManageDeleteHitModal-users"]}>+ <div className={styles['userManageDeleteHitModal-users']}>{deleteUsers.map((v) => {return (<li key={v.id}><AvatarPlat account={v} size="large" /><span>{v.nickname}</span></li>- );+ )})}</div></Modal>- );+ )},),-);+)-export default DeleteUserConfirmModal;+export default DeleteUserConfirmModaldiff --git a/project/web/src/app/[lng]/accounts/components/AccountSidebar/MCPKeyDetailModal.module.scss b/project/web/src/app/[lng]/accounts/components/AccountSidebar/MCPKeyDetailModal.module.scssindex c2126a81..930a5c49 100644--- a/project/web/src/app/[lng]/accounts/components/AccountSidebar/MCPKeyDetailModal.module.scss+++ b/project/web/src/app/[lng]/accounts/components/AccountSidebar/MCPKeyDetailModal.module.scss@@ -74,4 +74,4 @@text-align: center;}}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/accounts/components/AccountSidebar/MCPKeyDetailModal.tsx b/project/web/src/app/[lng]/accounts/components/AccountSidebar/MCPKeyDetailModal.tsxindex a37084d8..902dfe24 100644--- a/project/web/src/app/[lng]/accounts/components/AccountSidebar/MCPKeyDetailModal.tsx+++ b/project/web/src/app/[lng]/accounts/components/AccountSidebar/MCPKeyDetailModal.tsx@@ -1,154 +1,161 @@-import React, { forwardRef, memo, useImperativeHandle, useState, useEffect } from "react";-import { Modal, Button, List, Avatar, Tag, Space, message, Empty, Pagination, Popconfirm } from "antd";-import { CopyOutlined, DeleteOutlined, KeyOutlined, UserOutlined } from "@ant-design/icons";-import { SocialAccount } from "@/api/types/account.type";-import { apiGetMCPRefList, apiDeleteMCPRef } from "@/api/mcp";-import { getAccountListApi } from "@/api/account";-import { AccountPlatInfoMap, PlatType } from "@/app/config/platConfig";-import styles from "./MCPKeyDetailModal.module.scss";-import { useTransClient } from "@/app/i18n/client";+import type { SocialAccount } from '@/api/types/account.type'+import type { PlatType } from '@/app/config/platConfig'+import { CopyOutlined, DeleteOutlined, KeyOutlined, UserOutlined } from '@ant-design/icons'+import { Avatar, Button, Empty, List, message, Modal, Pagination, Popconfirm, Space, Tag } from 'antd'+import React, { forwardRef, memo, useEffect, useImperativeHandle, useState } from 'react'+import { getAccountListApi } from '@/api/account'+import { apiDeleteMCPRef, apiGetMCPRefList } from '@/api/mcp'+import { AccountPlatInfoMap } from '@/app/config/platConfig'+import { useTransClient } from '@/app/i18n/client'+import styles from './MCPKeyDetailModal.module.scss'export interface IMCPKeyDetailModalRef {- open: (keyInfo: any) => void;- close: () => void;+ open: (keyInfo: any) => void+ close: () => void}export interface IMCPKeyDetailModalProps {- open: boolean;- onClose: (open: boolean) => void;- keyInfo?: any;+ open: boolean+ onClose: (open: boolean) => void+ keyInfo?: any}const MCPKeyDetailModal = memo(forwardRef<IMCPKeyDetailModalRef, IMCPKeyDetailModalProps>(({ open, onClose, keyInfo: propKeyInfo }, ref) => {- const { t } = useTransClient("account");- const [keyInfo, setKeyInfo] = useState<any>(null);- const [refList, setRefList] = useState<any[]>([]);- const [loading, setLoading] = useState(false);- const [currentPage, setCurrentPage] = useState(1);- const [pageSize, setPageSize] = useState(10);- const [total, setTotal] = useState(0);- const [accountList, setAccountList] = useState<SocialAccount[]>([]);+ const { t } = useTransClient('account')+ const [keyInfo, setKeyInfo] = useState<any>(null)+ const [refList, setRefList] = useState<any[]>([])+ const [loading, setLoading] = useState(false)+ const [currentPage, setCurrentPage] = useState(1)+ const [pageSize, setPageSize] = useState(10)+ const [total, setTotal] = useState(0)+ const [accountList, setAccountList] = useState<SocialAccount[]>([])// 获取平台信息const getPlatformInfo = (platformType: string) => {- const platInfo = AccountPlatInfoMap.get(platformType as PlatType);+ const platInfo = AccountPlatInfoMap.get(platformType as PlatType)return {- name: platInfo?.name || t("unknownPlatform"),+ name: platInfo?.name || t('unknownPlatform'),icon: platInfo?.icon || '',- themeColor: platInfo?.themeColor || '#999'- };- };+ themeColor: platInfo?.themeColor || '#999',+ }+ }// 获取所有账户列表const fetchAccountList = async () => {try {- const res: any = await getAccountListApi();+ const res: any = await getAccountListApi()if (res?.code === 0) {- setAccountList(res.data || []);+ setAccountList(res.data || [])}- } catch (error) {- console.error('获取账户列表失败:', error);}- };+ catch (error) {+ console.error('获取账户列表失败:', error)+ }+ }// 获取关联账户列表const fetchRefList = async () => {- if (!keyInfo?.key) return;-+ if (!keyInfo?.key)+ return+try {- setLoading(true);- const res: any = await apiGetMCPRefList(currentPage, pageSize, keyInfo.key);+ setLoading(true)+ const res: any = await apiGetMCPRefList(currentPage, pageSize, keyInfo.key)if (res?.code === 0) {- const refListData = res.data.list || [];-+ const refListData = res.data.list || []+// 将账户ID映射到完整的账户信息const enrichedRefList = refListData.map((refItem: any) => {- const accountInfo = accountList.find(account => account.id === refItem);+ const accountInfo = accountList.find(account => account.id === refItem)return {...refItem,- account: accountInfo || null- };- });-- setRefList(enrichedRefList);- setTotal(res.data.total || 0);+ account: accountInfo || null,+ }+ })++ setRefList(enrichedRefList)+ setTotal(res.data.total || 0)}- } catch (error) {- message.error('获取关联账户列表失败');- } finally {- setLoading(false);}- };+ catch (error) {+ message.error('获取关联账户列表失败')+ }+ finally {+ setLoading(false)+ }+ }useEffect(() => {if (open) {- fetchAccountList();+ fetchAccountList()}- }, [open]);+ }, [open])useEffect(() => {if (open && keyInfo && accountList.length > 0) {- fetchRefList();+ fetchRefList()}- }, [open, keyInfo, currentPage, pageSize, accountList]);+ }, [open, keyInfo, currentPage, pageSize, accountList])const handleCopyKey = (key: string) => {- navigator.clipboard.writeText(key);- message.success('Key已复制到剪贴板');- };+ navigator.clipboard.writeText(key)+ message.success('Key已复制到剪贴板')+ }const handleUnlinkAccount = async (accountId: string) => {- console.log(accountId);+ console.log(accountId)try {const res = await apiDeleteMCPRef({key: keyInfo.key,- accountId: accountId- });+ accountId,+ })if (res?.code === 0) {- message.success('解除关联成功');- fetchRefList(); // 刷新列表- } else {- message.error('解除关联失败');+ message.success('解除关联成功')+ fetchRefList() // 刷新列表+ }+ else {+ message.error('解除关联失败')}- } catch (error) {- message.error('解除关联失败');}- };+ catch (error) {+ message.error('解除关联失败')+ }+ }// 当props中的keyInfo变化时,更新内部状态useEffect(() => {if (propKeyInfo) {- setKeyInfo(propKeyInfo);- setCurrentPage(1);- setRefList([]);- setTotal(0);+ setKeyInfo(propKeyInfo)+ setCurrentPage(1)+ setRefList([])+ setTotal(0)}- }, [propKeyInfo]);+ }, [propKeyInfo])useImperativeHandle(ref, () => ({open: (keyInfo: any) => {- setKeyInfo(keyInfo);- setCurrentPage(1);- setRefList([]);- setTotal(0);+ setKeyInfo(keyInfo)+ setCurrentPage(1)+ setRefList([])+ setTotal(0)},close: () => {- setKeyInfo(null);- setRefList([]);- setTotal(0);+ setKeyInfo(null)+ setRefList([])+ setTotal(0)},- }));+ }))return (<Modal- title={+ title={(<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><KeyOutlined style={{ color: '#625BF2' }} />MCP Key 详情</div>- }+ )}open={open}onCancel={() => onClose(false)}footer={null}@@ -168,8 +175,8 @@ const MCPKeyDetailModal = memo(<Tag color={keyInfo.status === 1 ? 'green' : 'red'}>{keyInfo.status === 1 ? '可用' : '不可用'}</Tag>- <Button- type="link"+ <Button+ type="link"icon={<CopyOutlined />}onClick={() => handleCopyKey(keyInfo.key)}>@@ -177,12 +184,12 @@ const MCPKeyDetailModal = memo(</Button></Space></div>-+<div className={styles.keyValue}><span className={styles.label}>Key值:</span><span className={styles.value}>{keyInfo.key}</span></div>-+<div className={styles.keyMeta}><div className={styles.metaItem}><span className={styles.label}>创建时间:</span>@@ -190,7 +197,11 @@ const MCPKeyDetailModal = memo(</div><div className={styles.metaItem}><span className={styles.label}>关联账户:</span>- <span>{total} 个</span>+ <span>+ {total}+ {' '}+ 个+ </span></div></div></div>@@ -201,95 +212,97 @@ const MCPKeyDetailModal = memo(<UserOutlined />关联账户列表</div>-- {refList.length === 0 && !loading ? (- <div className={styles.emptyState}>- <Empty description="暂无关联账户" />- </div>- ) : (- <>- <List- className={styles.refList}- dataSource={refList}- loading={loading}- renderItem={(item) => {- const platformInfo = getPlatformInfo(item.account?.type);- return (- <List.Item- actions={[- <Popconfirm- title="确定要解除关联吗?"- onConfirm={() => handleUnlinkAccount(item.account.id)}- okText="确定"- cancelText="取消"++ {refList.length === 0 && !loading+ ? (+ <div className={styles.emptyState}>+ <Empty description="暂无关联账户" />+ </div>+ )+ : (+ <>+ <List+ className={styles.refList}+ dataSource={refList}+ loading={loading}+ renderItem={(item) => {+ const platformInfo = getPlatformInfo(item.account?.type)+ return (+ <List.Item+ actions={[+ <Popconfirm+ title="确定要解除关联吗?"+ onConfirm={() => handleUnlinkAccount(item.account.id)}+ okText="确定"+ cancelText="取消"+ >+ <Button+ key="unlink"+ type="link"+ danger+ icon={<DeleteOutlined />}+ >+ 解除关联+ </Button>+ </Popconfirm>,+ ]}>- <Button- key="unlink"- type="link"- danger- icon={<DeleteOutlined />}- >- 解除关联- </Button>- </Popconfirm>- ]}- >- <List.Item.Meta- avatar={<Avatar src={item.account?.avatar} />}- title={item.account?.nickname || t("unknownAccount")}- description={- <div>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- {platformInfo.icon && (- <img- src={platformInfo.icon}- alt={platformInfo.name}- style={{- width: '16px',- height: '16px',- borderRadius: '2px'- }}- />- )}- <span style={{ color: platformInfo.themeColor }}>- {platformInfo.name}- </span>- </div>- </div>- }- />- </List.Item>- );- }}- />-- {total > 0 && (- <div style={{ marginTop: 16, textAlign: 'right' }}>- <Pagination- current={currentPage}- pageSize={pageSize}- total={total}- showSizeChanger- showQuickJumper- showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条,共 ${total} 条`}- onChange={(page, size) => {- setCurrentPage(page);- setPageSize(size);+ <List.Item.Meta+ avatar={<Avatar src={item.account?.avatar} />}+ title={item.account?.nickname || t('unknownAccount')}+ description={(+ <div>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ {platformInfo.icon && (+ <img+ src={platformInfo.icon}+ alt={platformInfo.name}+ style={{+ width: '16px',+ height: '16px',+ borderRadius: '2px',+ }}+ />+ )}+ <span style={{ color: platformInfo.themeColor }}>+ {platformInfo.name}+ </span>+ </div>+ </div>+ )}+ />+ </List.Item>+ )}}/>- </div>++ {total > 0 && (+ <div style={{ marginTop: 16, textAlign: 'right' }}>+ <Pagination+ current={currentPage}+ pageSize={pageSize}+ total={total}+ showSizeChanger+ showQuickJumper+ showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条,共 ${total} 条`}+ onChange={(page, size) => {+ setCurrentPage(page)+ setPageSize(size)+ }}+ />+ </div>+ )}+ </>)}- </>- )}</div></>)}</Modal>- );- }- )-);+ )+ },+ ),+)-MCPKeyDetailModal.displayName = "MCPKeyDetailModal";+MCPKeyDetailModal.displayName = 'MCPKeyDetailModal'-export default MCPKeyDetailModal;\ No newline at end of file+export default MCPKeyDetailModaldiff --git a/project/web/src/app/[lng]/accounts/components/AccountSidebar/MCPManagerModal.module.scss b/project/web/src/app/[lng]/accounts/components/AccountSidebar/MCPManagerModal.module.scssindex 2b3aef25..21251e6b 100644--- a/project/web/src/app/[lng]/accounts/components/AccountSidebar/MCPManagerModal.module.scss+++ b/project/web/src/app/[lng]/accounts/components/AccountSidebar/MCPManagerModal.module.scss@@ -7,14 +7,14 @@transition: all 0.3s ease;&:hover {- border-color: #625BF2;+ border-color: #625bf2;box-shadow: 0 2px 8px rgba(98, 91, 242, 0.1);}.ant-list-item-meta {.ant-list-item-meta-avatar {.ant-avatar {- background: linear-gradient(90deg, #625BF2 0%, #925BF2 100%);+ background: linear-gradient(90deg, #625bf2 0%, #925bf2 100%);}}@@ -58,15 +58,15 @@.ant-list-item-actions {.ant-btn-link {- color: #625BF2;-+ color: #625bf2;+&:hover {- color: #925BF2;+ color: #925bf2;}&.ant-btn-dangerous {color: #ff4d4f;-+&:hover {color: #ff7875;}@@ -77,12 +77,12 @@}.createButton {- background: linear-gradient(90deg, #625BF2 0%, #925BF2 100%);+ background: linear-gradient(90deg, #625bf2 0%, #925bf2 100%);border: none;border-radius: 6px;height: 40px;font-weight: 500;-+&:hover {background: linear-gradient(90deg, #5a54e8 0%, #8a54e8 100%);transform: translateY(-1px);@@ -111,4 +111,4 @@color: #ccc;}}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/accounts/components/AccountSidebar/MCPManagerModal.tsx b/project/web/src/app/[lng]/accounts/components/AccountSidebar/MCPManagerModal.tsxindex ae093d2b..c2337185 100644--- a/project/web/src/app/[lng]/accounts/components/AccountSidebar/MCPManagerModal.tsx+++ b/project/web/src/app/[lng]/accounts/components/AccountSidebar/MCPManagerModal.tsx@@ -1,147 +1,154 @@-import React, { forwardRef, memo, useImperativeHandle, useRef, useState, useEffect } from "react";-import { Modal, Button, List, Avatar, Tag, Space, message, Empty, Input, Form, Pagination } from "antd";-import { PlusOutlined, CopyOutlined, DeleteOutlined, KeyOutlined, EditOutlined } from "@ant-design/icons";-import ChooseAccountModule from "@/components/ChooseAccountModule/ChooseAccountModule";-import { SocialAccount } from "@/api/types/account.type";-import {- apiCreateMCPKey,- apiDeleteMCPKey,- apiGetMCPKeyList,- apiCreateMCPRef,-} from "@/api/mcp";-import MCPKeyDetailModal from "./MCPKeyDetailModal";-import styles from "./MCPManagerModal.module.scss";-import dayjs from "dayjs";+import type { SocialAccount } from '@/api/types/account.type'+import { CopyOutlined, DeleteOutlined, EditOutlined, KeyOutlined, PlusOutlined } from '@ant-design/icons'+import { Avatar, Button, Empty, Form, Input, List, message, Modal, Pagination, Space, Tag } from 'antd'+import dayjs from 'dayjs'+import React, { forwardRef, memo, useEffect, useImperativeHandle, useRef, useState } from 'react'+import {+ apiCreateMCPKey,+ apiCreateMCPRef,+ apiDeleteMCPKey,+ apiGetMCPKeyList,+} from '@/api/mcp'+import ChooseAccountModule from '@/components/ChooseAccountModule/ChooseAccountModule'+import MCPKeyDetailModal from './MCPKeyDetailModal'+import styles from './MCPManagerModal.module.scss'export interface IMCPManagerModalRef {- open: () => void;- close: () => void;+ open: () => void+ close: () => void}export interface IMCPManagerModalProps {- open: boolean;- onClose: (open: boolean) => void;+ open: boolean+ onClose: (open: boolean) => void}const MCPManagerModal = memo(forwardRef<IMCPManagerModalRef, IMCPManagerModalProps>(({ open, onClose }, ref) => {- const [mcpKeys, setMcpKeys] = useState<any[]>([]);- const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);- const [selectedAccounts, setSelectedAccounts] = useState<SocialAccount[]>([]);- const [newKeyName, setNewKeyName] = useState('');- const [loading, setLoading] = useState(false);- const [currentPage, setCurrentPage] = useState(1);- const [pageSize, setPageSize] = useState(10);- const [total, setTotal] = useState(0);- const [createForm] = Form.useForm();- const [showAccountSelector, setShowAccountSelector] = useState(false);- const [showDetailModal, setShowDetailModal] = useState(false);- const [selectedKeyInfo, setSelectedKeyInfo] = useState<any>(null);+ const [mcpKeys, setMcpKeys] = useState<any[]>([])+ const [isCreateModalOpen, setIsCreateModalOpen] = useState(false)+ const [selectedAccounts, setSelectedAccounts] = useState<SocialAccount[]>([])+ const [newKeyName, setNewKeyName] = useState('')+ const [loading, setLoading] = useState(false)+ const [currentPage, setCurrentPage] = useState(1)+ const [pageSize, setPageSize] = useState(10)+ const [total, setTotal] = useState(0)+ const [createForm] = Form.useForm()+ const [showAccountSelector, setShowAccountSelector] = useState(false)+ const [showDetailModal, setShowDetailModal] = useState(false)+ const [selectedKeyInfo, setSelectedKeyInfo] = useState<any>(null)// 获取MCP Key列表const fetchMCPKeys = async () => {try {- setLoading(true);- const res:any = await apiGetMCPKeyList(currentPage, pageSize);+ setLoading(true)+ const res: any = await apiGetMCPKeyList(currentPage, pageSize)if (res?.code === 0) {- setMcpKeys(res.data.list || []);- setTotal(res.data.total || 0);+ setMcpKeys(res.data.list || [])+ setTotal(res.data.total || 0)}- } catch (error) {- message.error('获取MCP Key列表失败');- } finally {- setLoading(false);}- };+ catch (error) {+ message.error('获取MCP Key列表失败')+ }+ finally {+ setLoading(false)+ }+ }// 初始化数据useEffect(() => {if (open) {- fetchMCPKeys();+ fetchMCPKeys()}- }, [open, currentPage, pageSize]);+ }, [open, currentPage, pageSize])const handleCreateKey = () => {- setIsCreateModalOpen(true);- };+ setIsCreateModalOpen(true)+ }const handleAccountConfirm = async (accounts: SocialAccount[]) => {try {- setLoading(true);-+ setLoading(true)+// 创建MCP Keyconst createParams: any = {desc: newKeyName,- accounts: accounts.map(account => account.id)- };-- const createRes = await apiCreateMCPKey(createParams);+ accounts: accounts.map(account => account.id),+ }++ const createRes = await apiCreateMCPKey(createParams)if (createRes?.code !== 0) {- message.error('创建MCP Key失败');- return;+ message.error('创建MCP Key失败')+ return}// 创建关联(如果选择了多个账户,需要多次请求)- const createdKey = (createRes.data as any)?.key;+ const createdKey = (createRes.data as any)?.keyif (createdKey) {for (const account of accounts) {try {await apiCreateMCPRef({key: createdKey,- accountId: account.id- });- } catch (error) {- console.error(`创建关联失败: ${account.account}`, error);+ accountId: account.id,+ })+ }+ catch (error) {+ console.error(`创建关联失败: ${account.account}`, error)}}}- setSelectedAccounts([]);- setIsCreateModalOpen(false);- setNewKeyName('');- message.success('MCP Key创建成功!');- fetchMCPKeys(); // 刷新列表- } catch (error) {- message.error('创建MCP Key失败');- } finally {- setLoading(false);+ setSelectedAccounts([])+ setIsCreateModalOpen(false)+ setNewKeyName('')+ message.success('MCP Key创建成功!')+ fetchMCPKeys() // 刷新列表+ }+ catch (error) {+ message.error('创建MCP Key失败')+ }+ finally {+ setLoading(false)}- };+ }const handleCopyKey = (key: string) => {- navigator.clipboard.writeText(key);- message.success('Key已复制到剪贴板');- };+ navigator.clipboard.writeText(key)+ message.success('Key已复制到剪贴板')+ }const handleDeleteKey = async (key: string) => {try {- const res = await apiDeleteMCPKey(key);+ const res = await apiDeleteMCPKey(key)if (res?.code === 0) {- message.success('MCP Key已删除');- fetchMCPKeys(); // 刷新列表- } else {- message.error('删除MCP Key失败');+ message.success('MCP Key已删除')+ fetchMCPKeys() // 刷新列表}- } catch (error) {- message.error('删除MCP Key失败');+ else {+ message.error('删除MCP Key失败')+ }+ }+ catch (error) {+ message.error('删除MCP Key失败')}- };+ }useImperativeHandle(ref, () => ({open: () => onClose(true),close: () => onClose(false),- }));+ }))return (<><Modal- title={+ title={(<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><KeyOutlined style={{ color: '#625BF2' }} />MCP 管理器</div>- }+ )}open={open}onCancel={() => onClose(false)}footer={null}@@ -149,8 +156,8 @@ const MCPManagerModal = memo(className={styles.mcpManagerModal}><div style={{ marginBottom: 16 }}>- <Button- type="primary"+ <Button+ type="primary"icon={<PlusOutlined />}onClick={handleCreateKey}className={styles.createButton}@@ -160,114 +167,124 @@ const MCPManagerModal = memo(</Button></div>- {mcpKeys.length === 0 && !loading ? (- <div className={styles.emptyState}>- <div className="emptyIcon">- <KeyOutlined />- </div>- <div className="emptyText">暂无MCP Key</div>- <div className="emptyDesc">点击上方按钮创建您的第一个MCP Key</div>- </div>- ) : (- <>- <List+ {mcpKeys.length === 0 && !loading+ ? (+ <div className={styles.emptyState}>+ <div className="emptyIcon">+ <KeyOutlined />+ </div>+ <div className="emptyText">暂无MCP Key</div>+ <div className="emptyDesc">点击上方按钮创建您的第一个MCP Key</div>+ </div>+ )+ : (+ <>+ <ListclassName={styles.mcpKeyList}dataSource={mcpKeys}loading={loading}- renderItem={(item) => (+ renderItem={item => (<List.Itemactions={[- <Button- key="copy"- type="link"+ <Button+ key="copy"+ type="link"icon={<CopyOutlined />}onClick={() => handleCopyKey(item.key)}>复制</Button>,- <Button- key="detail"- type="link"+ <Button+ key="detail"+ type="link"icon={<KeyOutlined />}onClick={() => {- setSelectedKeyInfo(item);- setShowDetailModal(true);+ setSelectedKeyInfo(item)+ setShowDetailModal(true)}}>详情</Button>,- <Button- key="delete"- type="link"+ <Button+ key="delete"+ type="link"dangericon={<DeleteOutlined />}onClick={() => handleDeleteKey(item.key)}loading={loading}>删除- </Button>+ </Button>,]}>- <List.Item.Meta- avatar={<Avatar style={{ background: 'linear-gradient(90deg, #625BF2 0%, #925BF2 100%)' }}>MCP</Avatar>}- title={- <Space>- <span>{item.desc}</span>- <Tag color={item.status === 1 ? 'green' : 'red'}>- {item.status === 1 ? '可用' : '不可用'}- </Tag>- </Space>- }- description={- <div>- <div className="keyDisplay">- {item.key}- </div>- <div className="keyInfo">- <div className="infoItem">- <span className="label">创建时间: </span>- <span> {dayjs(item.createdAt).format('YYYY-MM-DD HH:mm:ss')}</span>+ <List.Item.Meta+ avatar={<Avatar style={{ background: 'linear-gradient(90deg, #625BF2 0%, #925BF2 100%)' }}>MCP</Avatar>}+ title={(+ <Space>+ <span>{item.desc}</span>+ <Tag color={item.status === 1 ? 'green' : 'red'}>+ {item.status === 1 ? '可用' : '不可用'}+ </Tag>+ </Space>+ )}+ description={(+ <div>+ <div className="keyDisplay">+ {item.key}+ </div>+ <div className="keyInfo">+ <div className="infoItem">+ <span className="label">创建时间: </span>+ <span>+ {' '}+ {dayjs(item.createdAt).format('YYYY-MM-DD HH:mm:ss')}+ </span>+ </div>+ <div className="infoItem">+ <span className="label">关联账户: </span>+ <span>+ {' '}+ {item.accountNum}+ {' '}+ 个+ </span>+ </div>+ </div></div>- <div className="infoItem">- <span className="label">关联账户: </span>- <span> {item.accountNum} 个</span>- </div>- </div>- </div>- }- />- </List.Item>- )}- />-- {total > 0 && (- <div style={{ marginTop: 16, textAlign: 'right' }}>- <Pagination- current={currentPage}- pageSize={pageSize}- total={total}- showSizeChanger- showQuickJumper- showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条,共 ${total} 条`}- onChange={(page, size) => {- setCurrentPage(page);- setPageSize(size);- }}+ )}+ />+ </List.Item>+ )}/>- </div>++ {total > 0 && (+ <div style={{ marginTop: 16, textAlign: 'right' }}>+ <Pagination+ current={currentPage}+ pageSize={pageSize}+ total={total}+ showSizeChanger+ showQuickJumper+ showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条,共 ${total} 条`}+ onChange={(page, size) => {+ setCurrentPage(page)+ setPageSize(size)+ }}+ />+ </div>+ )}+ </>)}- </>- )}</Modal><Modaltitle="创建MCP Key"open={isCreateModalOpen}onCancel={() => {- setIsCreateModalOpen(false);- setSelectedAccounts([]);- setNewKeyName('');- createForm.resetFields();+ setIsCreateModalOpen(false)+ setSelectedAccounts([])+ setNewKeyName('')+ createForm.resetFields()}}footer={null}width={600}@@ -277,10 +294,10 @@ const MCPManagerModal = memo(layout="vertical"onFinish={(values) => {if (selectedAccounts.length === 0) {- message.warning('请选择至少一个账户');- return;+ message.warning('请选择至少一个账户')+ return}- handleAccountConfirm(selectedAccounts);+ handleAccountConfirm(selectedAccounts)}}><Form.Item@@ -291,30 +308,37 @@ const MCPManagerModal = memo(<Inputplaceholder="请输入Key名称"value={newKeyName}- onChange={(e) => setNewKeyName(e.target.value)}+ onChange={e => setNewKeyName(e.target.value)}/></Form.Item>-+<Form.Item label="选择账户"><div style={{ minHeight: 100, border: '1px dashed #d9d9d9', padding: 16, borderRadius: 6 }}>- {selectedAccounts.length === 0 ? (- <div style={{ textAlign: 'center', color: '#999' }}>- 请选择要关联的账户- </div>- ) : (- <div>- <div style={{ marginBottom: 8, fontWeight: 500 }}>已选择 {selectedAccounts.length} 个账户:</div>- {selectedAccounts.map(account => (- <Tag key={account.id} style={{ marginBottom: 4 }}>- {account.nickname}- </Tag>- ))}- </div>- )}- <Button- type="dashed"+ {selectedAccounts.length === 0+ ? (+ <div style={{ textAlign: 'center', color: '#999' }}>+ 请选择要关联的账户+ </div>+ )+ : (+ <div>+ <div style={{ marginBottom: 8, fontWeight: 500 }}>+ 已选择+ {selectedAccounts.length}+ {' '}+ 个账户:+ </div>+ {selectedAccounts.map(account => (+ <Tag key={account.id} style={{ marginBottom: 4 }}>+ {account.nickname}+ </Tag>+ ))}+ </div>+ )}+ <Button+ type="dashed"onClick={() => {- setShowAccountSelector(true);+ setShowAccountSelector(true)}}style={{ marginTop: 8 }}>@@ -322,22 +346,22 @@ const MCPManagerModal = memo(</Button></div></Form.Item>-+<Form.Item><Space>- <Button- type="primary"+ <Button+ type="primary"htmlType="submit"loading={loading}>创建</Button>- <Button+ <ButtononClick={() => {- setIsCreateModalOpen(false);- setSelectedAccounts([]);- setNewKeyName('');- createForm.resetFields();+ setIsCreateModalOpen(false)+ setSelectedAccounts([])+ setNewKeyName('')+ createForm.resetFields()}}>取消@@ -351,8 +375,8 @@ const MCPManagerModal = memo(open={showAccountSelector}onClose={() => setShowAccountSelector(false)}onAccountConfirm={(accounts) => {- setSelectedAccounts(accounts);- setShowAccountSelector(false);+ setSelectedAccounts(accounts)+ setShowAccountSelector(false)}}simpleAccountChooseProps={{choosedAccounts: selectedAccounts,@@ -360,23 +384,23 @@ const MCPManagerModal = memo(isCancelChooseAccount: true,}}/>-+<MCPKeyDetailModalopen={showDetailModal}onClose={(open) => {- setShowDetailModal(open);+ setShowDetailModal(open)if (!open) {- setSelectedKeyInfo(null);+ setSelectedKeyInfo(null)}}}keyInfo={selectedKeyInfo}/></>- );- }- )-);+ )+ },+ ),+)-MCPManagerModal.displayName = "MCPManagerModal";+MCPManagerModal.displayName = 'MCPManagerModal'-export default MCPManagerModal;\ No newline at end of file+export default MCPManagerModaldiff --git a/project/web/src/app/[lng]/accounts/components/AccountSidebar/UserManageModal.tsx b/project/web/src/app/[lng]/accounts/components/AccountSidebar/UserManageModal.tsxindex 21b1c2a4..7753b7f7 100644--- a/project/web/src/app/[lng]/accounts/components/AccountSidebar/UserManageModal.tsx+++ b/project/web/src/app/[lng]/accounts/components/AccountSidebar/UserManageModal.tsx@@ -1,124 +1,132 @@-import {+import type {+ TableProps,+} from 'antd'+import type {ForwardedRef,- forwardRef,- memo,- useImperativeHandle,- useMemo,- useRef,- useState,- useEffect,-} from "react";+} from 'react'+import type { SocialAccount } from '@/api/types/account.type'+import type { IpLocationInfo } from '@/utils/ipLocation'+import {+ CheckCircleOutlined,+ DeleteOutlined,+ EnvironmentOutlined,+ GlobalOutlined,+ WarningOutlined,+} from '@ant-design/icons'import {Button,+ Card,Drawer,message,Modal,Select,+ Space,Spin,Table,- TableProps,Tooltip,- Card,- Space,-} from "antd";-import styles from "./AccountSidebar.module.scss";-import { useAccountStore } from "@/store/account";-import { useShallow } from "zustand/react/shallow";+} from 'antd'import {- CheckCircleOutlined,- DeleteOutlined,- WarningOutlined,- GlobalOutlined,- EnvironmentOutlined,-} from "@ant-design/icons";-import UserManageSidebar from "./UserManageSidebar";-import { SocialAccount } from "@/api/types/account.type";-import { AccountPlatInfoMap } from "@/app/config/platConfig";-import { AccountStatus } from "@/app/config/accountConfig";-import AvatarPlat from "@/components/AvatarPlat";-import { deleteAccountsApi, updateAccountApi } from "@/api/account";-import { useTransClient } from "@/app/i18n/client";-import AddAccountModal from "../AddAccountModal";-import { getIpLocation, IpLocationInfo, formatLocationInfo, extractCountry } from "@/utils/ipLocation";-import DeleteUserConfirmModal from "@/app/[lng]/accounts/components/AccountSidebar/DeleteUserConfirmModal";+ forwardRef,+ memo,+ useEffect,+ useImperativeHandle,+ useMemo,+ useRef,+ useState,+} from 'react'+import { useShallow } from 'zustand/react/shallow'+import { deleteAccountsApi, updateAccountApi } from '@/api/account'+import DeleteUserConfirmModal from '@/app/[lng]/accounts/components/AccountSidebar/DeleteUserConfirmModal'+import { AccountStatus } from '@/app/config/accountConfig'+import { AccountPlatInfoMap } from '@/app/config/platConfig'+import { useTransClient } from '@/app/i18n/client'+import AvatarPlat from '@/components/AvatarPlat'+import { useAccountStore } from '@/store/account'+import { extractCountry, formatLocationInfo, getIpLocation } from '@/utils/ipLocation'+import AddAccountModal from '../AddAccountModal'+import styles from './AccountSidebar.module.scss'+import UserManageSidebar from './UserManageSidebar'export interface IUserManageModalRef {- setActiveGroup: (groupId: string) => void;+ setActiveGroup: (groupId: string) => void}export interface IUserManageModalProps {- open: boolean;- onCancel: () => void;+ open: boolean+ onCancel: () => void}-const UserGroupSelect = ({+function UserGroupSelect({account,onChange,}: {- account: SocialAccount;- onChange: (groupId: string) => void;-}) => {+ account: SocialAccount+ onChange: (groupId: string) => void+}) {const { accountGroupList } = useAccountStore(- useShallow((state) => ({+ useShallow(state => ({accountGroupList: state.accountGroupList,})),- );+ )return (<Select// @ts-ignorevalue={account.groupId}- style={{ width: "160px" }}+ style={{ width: '160px' }}fieldNames={{- value: "id",- label: "name",+ value: 'id',+ label: 'name',}}options={accountGroupList}onChange={onChange}/>- );-};+ )+}// 空间信息展示组件-const SpaceInfoCard = ({+function SpaceInfoCard({activeGroup,accountGroupList,- allUser+ allUser,}: {- activeGroup: string;- accountGroupList: any[];- allUser: string;-}) => {- const { t } = useTransClient("account");- const [ipLocationInfo, setIpLocationInfo] = useState<IpLocationInfo | null>(null);- const [ipLocationLoading, setIpLocationLoading] = useState(false);+ activeGroup: string+ accountGroupList: any[]+ allUser: string+}) {+ const { t } = useTransClient('account')+ const [ipLocationInfo, setIpLocationInfo] = useState<IpLocationInfo | null>(null)+ const [ipLocationLoading, setIpLocationLoading] = useState(false)// 获取IP地理位置信息useEffect(() => {const fetchIpLocation = async () => {try {- setIpLocationLoading(true);- const info = await getIpLocation();- setIpLocationInfo(info);- } catch (error) {- console.error('获取IP地理位置信息失败:', error);- } finally {- setIpLocationLoading(false);+ setIpLocationLoading(true)+ const info = await getIpLocation()+ setIpLocationInfo(info)+ }+ catch (error) {+ console.error('获取IP地理位置信息失败:', error)}- };+ finally {+ setIpLocationLoading(false)+ }+ }// 只在组件挂载时获取一次IP信息- fetchIpLocation();- }, []);+ fetchIpLocation()+ }, [])// 如果是全部账号,不显示信息卡片if (activeGroup === allUser) {- return null;+ return null}// 获取当前选中的空间信息- const currentSpace = accountGroupList.find(group => group.id === activeGroup);- if (!currentSpace) return null;+ const currentSpace = accountGroupList.find(group => group.id === activeGroup)+ if (!currentSpace)+ return nullreturn (<Card@@ -126,7 +134,7 @@ const SpaceInfoCard = ({style={{marginBottom: '16px',backgroundColor: 'var(--grayColor1)',- border: '1px solid var(--grayColor3)'+ border: '1px solid var(--grayColor3)',}}><Space direction="vertical" size="small" style={{ width: '100%' }}>@@ -143,7 +151,7 @@ const SpaceInfoCard = ({</div> */}{/* 根据proxyIp判断显示IP和属地信息 */}- {(!currentSpace.proxyIp || currentSpace.proxyIp === "") ? (+ {(!currentSpace.proxyIp || currentSpace.proxyIp === '') ? (// 本地IP显示<div style={{display: 'flex',@@ -151,56 +159,67 @@ const SpaceInfoCard = ({gap: '8px',padding: '8px',backgroundColor: 'var(--grayColor2)',- borderRadius: '6px'- }}>+ borderRadius: '6px',+ }}+ ><GlobalOutlined style={{ color: 'var(--colorPrimary5)' }} /><span style={{ fontSize: 'var(--fs-xs)', color: 'var(--grayColor7)' }}>- {t("ipInfo.loading")}+ {t('ipInfo.loading')}</span>- {ipLocationLoading ? (- <span style={{ color: 'var(--colorPrimary5)', fontStyle: 'italic' }}>- {t("ipInfo.loading")}- </span>- ) : ipLocationInfo ? (- <Tooltip title={t("ipInfo.tooltip", { asn: ipLocationInfo.asn, org: ipLocationInfo.org })}>- <span style={{- color: 'var(--grayColor7)',- cursor: 'help',- fontWeight: '500'- }}>- {formatLocationInfo(ipLocationInfo)}- </span>- </Tooltip>- ) : (- <span style={{ color: 'var(--errorColor)', fontStyle: 'italic' }}>- {t("ipInfo.error")}- </span>- )}+ {ipLocationLoading+ ? (+ <span style={{ color: 'var(--colorPrimary5)', fontStyle: 'italic' }}>+ {t('ipInfo.loading')}+ </span>+ )+ : ipLocationInfo+ ? (+ <Tooltip title={t('ipInfo.tooltip', { asn: ipLocationInfo.asn, org: ipLocationInfo.org })}>+ <span style={{+ color: 'var(--grayColor7)',+ cursor: 'help',+ fontWeight: '500',+ }}+ >+ {formatLocationInfo(ipLocationInfo)}+ </span>+ </Tooltip>+ )+ : (+ <span style={{ color: 'var(--errorColor)', fontStyle: 'italic' }}>+ {t('ipInfo.error')}+ </span>+ )}</div>- ) : (- // 数据中的IP显示- currentSpace.ip && currentSpace.location && (- <div style={{- display: 'flex',- alignItems: 'center',- gap: '8px',- padding: '8px',- backgroundColor: 'var(--grayColor2)',- borderRadius: '6px'- }}>- <GlobalOutlined style={{ color: 'var(--colorPrimary5)' }} />- <Tooltip title={`IP: ${currentSpace.ip}\n位置: ${currentSpace.location}`}>- <span style={{- color: 'var(--grayColor7)',- cursor: 'help',- fontWeight: '500'- }}>- {extractCountry(currentSpace.location)} | {currentSpace.ip}- </span>- </Tooltip>- </div>- )- )}+ )+ : (+ currentSpace.ip && currentSpace.location && (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ padding: '8px',+ backgroundColor: 'var(--grayColor2)',+ borderRadius: '6px',+ }}+ >+ <GlobalOutlined style={{ color: 'var(--colorPrimary5)' }} />+ <Tooltip title={`IP: ${currentSpace.ip}\n位置: ${currentSpace.location}`}>+ <span style={{+ color: 'var(--grayColor7)',+ cursor: 'help',+ fontWeight: '500',+ }}+ >+ {extractCountry(currentSpace.location)}+ {' '}+ |+ {currentSpace.ip}+ </span>+ </Tooltip>+ </div>+ )+ )}{/* 空间创建时间等信息 */}<div style={{@@ -208,26 +227,31 @@ const SpaceInfoCard = ({color: 'var(--grayColor6)',display: 'flex',alignItems: 'center',- gap: '4px'- }}>+ gap: '4px',+ }}+ ><EnvironmentOutlined />- <span>空间ID: {currentSpace.id}</span>+ <span>+ 空间ID:+ {currentSpace.id}+ </span>{currentSpace.isDefault && (<span style={{color: 'var(--colorPrimary5)',backgroundColor: 'var(--colorPrimary1)',padding: '1px 6px',borderRadius: '10px',- fontSize: 'var(--fs-xs)'- }}>+ fontSize: 'var(--fs-xs)',+ }}+ >defaultSpace</span>)}</div></Space></Card>- );-};+ )+}const UserManageModal = memo(forwardRef(@@ -235,39 +259,39 @@ const UserManageModal = memo({ open, onCancel }: IUserManageModalProps,ref: ForwardedRef<IUserManageModalRef>,) => {- const { t } = useTransClient("account");- const { accountList, getAccountList, accountGroupList, accountMap } =- useAccountStore(- useShallow((state) => ({+ const { t } = useTransClient('account')+ const { accountList, getAccountList, accountGroupList, accountMap }+ = useAccountStore(+ useShallow(state => ({accountList: state.accountList,getAccountList: state.getAccountList,accountGroupList: state.accountGroupList,accountMap: state.accountMap,})),- );- const [deleteHitOpen, setDeleteHitOpen] = useState(false);- const [selectedRows, setSelectedRows] = useState<SocialAccount[]>([]);+ )+ const [deleteHitOpen, setDeleteHitOpen] = useState(false)+ const [selectedRows, setSelectedRows] = useState<SocialAccount[]>([])// 全部账号- const allUser = useRef("-1");+ const allUser = useRef('-1')// -1=全部账号,不然为对应分组 ID- const [activeGroup, setActiveGroup] = useState(allUser.current);+ const [activeGroup, setActiveGroup] = useState(allUser.current)// 是否改变了顺序- const isUpdateRank = useRef(false);- const [deleteLoading, setDeleteLoading] = useState(false);- const [cutLoading, setCutLoading] = useState(false);- const [isAddAccountOpen, setIsAddAccountOpen] = useState(false);- const [targetGroupIdForModal, setTargetGroupIdForModal] = useState<string | undefined>(undefined);+ const isUpdateRank = useRef(false)+ const [deleteLoading, setDeleteLoading] = useState(false)+ const [cutLoading, setCutLoading] = useState(false)+ const [isAddAccountOpen, setIsAddAccountOpen] = useState(false)+ const [targetGroupIdForModal, setTargetGroupIdForModal] = useState<string | undefined>(undefined)const columns = useMemo(() => {- const columns: TableProps<SocialAccount>["columns"] = [+ const columns: TableProps<SocialAccount>['columns'] = [{- title: t("userManageModal.account"),+ title: t('userManageModal.account'),render: (text, am) => {return (<div- className={`userManage-content-user ${am.status === AccountStatus.DISABLE ? "userManage-content-user--disable" : ""}`}+ className={`userManage-content-user ${am.status === AccountStatus.DISABLE ? 'userManage-content-user--disable' : ''}`}>- {/*<Avatar src={am.avatar} />*/}+ {/* <Avatar src={am.avatar} /> */}<AvatarPlat account={am} size="large" /><spanclassName="userManage-content-user-name"@@ -276,112 +300,117 @@ const UserManageModal = memo({am.nickname}</span></div>- );+ )},width: 200,- key: "nickname",+ key: 'nickname',},{- title: t("userManageModal.platform"),+ title: t('userManageModal.platform'),render: (text, am) => {- const platInfo = AccountPlatInfoMap.get(am.type)!;+ const platInfo = AccountPlatInfoMap.get(am.type)!return (<div className="userManage-content-plat"><Tooltip title={platInfo?.name}>- <img src={platInfo?.icon} style={{- width: "20px",- height: "20px",- }} />+ <img+ src={platInfo?.icon}+ style={{+ width: '20px',+ height: '20px',+ }}+ /></Tooltip></div>- );+ )},width: 80,- key: "nickname",+ key: 'nickname',},{- title: t("accountStatus"),+ title: t('accountStatus'),render: (text, am) => {return (<>- {am.status === AccountStatus.USABLE ? (- <>- <CheckCircleOutlined- style={{- color: "var(--successColor)",- marginRight: "3px",- }}- />- {t("online")}- </>- ) : (- <>- <WarningOutlined- style={{- color: "var(--warningColor)",- marginRight: "3px",- }}- />- {t("offline")}- </>- )}+ {am.status === AccountStatus.USABLE+ ? (+ <>+ <CheckCircleOutlined+ style={{+ color: 'var(--successColor)',+ marginRight: '3px',+ }}+ />+ {t('online')}+ </>+ )+ : (+ <>+ <WarningOutlined+ style={{+ color: 'var(--warningColor)',+ marginRight: '3px',+ }}+ />+ {t('offline')}+ </>+ )}</>- );+ )},width: 100,- key: "nickname",+ key: 'nickname',},{- title: t("userManageModal.space"),+ title: t('userManageModal.space'),render: (text, am) => {return (<UserGroupSelectaccount={am}onChange={async (groupId) => {- setCutLoading(true);- await updateAccountGroupRank();+ setCutLoading(true)+ await updateAccountGroupRank()await updateAccountApi({id: am.id,groupId,- });- await getAccountList();- setCutLoading(false);+ })+ await getAccountList()+ setCutLoading(false)}}/>- );+ )},width: 200,- key: "groupId",+ key: 'groupId',},- ];- return columns;- }, []);+ ]+ return columns+ }, [])- const rowSelection: TableProps<SocialAccount>["rowSelection"] = {+ const rowSelection: TableProps<SocialAccount>['rowSelection'] = {onChange: (selectedRowKeys: React.Key[],selectedRows: SocialAccount[],) => {- setSelectedRows(selectedRows);+ setSelectedRows(selectedRows)},getCheckboxProps: (record: SocialAccount) => ({name: record.nickname,}),- selectedRowKeys: selectedRows.map((v) => v.id),- };+ selectedRowKeys: selectedRows.map(v => v.id),+ }const close = () => {- onCancel();- setSelectedRows([]);- updateAccountGroupRank();- };+ onCancel()+ setSelectedRows([])+ updateAccountGroupRank()+ }// 更新账户组顺序const updateAccountGroupRank = async () => {if (isUpdateRank.current) {- const accountGroupList = useAccountStore.getState().accountGroupList;+ const accountGroupList = useAccountStore.getState().accountGroupListfor (let i = 0; i < accountGroupList.length; i++) {- const v = accountGroupList[i];+ const v = accountGroupList[i]// 这里不需要更新数据,因为在排序完成后已经更新了全局的sotre,引用sotre的所有位置都会发生更改// TODO 排序更新// await icpEditDeleteAccountGroup({@@ -389,35 +418,35 @@ const UserManageModal = memo(// rank: i,// });}- isUpdateRank.current = false;+ isUpdateRank.current = false}- };+ }const accountListLast = useMemo(() => {if (activeGroup === allUser.current) {- return accountList;+ return accountList}- return accountGroupList.find((v) => v.id === activeGroup)?.children;- }, [accountMap, activeGroup, accountGroupList]);+ return accountGroupList.find(v => v.id === activeGroup)?.children+ }, [accountMap, activeGroup, accountGroupList])const imperativeHandle: IUserManageModalRef = {setActiveGroup,- };- useImperativeHandle(ref, () => imperativeHandle);+ }+ useImperativeHandle(ref, () => imperativeHandle)const openAddAccountFlow = async () => {- const currentGroupId = activeGroup;- close();+ const currentGroupId = activeGroup+ close()if (currentGroupId === allUser.current) {// 如果选择的是"全部账号",需要用户选择空间- setIsAddAccountOpen(true);- } else {+ setIsAddAccountOpen(true)+ }+ else {// 如果选择的是具体空间,直接使用该空间- setTargetGroupIdForModal(currentGroupId);- setIsAddAccountOpen(true);+ setTargetGroupIdForModal(currentGroupId)+ setIsAddAccountOpen(true)}- };-+ }return (<>@@ -426,15 +455,15 @@ const UserManageModal = memo(open={deleteHitOpen}onClose={() => setDeleteHitOpen(false)}onDeleteSuccess={async () => {- await getAccountList();- setSelectedRows([]);- message.success("删除成功");+ await getAccountList()+ setSelectedRows([])+ message.success('删除成功')}}/><Modalopen={open}- title={t("accountManager")}+ title={t('accountManager')}zIndex={1001}footer={null}width={1000}@@ -448,7 +477,7 @@ const UserManageModal = memo(activeGroup={activeGroup}onChange={setActiveGroup}onSortEnd={() => {- isUpdateRank.current = true;+ isUpdateRank.current = true}}/>@@ -460,33 +489,33 @@ const UserManageModal = memo(allUser={allUser.current}/>- <div className="userManage-content-head" style={{ marginBottom: "8px", display: "flex", justifyContent: "flex-end" }}>- <Button type="primary" onClick={openAddAccountFlow}>{t("addAccount")}</Button>+ <div className="userManage-content-head" style={{ marginBottom: '8px', display: 'flex', justifyContent: 'flex-end' }}>+ <Button type="primary" onClick={openAddAccountFlow}>{t('addAccount')}</Button></div><Table<SocialAccount>columns={columns}dataSource={accountListLast}rowKey="id"- scroll={{ y: "100%" }}- rowSelection={{ type: "checkbox", ...rowSelection }}+ scroll={{ y: '100%' }}+ rowSelection={{ type: 'checkbox', ...rowSelection }}/><Drawer- title={+ title={(<>已选择- <span style={{ color: "var(--successColor)" }}>+ <span style={{ color: 'var(--successColor)' }}>{selectedRows.length}</span>个账号</>- }+ )}placement="bottom"mask={false}height={150}closable={true}onClose={() => {- setSelectedRows([]);+ setSelectedRows([])}}open={selectedRows.length !== 0}getContainer={false}@@ -495,7 +524,7 @@ const UserManageModal = memo(<divclassName="userManage-content-multiple-item"onClick={() => {- setDeleteHitOpen(true);+ setDeleteHitOpen(true)}}><div className="userManage-content-multiple-item-icon">@@ -510,25 +539,24 @@ const UserManageModal = memo(</Spin></Modal>-<AddAccountModalopen={isAddAccountOpen}onClose={async () => {- setIsAddAccountOpen(false);- setTargetGroupIdForModal(undefined);+ setIsAddAccountOpen(false)+ setTargetGroupIdForModal(undefined)}}onAddSuccess={async (acc) => {// 账号已经在授权时直接添加到指定空间,无需额外移动- await getAccountList();+ await getAccountList()}}targetGroupId={targetGroupIdForModal}showSpaceSelector={activeGroup === allUser.current}/></>- );+ )},),-);-UserManageModal.displayName = "UserManageModal";+)+UserManageModal.displayName = 'UserManageModal'-export default UserManageModal;+export default UserManageModaldiff --git a/project/web/src/app/[lng]/accounts/components/AccountSidebar/UserManageSidebar.tsx b/project/web/src/app/[lng]/accounts/components/AccountSidebar/UserManageSidebar.tsxindex 264f1586..66c8db38 100644--- a/project/web/src/app/[lng]/accounts/components/AccountSidebar/UserManageSidebar.tsx+++ b/project/web/src/app/[lng]/accounts/components/AccountSidebar/UserManageSidebar.tsx@@ -1,36 +1,37 @@-import { ForwardedRef, forwardRef, memo, useRef, useState } from "react";-import { Button, Input, message, Modal } from "antd";+import type { ForwardedRef } from 'react'+import type { AccountGroupItem } from '@/api/types/account.type'import {ExclamationCircleFilled,PlusOutlined,UnorderedListOutlined,-} from "@ant-design/icons";-import { useAccountStore } from "@/store/account";-import { useShallow } from "zustand/react/shallow";-import styles from "./AccountSidebar.module.scss";-import { ReactSortable } from "react-sortablejs";-import { ControlledMenu, MenuItem } from "@szhsin/react-menu";-import "@szhsin/react-menu/dist/index.css";+} from '@ant-design/icons'+import { ControlledMenu, MenuItem } from '@szhsin/react-menu'+import { Button, Input, message, Modal } from 'antd'+import { forwardRef, memo, useRef, useState } from 'react'+import { ReactSortable } from 'react-sortablejs'+import { useShallow } from 'zustand/react/shallow'import {createAccountGroupApi,deleteAccountGroupApi,updateAccountGroupApi,-} from "@/api/account";-import { AccountGroupItem } from "@/api/types/account.type";-import { useTransClient } from "@/app/i18n/client";+} from '@/api/account'+import { useTransClient } from '@/app/i18n/client'+import { useAccountStore } from '@/store/account'+import styles from './AccountSidebar.module.scss'+import '@szhsin/react-menu/dist/index.css'export interface IUserManageSidebarRef {}export interface IUserManageSidebarProps {- activeGroup: string;- allUser: string;- onChange: (id: string) => void;- onSortEnd: () => void;+ activeGroup: string+ allUser: string+ onChange: (id: string) => void+ onSortEnd: () => void}-const { confirm } = Modal;+const { confirm } = Modal-const MENU_ID = "userManageSidebar";+const MENU_ID = 'userManageSidebar'const UserManageSidebar = memo(forwardRef(@@ -38,7 +39,7 @@ const UserManageSidebar = memo({ activeGroup, allUser, onChange, onSortEnd }: IUserManageSidebarProps,ref: ForwardedRef<IUserManageSidebarRef>,) => {- const { t } = useTransClient("account");+ const { t } = useTransClient('account')const {accountGroupList,accountList,@@ -46,59 +47,59 @@ const UserManageSidebar = memo(getAccountGroup,getAccountList,} = useAccountStore(- useShallow((state) => ({+ useShallow(state => ({accountGroupList: state.accountGroupList,accountList: state.accountList,getAccountGroup: state.getAccountGroup,getAccountList: state.getAccountList,setAccountGroupList: state.setAccountGroupList,})),- );- const [openCreateGroup, setOpenCreateGroup] = useState(false);- const [groupName, setGroupName] = useState("");- const [createGroupLoading, setCreateGroupLoading] = useState(false);+ )+ const [openCreateGroup, setOpenCreateGroup] = useState(false)+ const [groupName, setGroupName] = useState('')+ const [createGroupLoading, setCreateGroupLoading] = useState(false)// -1=新建 不然为重命名,值为要重命名的id- const [createGroupId, setCreateGroupId] = useState("-1");- const srcollEl = useRef<HTMLElement>(undefined);- const [isOpen, setOpen] = useState(false);- const [anchorPoint, setAnchorPoint] = useState({ x: 0, y: 0 });+ const [createGroupId, setCreateGroupId] = useState('-1')+ const srcollEl = useRef<HTMLElement>(undefined)+ const [isOpen, setOpen] = useState(false)+ const [anchorPoint, setAnchorPoint] = useState({ x: 0, y: 0 })// 右键操作的数据- const [rightClickOperateData, setRightClickOperateData] =- useState<AccountGroupItem>();+ const [rightClickOperateData, setRightClickOperateData]+ = useState<AccountGroupItem>()const createGroupCancel = () => {- setOpenCreateGroup(false);- setGroupName("");- };+ setOpenCreateGroup(false)+ setGroupName('')+ }return (<><ControlledMenuanchorPoint={anchorPoint}- state={isOpen ? "open" : "closed"}+ state={isOpen ? 'open' : 'closed'}direction="right"onClose={() => setOpen(false)}><MenuItemonClick={() => {- setCreateGroupId(rightClickOperateData!.id);- setOpenCreateGroup(true);- setGroupName(rightClickOperateData!.name);+ setCreateGroupId(rightClickOperateData!.id)+ setOpenCreateGroup(true)+ setGroupName(rightClickOperateData!.name)}}>- {t("userManageSidebar.rename")}+ {t('userManageSidebar.rename')}</MenuItem><MenuItemonClick={() => {confirm({- title: t("userManageSidebar.confirmDelete"),+ title: t('userManageSidebar.confirmDelete'),icon: <ExclamationCircleFilled />,content: (<>- {t("userManageSidebar.confirmDeleteContent")}+ {t('userManageSidebar.confirmDeleteContent')}<spanstyle={{- color: "var(--colorPrimary6)",+ color: 'var(--colorPrimary6)',}}>{rightClickOperateData?.name}@@ -107,56 +108,57 @@ const UserManageSidebar = memo(</>),onOk: async () => {- await deleteAccountGroupApi([rightClickOperateData!.id]);- await getAccountGroup();- message.success(t("userManageSidebar.deleteSuccess"));+ await deleteAccountGroupApi([rightClickOperateData!.id])+ await getAccountGroup()+ message.success(t('userManageSidebar.deleteSuccess'))},- });+ })}}>- {t("userManageSidebar.delete")}+ {t('userManageSidebar.delete')}</MenuItem></ControlledMenu><Modalopen={openCreateGroup}- title={createGroupId === "-1" ? t("userManageSidebar.createSpaceTitle") : t("userManageSidebar.renameSpaceTitle")}+ title={createGroupId === '-1' ? t('userManageSidebar.createSpaceTitle') : t('userManageSidebar.renameSpaceTitle')}onCancel={createGroupCancel}- footer={+ footer={(<>- <Button onClick={createGroupCancel}>{t("userManageSidebar.cancel")}</Button>+ <Button onClick={createGroupCancel}>{t('userManageSidebar.cancel')}</Button><Buttontype="primary"onClick={async () => {- setCreateGroupLoading(true);- if (createGroupId === "-1") {+ setCreateGroupLoading(true)+ if (createGroupId === '-1') {await createAccountGroupApi({name: groupName,- });- } else {+ })+ }+ else {await updateAccountGroupApi({name: groupName,id: createGroupId,- });+ })}- await getAccountGroup();- setCreateGroupLoading(false);- createGroupCancel();+ await getAccountGroup()+ setCreateGroupLoading(false)+ createGroupCancel()}}loading={createGroupLoading}>- {t("userManageSidebar.save")}+ {t('userManageSidebar.save')}</Button></>- }+ )}><div className={styles.createGroup}>- <label>{t("userManageSidebar.spaceName")}</label>+ <label>{t('userManageSidebar.spaceName')}</label><Inputvalue={groupName}- placeholder={t("userManageSidebar.spaceNamePlaceholder")}- onChange={(e) => setGroupName(e.target.value)}+ placeholder={t('userManageSidebar.spaceNamePlaceholder')}+ onChange={e => setGroupName(e.target.value)}/></div></Modal>@@ -165,27 +167,27 @@ const UserManageSidebar = memo(<div className="userManage-sidebar-top"><divclassName={[- "userManage-sidebar-allUser",- activeGroup === allUser && "userManage-sidebar--active",- ].join(" ")}+ 'userManage-sidebar-allUser',+ activeGroup === allUser && 'userManage-sidebar--active',+ ].join(' ')}onClick={() => {- onChange(allUser);+ onChange(allUser)}}>- <span className="userManage-sidebar-name">{t("userManageSidebar.allAccounts")}</span>+ <span className="userManage-sidebar-name">{t('userManageSidebar.allAccounts')}</span><span className="userManage-sidebar-count">{accountList.length}</span></div><div className="userManage-sidebar-list">- <p className="userManage-sidebar-list-title">{t("userManageSidebar.spaces")}</p>+ <p className="userManage-sidebar-list-title">{t('userManageSidebar.spaces')}</p><ReactSortableclassName="userManage-sidebar-list-sortable"list={accountGroupList}animation={250}onEnd={async () => {- onSortEnd();+ onSortEnd()}}setList={setAccountGroupList}scrollSensitivity={100}@@ -198,21 +200,21 @@ const UserManageSidebar = memo(return (<divclassName={[- "userManage-sidebar-list-item",- activeGroup === v.id && "userManage-sidebar--active",- ].join(" ")}+ 'userManage-sidebar-list-item',+ activeGroup === v.id && 'userManage-sidebar--active',+ ].join(' ')}key={v.id}onClick={() => {- onChange(v.id);+ onChange(v.id)}}onContextMenu={(e) => {- e.preventDefault();+ e.preventDefault()if (v.isDefault) {- return message.error(t("userManageSidebar.cannotOperateDefault"));+ return message.error(t('userManageSidebar.cannotOperateDefault'))}- setAnchorPoint({ x: e.clientX, y: e.clientY });- setOpen(true);- setRightClickOperateData(v);+ setAnchorPoint({ x: e.clientX, y: e.clientY })+ setOpen(true)+ setRightClickOperateData(v)}}><div className="userManage-sidebar-left">@@ -227,7 +229,7 @@ const UserManageSidebar = memo({v.children.length}</span></div>- );+ )})}</ReactSortable></div>@@ -237,19 +239,19 @@ const UserManageSidebar = memo(type="primary"icon={<PlusOutlined />}onClick={() => {- setCreateGroupId("-1");- setOpenCreateGroup(true);+ setCreateGroupId('-1')+ setOpenCreateGroup(true)}}>- {t("userManageSidebar.createSpace")}+ {t('userManageSidebar.createSpace')}</Button></div></div></>- );+ )},),-);-UserManageSidebar.displayName = "UserManageSidebar";+)+UserManageSidebar.displayName = 'UserManageSidebar'-export default UserManageSidebar;+export default UserManageSidebardiff --git a/project/web/src/app/[lng]/accounts/components/AddAccountModal/AddAccountModal.module.scss b/project/web/src/app/[lng]/accounts/components/AddAccountModal/AddAccountModal.module.scssindex 25dbbad6..05f3abe8 100644--- a/project/web/src/app/[lng]/accounts/components/AddAccountModal/AddAccountModal.module.scss+++ b/project/web/src/app/[lng]/accounts/components/AddAccountModal/AddAccountModal.module.scss@@ -44,4 +44,4 @@}}}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/accounts/components/AddAccountModal/index.tsx b/project/web/src/app/[lng]/accounts/components/AddAccountModal/index.tsxindex 49bbb1d3..eae28d94 100644--- a/project/web/src/app/[lng]/accounts/components/AddAccountModal/index.tsx+++ b/project/web/src/app/[lng]/accounts/components/AddAccountModal/index.tsx@@ -1,274 +1,285 @@-import { ForwardedRef, forwardRef, memo, useEffect, useMemo, useState } from "react";-import styles from "./AddAccountModal.module.scss";-import { Button, Modal, Tooltip, Select, Space, Typography } from "antd";-import { AccountPlatInfoArr, PlatType } from "@/app/config/platConfig";-import { SocialAccount } from "@/api/types/account.type";-import { useTransClient } from "@/app/i18n/client";-import { kwaiSkip } from "@/app/[lng]/accounts/plat/kwaiLogin";-import { bilibiliSkip } from "../../plat/BilibiliLogin";-import { youtubeSkip } from "../../plat/YoutubeLogin";-import { twitterSkip } from "../../plat/TwtterLogin";-import { tiktokSkip } from "../../plat/TiktokLogin";-import { facebookSkip, FacebookPagesModal } from "../../plat/FacebookLogin";-import { instagramSkip } from "../../plat/InstagramLogin";-import { threadsSkip } from "../../plat/ThreadsLogin";-import { wxGzhSkip } from "../../plat/WxGzh";-import { pinterestSkip } from "../../plat/PinterestLogin";-import { linkedinSkip } from "../../plat/LinkedinLogin";-import { useAccountStore } from "@/store/account";-import { useShallow } from "zustand/react/shallow";-import { getIpLocation, IpLocationInfo } from "@/utils/ipLocation";-import DownloadAppModal from "@/components/common/DownloadAppModal";--const { Text } = Typography;+import type { ForwardedRef } from 'react'+import type { SocialAccount } from '@/api/types/account.type'+import type { IpLocationInfo } from '@/utils/ipLocation'+import { Button, Modal, Select, Space, Tooltip, Typography } from 'antd'+import { forwardRef, memo, useEffect, useMemo, useState } from 'react'+import { useShallow } from 'zustand/react/shallow'+import { kwaiSkip } from '@/app/[lng]/accounts/plat/kwaiLogin'+import { AccountPlatInfoArr, PlatType } from '@/app/config/platConfig'+import { useTransClient } from '@/app/i18n/client'+import DownloadAppModal from '@/components/common/DownloadAppModal'+import { useAccountStore } from '@/store/account'+import { getIpLocation } from '@/utils/ipLocation'+import { bilibiliSkip } from '../../plat/BilibiliLogin'+import { FacebookPagesModal, facebookSkip } from '../../plat/FacebookLogin'+import { instagramSkip } from '../../plat/InstagramLogin'+import { linkedinSkip } from '../../plat/LinkedinLogin'+import { pinterestSkip } from '../../plat/PinterestLogin'+import { threadsSkip } from '../../plat/ThreadsLogin'+import { tiktokSkip } from '../../plat/TiktokLogin'+import { twitterSkip } from '../../plat/TwtterLogin'+import { wxGzhSkip } from '../../plat/WxGzh'+import { youtubeSkip } from '../../plat/YoutubeLogin'+import styles from './AddAccountModal.module.scss'++const { Text } = Typographyexport interface IAddAccountModalRef {}export interface IAddAccountModalProps {- open: boolean;- onClose: () => void;- onAddSuccess: (accountInfo: SocialAccount) => void;+ open: boolean+ onClose: () => void+ onAddSuccess: (accountInfo: SocialAccount) => void// 目标空间ID,用于根据空间属地(CN)过滤可添加平台- targetGroupId?: string;+ targetGroupId?: string// 是否显示空间选择器(当从AccountSidebar的"添加账号"按钮打开时显示)- showSpaceSelector?: boolean;+ showSpaceSelector?: boolean// 自动触发平台,用于在打开时直接尝试跳转授权- autoTriggerPlatform?: PlatType;+ autoTriggerPlatform?: PlatType}const AddAccountModal = memo(forwardRef(- (- { open, onClose, onAddSuccess, targetGroupId, showSpaceSelector = false, autoTriggerPlatform }: IAddAccountModalProps,+ (+ { open, onClose, onAddSuccess, targetGroupId, showSpaceSelector = false, autoTriggerPlatform }: IAddAccountModalProps,ref: ForwardedRef<IAddAccountModalRef>,) => {- const { t } = useTransClient('account');- const [showFacebookPagesModal, setShowFacebookPagesModal] = useState(false);+ const { t } = useTransClient('account')+ const [showFacebookPagesModal, setShowFacebookPagesModal] = useState(false)const { accountGroupList, getAccountList } = useAccountStore(- useShallow((state) => ({+ useShallow(state => ({accountGroupList: state.accountGroupList,getAccountList: state.getAccountList,- }))- );- const [downloadVisible, setDownloadVisible] = useState(false);- const [downloadPlatform, setDownloadPlatform] = useState<string>("");- const aitoearnDownloadUrl = process.env.NEXT_PUBLIC_AITOEARN_APP_DOWNLOAD_URL || "";+ })),+ )+ const [downloadVisible, setDownloadVisible] = useState(false)+ const [downloadPlatform, setDownloadPlatform] = useState<string>('')+ const aitoearnDownloadUrl = process.env.NEXT_PUBLIC_AITOEARN_APP_DOWNLOAD_URL || ''// 空间选择相关状态- const [selectedSpaceId, setSelectedSpaceId] = useState<string | undefined>(targetGroupId);- const [spaceSelectionRequired, setSpaceSelectionRequired] = useState(false);+ const [selectedSpaceId, setSelectedSpaceId] = useState<string | undefined>(targetGroupId)+ const [spaceSelectionRequired, setSpaceSelectionRequired] = useState(false)// 判断location是否属于中国(CN)const isLocationCN = (location?: string | null): boolean => {- if (!location) return false;- const upper = location.toUpperCase();- return upper.startsWith('CN') || upper.includes('CHINA') || location.includes('中国');- };+ if (!location)+ return false+ const upper = location.toUpperCase()+ return upper.startsWith('CN') || upper.includes('CHINA') || location.includes('中国')+ }// 当前目标空间是否视为中国属地- const [isCnSpace, setIsCnSpace] = useState<boolean | null>(null);- const [isLocLoading, setIsLocLoading] = useState(false);+ const [isCnSpace, setIsCnSpace] = useState<boolean | null>(null)+ const [isLocLoading, setIsLocLoading] = useState(false)// 初始化空间选择 - 简化版本useEffect(() => {if (!open) {- setSpaceSelectionRequired(false);- setSelectedSpaceId(undefined);- return;+ setSpaceSelectionRequired(false)+ setSelectedSpaceId(undefined)+ return}-+if (showSpaceSelector) {- setSpaceSelectionRequired(true);+ setSpaceSelectionRequired(true)// 默认选择第一个默认空间- const defaultSpace = accountGroupList.find(group => group.isDefault);+ const defaultSpace = accountGroupList.find(group => group.isDefault)if (defaultSpace && !selectedSpaceId) {- setSelectedSpaceId(defaultSpace.id);+ setSelectedSpaceId(defaultSpace.id)}- } else {- setSpaceSelectionRequired(false);+ }+ else {+ setSpaceSelectionRequired(false)if (targetGroupId) {- setSelectedSpaceId(targetGroupId);+ setSelectedSpaceId(targetGroupId)}}- }, [open, showSpaceSelector, targetGroupId, accountGroupList, selectedSpaceId]);--+ }, [open, showSpaceSelector, targetGroupId, accountGroupList, selectedSpaceId])useEffect(() => {if (!open || !selectedSpaceId) {- setIsCnSpace(null);- setIsLocLoading(false);- return;+ setIsCnSpace(null)+ setIsLocLoading(false)+ return}- const currentSpace = (accountGroupList || []).find((g: any) => g.id === selectedSpaceId);+ const currentSpace = (accountGroupList || []).find((g: any) => g.id === selectedSpaceId)if (!currentSpace) {- setIsCnSpace(null);- return;+ setIsCnSpace(null)+ return}- const shouldUseLocal = !currentSpace.proxyIp || currentSpace.proxyIp === '';+ const shouldUseLocal = !currentSpace.proxyIp || currentSpace.proxyIp === ''if (!shouldUseLocal && currentSpace.ip && currentSpace.location) {- setIsCnSpace(isLocationCN(currentSpace.location));- return;+ setIsCnSpace(isLocationCN(currentSpace.location))+ return}- let cancelled = false;+ let cancelled = falseconst fetchLocal = async () => {try {- setIsLocLoading(true);- const info: IpLocationInfo = await getIpLocation();- if (!cancelled) setIsCnSpace(isLocationCN(info.location));- } catch {- if (!cancelled) setIsCnSpace(null);- } finally {- if (!cancelled) setIsLocLoading(false);+ setIsLocLoading(true)+ const info: IpLocationInfo = await getIpLocation()+ if (!cancelled)+ setIsCnSpace(isLocationCN(info.location))+ }+ catch {+ if (!cancelled)+ setIsCnSpace(null)}- };- fetchLocal();+ finally {+ if (!cancelled)+ setIsLocLoading(false)+ }+ }+ fetchLocal()return () => {- cancelled = true;- };- }, [open, selectedSpaceId]);+ cancelled = true+ }+ }, [open, selectedSpaceId])// 自动触发平台授权useEffect(() => {if (open && autoTriggerPlatform && selectedSpaceId) {// 延迟一下确保弹窗完全打开const timer = setTimeout(() => {- const platformInfo = AccountPlatInfoArr.find(([key]) => key === autoTriggerPlatform);+ const platformInfo = AccountPlatInfoArr.find(([key]) => key === autoTriggerPlatform)if (platformInfo) {- handlePlatformClick(autoTriggerPlatform, platformInfo[1]);+ handlePlatformClick(autoTriggerPlatform, platformInfo[1])}- }, 500);-- return () => clearTimeout(timer);+ }, 500)++ return () => clearTimeout(timer)}- }, [open, autoTriggerPlatform, selectedSpaceId]);+ }, [open, autoTriggerPlatform, selectedSpaceId])// 判断平台是否在当前属地可用const isPlatformAvailable = (platType: PlatType): boolean => {// TODO: 暂时屏蔽国内平台 @@.@@- return true;- if (isCnSpace === null) return true; // 未确定属地时显示所有平台-+ return true+ if (isCnSpace === null)+ return true // 未确定属地时显示所有平台+const cnOnlyPlatforms = new Set<PlatType>([PlatType.Douyin,PlatType.KWAI,PlatType.WxGzh,PlatType.WxSph,PlatType.BILIBILI,- ]);-+ ])+// 小红书是全球平台,不受IP限制if (platType === PlatType.Xhs) {- return true;+ return true}-+if (isCnSpace === true) {// 中国属地:仅国内平台可用- return cnOnlyPlatforms.has(platType);- } else {+ return cnOnlyPlatforms.has(platType)+ }+ else {// 非中国属地:国内平台不可用- return !cnOnlyPlatforms.has(platType);+ return !cnOnlyPlatforms.has(platType)}- };+ }const handleOk = () => {- onClose();- };+ onClose()+ }const handleCancel = () => {- onClose();- };+ onClose()+ }// 处理Facebook授权成功后的页面选择const handleFacebookAuthSuccess = () => {- setShowFacebookPagesModal(true);- };+ setShowFacebookPagesModal(true)+ }// 处理Facebook页面选择成功const handleFacebookPagesSuccess = () => {- setShowFacebookPagesModal(false);- onClose();+ setShowFacebookPagesModal(false)+ onClose()// 可以在这里添加成功提示或其他逻辑- };+ }// 处理平台点击const handlePlatformClick = async (key: PlatType, value: any) => {// 如果需要选择空间但未选择,提示用户if (spaceSelectionRequired && !selectedSpaceId) {- return;+ return}// 如果平台在当前属地不可用,则提示if (!isPlatformAvailable(key)) {- return;+ return}// 如果该平台在PC端不可用,则提示下载Aitoearn Appif (value.pcNoThis) {- setDownloadPlatform(value.name);- setDownloadVisible(true);- return;+ setDownloadPlatform(value.name)+ setDownloadVisible(true)+ return}// 记录授权前的账号数量,用于后续识别新账号- const beforeAuthCount = accountGroupList.reduce((total, group) => total + group.children.length, 0);+ const beforeAuthCount = accountGroupList.reduce((total, group) => total + group.children.length, 0)switch (key) {case PlatType.KWAI:- await kwaiSkip(key, selectedSpaceId);- break;+ await kwaiSkip(key, selectedSpaceId)+ breakcase PlatType.BILIBILI:- await bilibiliSkip(key, selectedSpaceId);- break;+ await bilibiliSkip(key, selectedSpaceId)+ breakcase PlatType.YouTube:- await youtubeSkip(key, selectedSpaceId);- break;+ await youtubeSkip(key, selectedSpaceId)+ breakcase PlatType.Twitter:- await twitterSkip(key, selectedSpaceId);- break;+ await twitterSkip(key, selectedSpaceId)+ breakcase PlatType.Tiktok:- await tiktokSkip(key, selectedSpaceId);- break;+ await tiktokSkip(key, selectedSpaceId)+ breakcase PlatType.Facebook:try {- await facebookSkip(key, selectedSpaceId);+ await facebookSkip(key, selectedSpaceId)// Facebook授权成功后显示页面选择弹窗- handleFacebookAuthSuccess();- } catch (error) {- console.error('Facebook授权失败:', error);+ handleFacebookAuthSuccess()}- break;+ catch (error) {+ console.error('Facebook授权失败:', error)+ }+ breakcase PlatType.Instagram:- await instagramSkip(key, selectedSpaceId);- break;+ await instagramSkip(key, selectedSpaceId)+ breakcase PlatType.Threads:- await threadsSkip(key, selectedSpaceId);- break;+ await threadsSkip(key, selectedSpaceId)+ breakcase PlatType.WxGzh:- await wxGzhSkip(key, selectedSpaceId);- break;+ await wxGzhSkip(key, selectedSpaceId)+ breakcase PlatType.Pinterest:- await pinterestSkip(key, selectedSpaceId);- break;+ await pinterestSkip(key, selectedSpaceId)+ breakcase PlatType.LinkedIn:- await linkedinSkip(key, selectedSpaceId);- break;+ await linkedinSkip(key, selectedSpaceId)+ break}// 授权完成后刷新账号列表setTimeout(async () => {try {- await getAccountList();- console.log('账号列表已刷新');- } catch (error) {- console.error('刷新账号列表失败:', error);+ await getAccountList()+ console.log('账号列表已刷新')+ }+ catch (error) {+ console.error('刷新账号列表失败:', error)}- }, 2000); // 等待3秒让授权完成- };+ }, 2000) // 等待3秒让授权完成+ }return (<>@@ -282,14 +293,15 @@ const AddAccountModal = memo(><div className={styles.addAccountModal}><h1>{t('addAccountModal.subtitle')}</h1>-+{/* 空间选择器 */}{spaceSelectionRequired && (- <div style={{+ <div style={{marginBottom: '20px',paddingBottom: '16px',- borderBottom: '1px solid var(--grayColor3)'- }}>+ borderBottom: '1px solid var(--grayColor3)',+ }}+ ><Space align="center" style={{ width: '100%' }}><Text strong style={{ fontSize: '14px', minWidth: '80px' }}>{t('addAccountModal.addTo')}</Text><Select@@ -297,7 +309,7 @@ const AddAccountModal = memo(placeholder={t('pleaseChooseSpace')}value={selectedSpaceId}onChange={setSelectedSpaceId}- options={accountGroupList.map((g) => ({ value: g.id, label: g.name }))}+ options={accountGroupList.map(g => ({ value: g.id, label: g.name }))}/></Space></div>@@ -305,74 +317,81 @@ const AddAccountModal = memo({/* 当前选择的空间信息 */}{selectedSpaceId && !spaceSelectionRequired && (- <div style={{+ <div style={{marginBottom: '20px',padding: '12px',backgroundColor: 'var(--grayColor1)',borderRadius: '6px',border: '1px solid var(--grayColor3)',fontSize: 'var(--fs-xs)',- color: 'var(--grayColor6)'- }}>- <Text>{t('addAccountModal.currentSpace')}: {accountGroupList.find(g => g.id === selectedSpaceId)?.name}</Text>+ color: 'var(--grayColor6)',+ }}+ >+ <Text>+ {t('addAccountModal.currentSpace')}+ :+ {' '}+ {accountGroupList.find(g => g.id === selectedSpaceId)?.name}+ </Text></div>)}<div className="addAccountModal_plats">{AccountPlatInfoArr.map(([key, value]) => {- const isAvailable = isPlatformAvailable(key as PlatType);+ const isAvailable = isPlatformAvailable(key as PlatType)return (<Tooltip title={value.tips?.account} key={key}><Buttontype="text"- style={{ width: '84px', }}+ style={{ width: '84px' }}className={`addAccountModal_plats-item ${!isAvailable ? 'disabled' : ''}`}disabled={!isAvailable || (spaceSelectionRequired && !selectedSpaceId)}onClick={() => handlePlatformClick(key as PlatType, value)}><div className="addAccountModal_plats-item-con">- <img- src={value.icon}- style={{ opacity: isAvailable ? 1 : 0.5 }}+ <img+ src={value.icon}+ style={{ opacity: isAvailable ? 1 : 0.5 }}/><span style={{ opacity: isAvailable ? 1 : 0.5 }}>{value.name}</span></div></Button></Tooltip>- );+ )})}</div>{/* 属地限制提示 */}{isCnSpace !== null && (- <div style={{- marginTop: '16px',- padding: '12px',- backgroundColor: 'var(--grayColor1)',+ <div style={{+ marginTop: '16px',+ padding: '12px',+ backgroundColor: 'var(--grayColor1)',borderRadius: '6px',fontSize: 'var(--fs-xs)',color: 'var(--grayColor6)',- textAlign: 'center'- }}>- {isCnSpace ?- t('locationRestriction.cnSpace') :- t('locationRestriction.nonCnSpace')- }+ textAlign: 'center',+ }}+ >+ {isCnSpace+ ? t('locationRestriction.cnSpace')+ : t('locationRestriction.nonCnSpace')}</div>)}{/* 空间选择提示 */}{spaceSelectionRequired && !selectedSpaceId && (- <div style={{- marginTop: '16px',- padding: '12px',- backgroundColor: 'var(--warningColor1)',+ <div style={{+ marginTop: '16px',+ padding: '12px',+ backgroundColor: 'var(--warningColor1)',borderRadius: '6px',fontSize: 'var(--fs-xs)',color: 'var(--warningColor)',- textAlign: 'center'- }}>+ textAlign: 'center',+ }}+ >{t('addAccountModal.pleaseChooseSpaceFirst')}</div>)}@@ -391,14 +410,14 @@ const AddAccountModal = memo(visible={downloadVisible}onClose={() => setDownloadVisible(false)}platform={downloadPlatform}- appName={"Aitoearn App"}+ appName="Aitoearn App"downloadUrl={aitoearnDownloadUrl}/></>- );+ )},),-);-AddAccountModal.displayName = "AddAccountModal";+)+AddAccountModal.displayName = 'AddAccountModal'-export default AddAccountModal;+export default AddAccountModaldiff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/AllPlatIcon.tsx b/project/web/src/app/[lng]/accounts/components/CalendarTiming/AllPlatIcon.tsxindex abe7f316..141bfe36 100644--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/AllPlatIcon.tsx+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/AllPlatIcon.tsx@@ -1,11 +1,12 @@-import { ForwardedRef, forwardRef, memo, useMemo } from "react";-import styles from "./calendarTiming.module.scss";+import type { ForwardedRef } from 'react'+import { forwardRef, memo, useMemo } from 'react'+import styles from './calendarTiming.module.scss'export interface IAllPlatIconRef {}export interface IAllPlatIconProps {- size?: number;- style?: React.CSSProperties;+ size?: number+ style?: React.CSSProperties}const AllPlatIcon = memo(@@ -15,20 +16,20 @@ const AllPlatIcon = memo(ref: ForwardedRef<IAllPlatIconRef>,) => {const widthChild = useMemo(() => {- return size / 5;- }, [size]);+ return size / 5+ }, [size])const childStyle = useMemo(() => {return {- width: widthChild + "px",- height: widthChild + "px",- };- }, [widthChild]);+ width: `${widthChild}px`,+ height: `${widthChild}px`,+ }+ }, [widthChild])return (<divclassName={styles.allPlatIcon}- style={{ width: size + "px", height: size + "px", ...style }}+ style={{ width: `${size}px`, height: `${size}px`, ...style }}><ul><li style={childStyle}></li>@@ -39,9 +40,9 @@ const AllPlatIcon = memo(<li style={childStyle}></li></ul></div>- );+ )},),-);+)-export default AllPlatIcon;+export default AllPlatIcondiff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/BoxDragPreview.tsx b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/BoxDragPreview.tsxindex 5bb8d6c4..388381d6 100644--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/BoxDragPreview.tsx+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/BoxDragPreview.tsx@@ -1,35 +1,35 @@-import type { CSSProperties, FC } from "react";-import { memo, useEffect, useState } from "react";-import RecordCore from "@/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/RecordCore";-import { PublishRecordItem } from "@/api/plat/types/publish.types";+import type { CSSProperties, FC } from 'react'+import type { PublishRecordItem } from '@/api/plat/types/publish.types'+import { memo, useEffect, useState } from 'react'+import RecordCore from '@/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/RecordCore'const styles: CSSProperties = {- display: "inline-block",- transform: "rotate(-7deg)",- WebkitTransform: "rotate(-7deg)",- transition: "0.3s",-};+ display: 'inline-block',+ transform: 'rotate(-7deg)',+ WebkitTransform: 'rotate(-7deg)',+ transition: '0.3s',+}export interface BoxDragPreviewProps {- publishRecord: PublishRecordItem;+ publishRecord: PublishRecordItem}export const BoxDragPreview: FC<BoxDragPreviewProps> = memo(- function BoxDragPreview({ publishRecord }) {- const [tickTock, setTickTock] = useState(false);+ ({ publishRecord }) => {+ const [tickTock, setTickTock] = useState(false)useEffect(- function subscribeToIntervalTick() {- const interval = setInterval(() => setTickTock(!tickTock), 500);- return () => clearInterval(interval);+ () => {+ const interval = setInterval(() => setTickTock(!tickTock), 500)+ return () => clearInterval(interval)},[tickTock],- );+ )return (<div style={styles}><RecordCore publishRecord={publishRecord} /></div>- );+ )},-);+)diff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/CalendarRecord.tsx b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/CalendarRecord.tsxindex dcce8235..2f2e23da 100644--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/CalendarRecord.tsx+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/CalendarRecord.tsx@@ -1,25 +1,29 @@-import { ForwardedRef, forwardRef, memo, useEffect } from "react";-import styles from "./calendarRecord.module.scss";-import { DragSourceMonitor, useDrag } from "react-dnd";-import { getEmptyImage } from "react-dnd-html5-backend";-import RecordCore from "@/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/RecordCore";-import {+import type { ForwardedRef } from 'react'+import type { DragSourceMonitor } from 'react-dnd'+import type {PublishRecordItem,+} from '@/api/plat/types/publish.types'+import dayjs from 'dayjs'+import { forwardRef, memo, useEffect } from 'react'+import { useDrag } from 'react-dnd'+import { getEmptyImage } from 'react-dnd-html5-backend'+import { useShallow } from 'zustand/react/shallow'+import { updatePublishRecordTimeApi } from '@/api/plat/publish'+import {PublishStatus,-} from "@/api/plat/types/publish.types";-import { useCalendarTiming } from "@/app/[lng]/accounts/components/CalendarTiming/useCalendarTiming";-import { useShallow } from "zustand/react/shallow";+} from '@/api/plat/types/publish.types'import {getDays,getUtcDays,-} from "@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils";-import { updatePublishRecordTimeApi } from "@/api/plat/publish";-import dayjs from "dayjs";+} from '@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils'+import RecordCore from '@/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/RecordCore'+import { useCalendarTiming } from '@/app/[lng]/accounts/components/CalendarTiming/useCalendarTiming'+import styles from './calendarRecord.module.scss'export interface ICalendarRecordRef {}export interface ICalendarRecordProps {- publishRecord: PublishRecordItem;+ publishRecord: PublishRecordItem}const CalendarRecord = memo(@@ -29,87 +33,88 @@ const CalendarRecord = memo(ref: ForwardedRef<ICalendarRecordRef>,) => {const { setRecordMap, recordMap } = useCalendarTiming(- useShallow((state) => ({+ useShallow(state => ({setRecordMap: state.setRecordMap,recordMap: state.recordMap,})),- );+ )const [{ opacity }, drag, preview] = useDrag(() => ({- type: "box",+ type: 'box',item: { publishRecord },end(item, monitor) {- const dropResult: any = monitor.getDropResult();- if (!dropResult) return null;+ const dropResult: any = monitor.getDropResult()+ if (!dropResult)+ return null- const { publishRecord } = item;- const newRecordMap = new Map(recordMap);- const days = getDays(publishRecord.publishTime);- const timeStr = days.format("YYYY-MM-DD");+ const { publishRecord } = item+ const newRecordMap = new Map(recordMap)+ const days = getDays(publishRecord.publishTime)+ const timeStr = days.format('YYYY-MM-DD')const newTimeStr = getDays(dropResult!.time.date).format(- "YYYY-MM-DD",- );+ 'YYYY-MM-DD',+ )// 原始时间- const oldDate = dayjs(item.publishRecord.publishTime);+ const oldDate = dayjs(item.publishRecord.publishTime)// 新日期(只取年月日)- const newDate = dayjs(dropResult!.time.date);+ const newDate = dayjs(dropResult!.time.date)// 合并年月日和时分秒const mergedDate = newDate.hour(oldDate.hour()).minute(oldDate.minute()).second(oldDate.second())- .millisecond(oldDate.millisecond());+ .millisecond(oldDate.millisecond())- item.publishRecord["publishTime"] = mergedDate.toDate();+ item.publishRecord.publishTime = mergedDate.toDate()// 移除旧数据newRecordMap.set(timeStr,newRecordMap.get(timeStr)!- .filter((v) => v.id !== publishRecord.id),- );+ .filter(v => v.id !== publishRecord.id),+ )// 添加新数据- let list = newRecordMap.get(newTimeStr);+ let list = newRecordMap.get(newTimeStr)if (!list) {- list = [];- newRecordMap.set(newTimeStr, list);+ list = []+ newRecordMap.set(newTimeStr, list)}- list.push(publishRecord);+ list.push(publishRecord)// 排序list = list.sort((a, b) =>- new Date(a.publishTime).getTime() -- new Date(b.publishTime).getTime(),- );- newRecordMap.set(newTimeStr, list);+ new Date(a.publishTime).getTime()+ - new Date(b.publishTime).getTime(),+ )+ newRecordMap.set(newTimeStr, list)- setRecordMap(newRecordMap);+ setRecordMap(newRecordMap)// 更新APIupdatePublishRecordTimeApi({id: publishRecord.id,publishTime: getUtcDays(publishRecord.publishTime).format(),- });+ })},collect: (monitor: DragSourceMonitor) => ({opacity: monitor.isDragging() ? 0 : 1,}),}),[recordMap],- );+ )useEffect(() => {- preview(getEmptyImage(), { captureDraggingState: true });- }, []);+ preview(getEmptyImage(), { captureDraggingState: true })+ }, [])return (<div- style={{ opacity: opacity }}+ style={{ opacity }}ref={(node) => {if (publishRecord.status === PublishStatus.UNPUBLISH) {- drag(node);+ drag(node)}}}className={styles.calendarRecord}@@ -117,9 +122,9 @@ const CalendarRecord = memo(><RecordCore publishRecord={publishRecord} /></div>- );+ )},),-);+)-export default CalendarRecord;+export default CalendarRecorddiff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/CustomDragLayer.tsx b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/CustomDragLayer.tsxindex 2a0a4db2..79300fd4 100644--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/CustomDragLayer.tsx+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/CustomDragLayer.tsx@@ -1,24 +1,24 @@-import type { CSSProperties, FC } from "react";-import type { XYCoord } from "react-dnd";-import { useDragLayer } from "react-dnd";-import { BoxDragPreview } from "@/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/BoxDragPreview";-import { PublishRecordItem } from "@/api/plat/types/publish.types";+import type { CSSProperties, FC } from 'react'+import type { XYCoord } from 'react-dnd'+import type { PublishRecordItem } from '@/api/plat/types/publish.types'+import { useDragLayer } from 'react-dnd'+import { BoxDragPreview } from '@/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/BoxDragPreview'function snapToGrid(x: number, y: number): [number, number] {- const snappedX = Math.round(x / 32) * 32;- const snappedY = Math.round(y / 32) * 32;- return [snappedX, snappedY];+ const snappedX = Math.round(x / 32) * 32+ const snappedY = Math.round(y / 32) * 32+ return [snappedX, snappedY]}const layerStyles: CSSProperties = {- position: "fixed",- pointerEvents: "none",+ position: 'fixed',+ pointerEvents: 'none',zIndex: 1000,left: 0,top: 0,- width: "100%",- height: "100%",-};+ width: '100%',+ height: '100%',+}function getItemStyles(initialOffset: XYCoord | null,@@ -27,53 +27,53 @@ function getItemStyles() {if (!initialOffset || !currentOffset) {return {- display: "none",- };+ display: 'none',+ }}- let { x, y } = currentOffset;+ let { x, y } = currentOffsetif (isSnapToGrid) {- x -= initialOffset.x;+ x -= initialOffset.xy -= initialOffset.y;- [x, y] = snapToGrid(x, y);- x += initialOffset.x;- y += initialOffset.y;+ [x, y] = snapToGrid(x, y)+ x += initialOffset.x+ y += initialOffset.y}- const transform = `translate(${x}px, ${y}px)`;+ const transform = `translate(${x}px, ${y}px)`return {transform,WebkitTransform: transform,- };+ }}export interface CustomDragLayerProps {- snapToGrid: boolean;- publishRecord: PublishRecordItem;+ snapToGrid: boolean+ publishRecord: PublishRecordItem}export const CustomDragLayer: FC<CustomDragLayerProps> = (props) => {- const { itemType, isDragging, item, initialOffset, currentOffset } =- useDragLayer((monitor) => ({+ const { itemType, isDragging, item, initialOffset, currentOffset }+ = useDragLayer(monitor => ({item: monitor.getItem(),itemType: monitor.getItemType(),initialOffset: monitor.getInitialSourceClientOffset(),currentOffset: monitor.getSourceClientOffset(),isDragging: monitor.isDragging(),- }));+ }))return (<div style={layerStyles}><divstyle={{...getItemStyles(initialOffset, currentOffset, props.snapToGrid),- position: "relative",+ position: 'relative',zIndex: 10001111,}}><BoxDragPreview publishRecord={props.publishRecord} /></div></div>- );-};+ )+}diff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/RecordCore.tsx b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/RecordCore.tsxindex 5d91d12d..2045873d 100644--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/RecordCore.tsx+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/RecordCore.tsx@@ -1,20 +1,11 @@-import {+import type { MenuProps } from 'antd'+import type { TooltipRef } from 'antd/lib/tooltip'+import type {ForwardedRef,- forwardRef,- memo,- useMemo,- useRef,- useState,-} from "react";-import { Button, Dropdown, Image, Popover, Tag } from "antd";-import { useCalendarTiming } from "@/app/[lng]/accounts/components/CalendarTiming/useCalendarTiming";-import { useShallow } from "zustand/react/shallow";-import {+} from 'react'+import type {PublishRecordItem,- PublishStatus,-} from "@/api/plat/types/publish.types";-import styles from "./recordCore.module.scss";-import { AccountPlatInfoMap, PlatType } from "@/app/config/platConfig";+} from '@/api/plat/types/publish.types'import {CheckCircleOutlined,ClockCircleOutlined,@@ -29,54 +20,75 @@ import {MoreOutlined,SendOutlined,ShareAltOutlined,-} from "@ant-design/icons";-import AvatarPlat from "@/components/AvatarPlat";-import { useAccountStore } from "@/store/account";-import type { MenuProps } from "antd";-import { TooltipRef } from "antd/lib/tooltip";-import { deletePublishRecordApi, nowPubTaskApi } from "@/api/plat/publish";-import { getDays } from "@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils";-import { getOssUrl } from "@/utils/oss";-import { useTransClient } from "@/app/i18n/client";-import ScrollButtonContainer from "@/components/ScrollButtonContainer";+} from '@ant-design/icons'+import { Button, Dropdown, Image, Popover, Tag } from 'antd'+import {+ forwardRef,+ memo,+ useMemo,+ useRef,+ useState,+} from 'react'+import { useShallow } from 'zustand/react/shallow'+import { deletePublishRecordApi, nowPubTaskApi } from '@/api/plat/publish'+import {+ PublishStatus,+} from '@/api/plat/types/publish.types'+import { getDays } from '@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils'+import { useCalendarTiming } from '@/app/[lng]/accounts/components/CalendarTiming/useCalendarTiming'+import { AccountPlatInfoMap, PlatType } from '@/app/config/platConfig'+import { useTransClient } from '@/app/i18n/client'+import AvatarPlat from '@/components/AvatarPlat'+import ScrollButtonContainer from '@/components/ScrollButtonContainer'+import { useAccountStore } from '@/store/account'+import { getOssUrl } from '@/utils/oss'+import styles from './recordCore.module.scss'export interface IRecordCoreRef {}export interface IRecordCoreProps {- publishRecord: PublishRecordItem;+ publishRecord: PublishRecordItem}-const PubStatus = ({ status }: { status: PublishStatus }) => {- const { t } = useTransClient("publish");+function PubStatus({ status }: { status: PublishStatus }) {+ const { t } = useTransClient('publish')return (<div className={styles.pubStatus}>- {status === PublishStatus.FAIL ? (- <Tag color="error">- {t("status.publishFailed")}- <CloseCircleOutlined />- </Tag>- ) : status === PublishStatus.PUB_LOADING ? (- <Tag color="cyan">- {t("status.publishing")}- <LoadingOutlined />- </Tag>- ) : status === PublishStatus.RELEASED ? (- <Tag color="success">- {t("status.publishSuccess")}- <CheckCircleOutlined />- </Tag>- ) : status === PublishStatus.UNPUBLISH ? (- <Tag color="processing">- {t("status.waitingPublish")}- <ClockCircleOutlined />- </Tag>- ) : (- <></>- )}+ {status === PublishStatus.FAIL+ ? (+ <Tag color="error">+ {t('status.publishFailed')}+ <CloseCircleOutlined />+ </Tag>+ )+ : status === PublishStatus.PUB_LOADING+ ? (+ <Tag color="cyan">+ {t('status.publishing')}+ <LoadingOutlined />+ </Tag>+ )+ : status === PublishStatus.RELEASED+ ? (+ <Tag color="success">+ {t('status.publishSuccess')}+ <CheckCircleOutlined />+ </Tag>+ )+ : status === PublishStatus.UNPUBLISH+ ? (+ <Tag color="processing">+ {t('status.waitingPublish')}+ <ClockCircleOutlined />+ </Tag>+ )+ : (+ <></>+ )}</div>- );-};+ )+}const RecordCore = memo(forwardRef(@@ -84,94 +96,94 @@ const RecordCore = memo({ publishRecord }: IRecordCoreProps,ref: ForwardedRef<IRecordCoreRef>,) => {- const { calendarCallWidth, setListLoading, getPubRecord } =- useCalendarTiming(- useShallow((state) => ({+ const { calendarCallWidth, setListLoading, getPubRecord }+ = useCalendarTiming(+ useShallow(state => ({calendarCallWidth: state.calendarCallWidth,setListLoading: state.setListLoading,getPubRecord: state.getPubRecord,})),- );+ )const { accountAccountMap } = useAccountStore(- useShallow((state) => ({+ useShallow(state => ({accountAccountMap: state.accountAccountMap,})),- );- const [popoverOpen, setPopoverOpen] = useState(false);- const popoverRef = useRef<TooltipRef>(null);- const { t } = useTransClient("publish");- const [nowPubLoading, setNowPubLoading] = useState(false);+ )+ const [popoverOpen, setPopoverOpen] = useState(false)+ const popoverRef = useRef<TooltipRef>(null)+ const { t } = useTransClient('publish')+ const [nowPubLoading, setNowPubLoading] = useState(false)- const dropdownItems: MenuProps["items"] = useMemo(() => {+ const dropdownItems: MenuProps['items'] = useMemo(() => {if (publishRecord.workLink) {return [{- key: "2",- label: t("buttons.copyLink"),+ key: '2',+ label: t('buttons.copyLink'),onClick: async () => {await navigator.clipboard.writeText(- publishRecord?.workLink ?? "",- );+ publishRecord?.workLink ?? '',+ )},},- ];+ ]}if (publishRecord.status === PublishStatus.UNPUBLISH) {return [{- key: "3",+ key: '3',danger: true,- label: t("buttons.delete"),+ label: t('buttons.delete'),onClick: async () => {- setPopoverOpen(false);- setListLoading(true);- await deletePublishRecordApi(publishRecord.id);- getPubRecord();+ setPopoverOpen(false)+ setListLoading(true)+ await deletePublishRecordApi(publishRecord.id)+ getPubRecord()},},- ];+ ]}- }, [publishRecord]);+ }, [publishRecord])const days = useMemo(() => {- return getDays(publishRecord.publishTime);- }, [publishRecord]);+ return getDays(publishRecord.publishTime)+ }, [publishRecord])const account = useMemo(() => {- return accountAccountMap.get(publishRecord?.accountId ?? "");- }, [accountAccountMap, publishRecord.accountId]);+ return accountAccountMap.get(publishRecord?.accountId ?? '')+ }, [accountAccountMap, publishRecord.accountId])const platIcon = useMemo(() => {return AccountPlatInfoMap.get(publishRecord?.accountType ?? PlatType.Xhs,- )?.icon;- }, [publishRecord]);+ )?.icon+ }, [publishRecord])const recordInfo = useMemo(() => {return [{- label: t("record.metrics.views"),+ label: t('record.metrics.views'),icon: <EyeOutlined />,- key: "viewCount",+ key: 'viewCount',},{- label: t("record.metrics.comments"),+ label: t('record.metrics.comments'),icon: <MessageOutlined />,- key: "commentCount",+ key: 'commentCount',},{- label: t("record.metrics.likes"),+ label: t('record.metrics.likes'),icon: <LikeOutlined />,- key: "likeCount",+ key: 'likeCount',},{- label: t("record.metrics.shares"),+ label: t('record.metrics.shares'),icon: <ShareAltOutlined />,- key: "shareCount",+ key: 'shareCount',},- ];- }, [t]);+ ]+ }, [t])return (<Popover@@ -179,12 +191,12 @@ const RecordCore = memo(placement="right"rootClassName={styles.recordPopover}open={popoverOpen}- onOpenChange={(e) => setPopoverOpen(e)}- content={+ onOpenChange={e => setPopoverOpen(e)}+ content={(<div className={styles.recordDetails}><div className="recordDetails-top"><div className="recordDetails-top-left">- {days.format("YYYY-MM-DD HH:mm")}+ {days.format('YYYY-MM-DD HH:mm')}<FieldTimeOutlined /></div><Button icon={<FullscreenOutlined />} size="small" />@@ -216,35 +228,37 @@ const RecordCore = memo(</div></div><div className="recordDetails-center-right">- {publishRecord.videoUrl ? (- <>- <Image- src={getOssUrl(publishRecord.coverUrl || "")}- preview={{- destroyOnHidden: true,- imageRender: () => (- <video- muted- width="80%"- height={500}- controls- src={publishRecord.videoUrl}- />- ),- toolbarRender: () => null,- }}- />- </>- ) : (- <Image.PreviewGroup items={publishRecord.imgUrlList}>- <Image src={getOssUrl(publishRecord.coverUrl || "")} />- </Image.PreviewGroup>- )}+ {publishRecord.videoUrl+ ? (+ <>+ <Image+ src={getOssUrl(publishRecord.coverUrl || '')}+ preview={{+ destroyOnHidden: true,+ imageRender: () => (+ <video+ muted+ width="80%"+ height={500}+ controls+ src={publishRecord.videoUrl}+ />+ ),+ toolbarRender: () => null,+ }}+ />+ </>+ )+ : (+ <Image.PreviewGroup items={publishRecord.imgUrlList}>+ <Image src={getOssUrl(publishRecord.coverUrl || '')} />+ </Image.PreviewGroup>+ )}</div></div><ScrollButtonContainer><div className="recordDetails-info">- {recordInfo.map((v) => (+ {recordInfo.map(v => (<div key={v.label} className="recordDetails-info-item"><div className="recordDetails-info-item-top">{v.icon}@@ -252,7 +266,7 @@ const RecordCore = memo(</div>{publishRecord.engagement && (<div className="recordDetails-info-item-num">- {publishRecord.engagement[v.key as "viewCount"] ?? 0}+ {publishRecord.engagement[v.key as 'viewCount'] ?? 0}</div>)}</div>@@ -264,30 +278,32 @@ const RecordCore = memo(<Buttonicon={<ExportOutlined />}onClick={() => {- window.open(publishRecord.workLink, "_blank");+ window.open(publishRecord.workLink, '_blank')}}>- {t("record.viewWork")}+ {t('record.viewWork')}</Button>)}- {publishRecord.status !== PublishStatus.RELEASED &&- publishRecord.status !== PublishStatus.PUB_LOADING ? (- <Button- loading={nowPubLoading}- icon={<SendOutlined />}- onClick={async () => {- setNowPubLoading(true);- await nowPubTaskApi(publishRecord.id);- getPubRecord();- setNowPubLoading(false);- }}- >- {t("buttons.publishNow")}- </Button>- ) : (- <></>- )}+ {publishRecord.status !== PublishStatus.RELEASED+ && publishRecord.status !== PublishStatus.PUB_LOADING+ ? (+ <Button+ loading={nowPubLoading}+ icon={<SendOutlined />}+ onClick={async () => {+ setNowPubLoading(true)+ await nowPubTaskApi(publishRecord.id)+ getPubRecord()+ setNowPubLoading(false)+ }}+ >+ {t('buttons.publishNow')}+ </Button>+ )+ : (+ <></>+ )}{dropdownItems && dropdownItems.length > 0 && (<Dropdown menu={{ items: dropdownItems }} placement="top"><Button icon={<MoreOutlined />} />@@ -295,25 +311,25 @@ const RecordCore = memo()}</div></div>- }+ )}trigger="click"><ButtonclassName={styles.recordCore}- style={{ width: calendarCallWidth + "px" }}+ style={{ width: `${calendarCallWidth}px` }}><div className="recordCore-left">- <img src={platIcon} style={{ width: "25px", height: "25px" }} />- <div className="recordCore-left-date">{days.format("HH:mm")}</div>+ <img src={platIcon} style={{ width: '25px', height: '25px' }} />+ <div className="recordCore-left-date">{days.format('HH:mm')}</div></div><div className="recordCore-right">- <img src={getOssUrl(publishRecord.coverUrl || "")} />+ <img src={getOssUrl(publishRecord.coverUrl || '')} /></div></Button></Popover>- );+ )},),-);+)-export default RecordCore;+export default RecordCorediff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/calendarRecord.module.scss b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/calendarRecord.module.scssindex b2a17263..9e6dd73c 100644--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/calendarRecord.module.scss+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/calendarRecord.module.scss@@ -1,3 +1,2 @@.calendarRecord {--}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/calendarTimingItem.module.scss b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/calendarTimingItem.module.scssindex 976c4d76..b16ac99f 100644--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/calendarTimingItem.module.scss+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/calendarTimingItem.module.scss@@ -63,4 +63,4 @@.calendarTimingItem_over {background: var(--colorPrimary3);-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/recordCore.module.scss b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/recordCore.module.scssindex e92dc5ba..a11c44b8 100644--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/recordCore.module.scss+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/recordCore.module.scss@@ -138,4 +138,4 @@margin-left: 5px;}}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/index.tsx b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/index.tsxindex 24e27d62..a24e2580 100644--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/index.tsx+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/index.tsx@@ -1,25 +1,26 @@-import { ForwardedRef, forwardRef, memo, useEffect, useMemo, useRef, useState } from "react";-import styles from "./components/calendarTimingItem.module.scss";-import { DayCellContentArg } from "@fullcalendar/core";-import { Button, Skeleton } from "antd";-import { useTransClient } from "@/app/i18n/client";-import { DownOutlined, PlusOutlined, UpOutlined } from "@ant-design/icons";-import { useDrop } from "react-dnd";-import CalendarRecord from "@/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/CalendarRecord";-import { CustomDragLayer } from "@/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/CustomDragLayer";-import dayjs from "dayjs";-import { PublishRecordItem } from "@/api/plat/types/publish.types";-import { useCalendarTiming } from "@/app/[lng]/accounts/components/CalendarTiming/useCalendarTiming";-import { useShallow } from "zustand/react/shallow";+import type { DayCellContentArg } from '@fullcalendar/core'+import type { ForwardedRef } from 'react'+import type { PublishRecordItem } from '@/api/plat/types/publish.types'+import { DownOutlined, PlusOutlined, UpOutlined } from '@ant-design/icons'+import { Button, Skeleton } from 'antd'+import dayjs from 'dayjs'+import { forwardRef, memo, useEffect, useMemo, useRef, useState } from 'react'+import { useDrop } from 'react-dnd'+import { useShallow } from 'zustand/react/shallow'+import CalendarRecord from '@/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/CalendarRecord'+import { CustomDragLayer } from '@/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem/components/CustomDragLayer'+import { useCalendarTiming } from '@/app/[lng]/accounts/components/CalendarTiming/useCalendarTiming'+import { useTransClient } from '@/app/i18n/client'+import styles from './components/calendarTimingItem.module.scss'export interface ICalendarTimingItemRef {}export interface ICalendarTimingItemProps {- arg: DayCellContentArg;- onClickPub: (date: string) => void;- loading: boolean;+ arg: DayCellContentArg+ onClickPub: (date: string) => void+ loading: boolean// 发布记录数据- records?: PublishRecordItem[];+ records?: PublishRecordItem[]}const CalendarTimingItem = memo(@@ -28,84 +29,86 @@ const CalendarTimingItem = memo({ arg, onClickPub, loading, records }: ICalendarTimingItemProps,ref: ForwardedRef<ICalendarTimingItemRef>,) => {- const { t } = useTransClient("account");+ const { t } = useTransClient('account')// arg.date 是当前格子的日期,Date 类型- const today = new Date();-+ const today = new Date()+// 🔧 测试模式:模拟今天是1号(取消注释下面一行来测试)// today.setDate(30);-+// 去掉时分秒,只比较年月日const argDate = new Date(arg.date.getFullYear(),arg.date.getMonth(),arg.date.getDate(),- );+ )const nowDate = new Date(today.getFullYear(),today.getMonth(),today.getDate(),- );+ )// [[小时,分钟]] [[4, 12]]- const [reservationsTimes, setReservationsTimes] = useState([]);+ const [reservationsTimes, setReservationsTimes] = useState([])const [{ canDrop, isOver }, drop] = useDrop(() => ({- accept: "box",+ accept: 'box',drop: () => ({time: arg,}),- collect: (monitor) => ({+ collect: monitor => ({isOver: monitor.isOver(),canDrop: monitor.canDrop(),}),}),[],- );- const [isMore, setIsMore] = useState(false);- const cellRef = useRef<HTMLDivElement | null>(null);+ )+ const [isMore, setIsMore] = useState(false)+ const cellRef = useRef<HTMLDivElement | null>(null)const { recordMap } = useCalendarTiming(- useShallow((state) => ({+ useShallow(state => ({recordMap: state.recordMap,})),- );+ )const reservationsTimesLast = useMemo(() => {- return argDate >= nowDate ? reservationsTimes : [];- }, [reservationsTimes]);+ return argDate >= nowDate ? reservationsTimes : []+ }, [reservationsTimes])const recordsLast = useMemo(() => {- if (!records) return [];+ if (!records)+ return []if (isMore) {- return records;- } else {- return records?.slice(0, 3 - reservationsTimesLast.length);+ return records}- }, [isMore, records, reservationsTimesLast, recordMap]);+ else {+ return records?.slice(0, 3 - reservationsTimesLast.length)+ }+ }, [isMore, records, reservationsTimesLast, recordMap])// 进入视图时将“今天”尽量居中显示useEffect(() => {if (argDate.getTime() === nowDate.getTime()) {// 推迟到布局完成后再滚动setTimeout(() => {- cellRef.current?.scrollIntoView({ block: "center", inline: "nearest" });- }, 0);+ cellRef.current?.scrollIntoView({ block: 'center', inline: 'nearest' })+ }, 0)}- }, []);+ }, [])return (<divref={(node) => {if (argDate >= nowDate) {- drop(node);+ drop(node)}- cellRef.current = node;+ cellRef.current = node}}className={[- "calendarTimingItem--js",+ 'calendarTimingItem--js',styles.calendarTimingItem,- argDate < nowDate ? styles.calendarTimingItemPast : "",- isOver ? styles.calendarTimingItem_over : "",- ].join(" ")}+ argDate < nowDate ? styles.calendarTimingItemPast : '',+ isOver ? styles.calendarTimingItem_over : '',+ ].join(' ')}><div className="calendarTimingItem-top"><div className="calendarTimingItem-top-day">@@ -117,90 +120,101 @@ const CalendarTimingItem = memo(size="small"icon={<PlusOutlined />}onClick={() => {- const days = dayjs(arg.date);- const today = dayjs();+ const days = dayjs(arg.date)+ const today = dayjs()if (today.date() === days.date()) {- onClickPub(today.add(10, "minute").format());- } else {- onClickPub(days.format());+ onClickPub(today.add(10, 'minute').format())+ }+ else {+ onClickPub(days.format())}}}/>)}</div>- {loading ? (- <>- <Skeleton.Button active={true} block={true} size="small" />- </>- ) : (- <div className="calendarTimingItem-con">- {argDate >= nowDate &&- reservationsTimesLast.map((v, i) => {- return (+ {loading+ ? (+ <>+ <Skeleton.Button active={true} block={true} size="small" />+ </>+ )+ : (+ <div className="calendarTimingItem-con">+ {argDate >= nowDate+ && reservationsTimesLast.map((v, i) => {+ return (+ <Button+ key={i}+ size="small"+ type="dashed"+ onClick={() => {+ const days = dayjs(arg.date)+ .set('hour', v[0])+ .set('minute', v[1])+ onClickPub(days.format())+ }}+ >+ <div className="calendarTimingItem-con-btn1">+ {v[0]}+ :+ {v[1]}+ {' '}+ PM+ </div>+ <div className="calendarTimingItem-con-btn2">+ {t('addPost')}+ </div>+ </Button>+ )+ })}+ {records+ && recordsLast.map((v) => {+ return (+ <div key={v.id + v.title + v.uid + v.updatedAt}>+ <CustomDragLayer publishRecord={v} snapToGrid={false} />+ <CalendarRecord publishRecord={v} />+ </div>+ )+ })}++ {records && records.length > 3 - reservationsTimesLast.length && (<Button- key={i}- size="small"- type="dashed"+ type="text"+ style={{+ height: 'auto',+ width: 'auto',+ padding: '3px 10px',+ fontSize: 'var(--fs-sm)',+ marginBottom: '0',+ }}onClick={() => {- const days = dayjs(arg.date)- .set("hour", v[0])- .set("minute", v[1]);- onClickPub(days.format());+ setIsMore(!isMore)}}>- <div className="calendarTimingItem-con-btn1">- {v[0]}:{v[1]} PM- </div>- <div className="calendarTimingItem-con-btn2">- {t("addPost")}- </div>+ {isMore+ ? (+ <>+ <UpOutlined style={{ marginRight: '8px' }} />+ 隐藏更多+ </>+ )+ : (+ <>+ <DownOutlined style={{ marginRight: '8px' }} />+ {records.length - recordsLast?.length}+ {' '}+ 更多+ </>+ )}</Button>- );- })}- {records &&- recordsLast.map((v) => {- return (- <div key={v.id + v.title + v.uid + v.updatedAt}>- <CustomDragLayer publishRecord={v} snapToGrid={false} />- <CalendarRecord publishRecord={v} />- </div>- );- })}-- {records && records.length > 3 - reservationsTimesLast.length && (- <Button- type="text"- style={{- height: "auto",- width: "auto",- padding: "3px 10px",- fontSize: "var(--fs-sm)",- marginBottom: "0",- }}- onClick={() => {- setIsMore(!isMore);- }}- >- {isMore ? (- <>- <UpOutlined style={{ marginRight: "8px" }} />- 隐藏更多- </>- ) : (- <>- <DownOutlined style={{ marginRight: "8px" }} />- {records.length - recordsLast?.length} 更多- </>)}- </Button>+ </div>)}- </div>- )}</div>- );+ )},),-);+)-export default CalendarTimingItem;+export default CalendarTimingItemdiff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/ListMode/QueueItem.tsx b/project/web/src/app/[lng]/accounts/components/CalendarTiming/ListMode/QueueItem.tsxindex 279893a8..b1b70efc 100644--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/ListMode/QueueItem.tsx+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/ListMode/QueueItem.tsx@@ -1,89 +1,90 @@-import { memo } from "react";-import { Avatar, Button, Tag } from "antd";-import {- CheckCircleOutlined,- ClockCircleOutlined,- CloseCircleOutlined,+import type { PublishRecordItem } from '@/api/plat/types/publish.types'+import {+ CheckCircleOutlined,+ ClockCircleOutlined,+ CloseCircleOutlined,LoadingOutlined,- SendOutlined,MessageOutlined,- UserOutlined-} from "@ant-design/icons";-import { PublishRecordItem, PublishStatus } from "@/api/plat/types/publish.types";-import { AccountPlatInfoMap } from "@/app/config/platConfig";-import { useAccountStore } from "@/store/account";-import { useShallow } from "zustand/react/shallow";-import { getOssUrl } from "@/utils/oss";-import { getDays } from "@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils";-import { useTransClient } from "@/app/i18n/client";-import styles from "./queueItem.module.scss";+ SendOutlined,+ UserOutlined,+} from '@ant-design/icons'+import { Avatar, Button, Tag } from 'antd'+import { memo } from 'react'+import { useShallow } from 'zustand/react/shallow'+import { PublishStatus } from '@/api/plat/types/publish.types'+import { getDays } from '@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils'+import { AccountPlatInfoMap } from '@/app/config/platConfig'+import { useTransClient } from '@/app/i18n/client'+import { useAccountStore } from '@/store/account'+import { getOssUrl } from '@/utils/oss'+import styles from './queueItem.module.scss'interface QueueItemProps {- record: PublishRecordItem;- onRetry?: (record: PublishRecordItem) => void;- onEdit?: (record: PublishRecordItem) => void;- onMore?: (record: PublishRecordItem) => void;+ record: PublishRecordItem+ onRetry?: (record: PublishRecordItem) => void+ onEdit?: (record: PublishRecordItem) => void+ onMore?: (record: PublishRecordItem) => void}const QueueItem = memo(({ record, onRetry, onEdit, onMore }: QueueItemProps) => {- const { t } = useTransClient("publish");+ const { t } = useTransClient('publish')const { accountMap, accountActive } = useAccountStore(- useShallow((state) => ({+ useShallow(state => ({accountMap: state.accountMap,accountActive: state.accountActive,})),- );+ )- const account = accountMap.get(record.accountId);- const platInfo = AccountPlatInfoMap.get(record.accountType);- const days = getDays(record.publishTime);+ const account = accountMap.get(record.accountId)+ const platInfo = AccountPlatInfoMap.get(record.accountType)+ const days = getDays(record.publishTime)const getStatusInfo = () => {switch (record.status) {case PublishStatus.FAIL:return {- color: "error",- text: t("status.publishFailed"),- icon: <CloseCircleOutlined />- };+ color: 'error',+ text: t('status.publishFailed'),+ icon: <CloseCircleOutlined />,+ }case PublishStatus.PUB_LOADING:return {- color: "cyan",- text: t("status.publishing"),- icon: <LoadingOutlined />- };+ color: 'cyan',+ text: t('status.publishing'),+ icon: <LoadingOutlined />,+ }case PublishStatus.RELEASED:return {- color: "success",- text: t("status.publishSuccess"),- icon: <CheckCircleOutlined />- };+ color: 'success',+ text: t('status.publishSuccess'),+ icon: <CheckCircleOutlined />,+ }case PublishStatus.UNPUBLISH:return {- color: "processing",- text: t("status.waitingPublish"),- icon: <ClockCircleOutlined />- };+ color: 'processing',+ text: t('status.waitingPublish'),+ icon: <ClockCircleOutlined />,+ }default:return {- color: "default",- text: t("status.unknown"),- icon: null- };+ color: 'default',+ text: t('status.unknown'),+ icon: null,+ }}- };+ }- const statusInfo = getStatusInfo();+ const statusInfo = getStatusInfo()return (<div className={styles.queueItem}>{/* 状态头部 */}<div className={styles.statusHeader}><div className={styles.statusInfo}>-+<div className={styles.dateTime}>- <span className={styles.date}>{days.format("MMM DD")}</span>- <span className={styles.time}>{days.format("h:mm A")}</span>+ <span className={styles.date}>{days.format('MMM DD')}</span>+ <span className={styles.time}>{days.format('h:mm A')}</span></div><span className={styles.statusText}>{statusInfo.text}</span></div>@@ -112,123 +113,125 @@ const QueueItem = memo(({ record, onRetry, onEdit, onMore }: QueueItemProps) =>{/* 主要内容区域 */}<div className={styles.contentArea}>- <div style={{display: 'flex', flexDirection: 'row', justifyContent: 'space-between', gap: '12px'}}>+ <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', gap: '12px' }}>- {/* 账户信息 */}+ {/* 账户信息 */}- <div style={{display: 'flex', flexDirection: 'column', gap: '12px'}}>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>- <div className={styles.accountInfo}>- <div className={styles.avatarContainer}>+ <div className={styles.accountInfo}>+ <div className={styles.avatarContainer}>- <Avatar- size={40}- src={getOssUrl(accountActive?.avatar || "")}- className={styles.avatar}- >- {accountActive?.nickname?.charAt(0) || accountActive?.account?.charAt(0)}- </Avatar>+ <Avatar+ size={40}+ src={getOssUrl(accountActive?.avatar || '')}+ className={styles.avatar}+ >+ {accountActive?.nickname?.charAt(0) || accountActive?.account?.charAt(0)}+ </Avatar>- {/* <Avatar+ {/* <Avatarsrc={getOssUrl(account?.avatar || "")}icon={!account?.avatar ? <UserOutlined /> : undefined}className={styles.avatar}/> */}- <div className={styles.platformIcon}>- <img- src={platInfo?.icon}- alt="platform"- className={styles.platIcon}- />- </div>- </div>- <div className={styles.accountDetails}>- <div className={styles.accountName}>{account?.nickname}</div>- <div className={styles.accountHandle}>@{account?.account}</div>- </div>-- </div>-- <div className={styles.postText}>{record.desc}</div>- </div>--- {/* 发布内容 */}- <div className={styles.postContent}>--- {/* 媒体内容 */}- {(record.coverUrl || record.imgUrlList?.length > 0) && (- <div className={styles.mediaContainer}>- {record.videoUrl ? (- <div className={styles.videoThumbnail}>- <img- src={getOssUrl(record.coverUrl || "")}- alt="video thumbnail"- className={styles.mediaImage}+ <div className={styles.platformIcon}>+ <img+ src={platInfo?.icon}+ alt="platform"+ className={styles.platIcon}/>- <div className={styles.playButton}>- <div className={styles.playIcon}>▶</div>- </div></div>- ) : (- <div className={styles.imageContainer}>- <img- src={getOssUrl(record.coverUrl || record.imgUrlList?.[0] || "")}- alt="post image"- className={styles.mediaImage}- />+ </div>+ <div className={styles.accountDetails}>+ <div className={styles.accountName}>{account?.nickname}</div>+ <div className={styles.accountHandle}>+ @+ {account?.account}</div>- )}+ </div>+</div>- )}- </div>+ <div className={styles.postText}>{record.desc}</div>+ </div>++ {/* 发布内容 */}+ <div className={styles.postContent}>++ {/* 媒体内容 */}+ {(record.coverUrl || record.imgUrlList?.length > 0) && (+ <div className={styles.mediaContainer}>+ {record.videoUrl+ ? (+ <div className={styles.videoThumbnail}>+ <img+ src={getOssUrl(record.coverUrl || '')}+ alt="video thumbnail"+ className={styles.mediaImage}+ />+ <div className={styles.playButton}>+ <div className={styles.playIcon}>▶</div>+ </div>+ </div>+ )+ : (+ <div className={styles.imageContainer}>+ <img+ src={getOssUrl(record.coverUrl || record.imgUrlList?.[0] || '')}+ alt="post image"+ className={styles.mediaImage}+ />+ </div>+ )}+ </div>+ )}++ </div></div>--</div>{/* 底部信息 */}<div className={styles.footer}><div className={styles.creationInfo}>- {t("creationInfo", { date: days.format("YYYY-MM-DD") })}+ {t('creationInfo', { date: days.format('YYYY-MM-DD') })}</div><div className={styles.actionButtons}>{record.status === PublishStatus.UNPUBLISH && (- <Button- type="primary"+ <Button+ type="primary"icon={<SendOutlined />}onClick={() => onRetry?.(record)}className={styles.retryButton}>- {t("buttons.publishNow")}+ {t('buttons.publishNow')}</Button>)}{record.workLink && (- <Button+ <Buttonicon={<SendOutlined />}onClick={async () => {try {- await navigator.clipboard.writeText(record.workLink);+ await navigator.clipboard.writeText(record.workLink)// 可以添加一个提示消息- } catch (err) {- console.error('复制链接失败:', err);+ }+ catch (err) {+ console.error('复制链接失败:', err)}}}className={styles.copyButton}>- {t("buttons.copyLink")}+ {t('buttons.copyLink')}</Button>)}</div></div></div>- );-});+ )+})-QueueItem.displayName = "QueueItem";+QueueItem.displayName = 'QueueItem'-export default QueueItem;+export default QueueItemdiff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/ListMode/SentList.tsx b/project/web/src/app/[lng]/accounts/components/CalendarTiming/ListMode/SentList.tsxindex 9abe8e21..79891703 100644--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/ListMode/SentList.tsx+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/ListMode/SentList.tsx@@ -1,156 +1,146 @@-import React, { useEffect, useState, useMemo } from 'react';-import { List, Card, Avatar, Typography, Space, Tag, Button, Skeleton, Empty } from 'antd';-import { EyeOutlined, LikeOutlined, MessageOutlined, ShareAltOutlined, HeartOutlined, BarChartOutlined, AimOutlined, EyeInvisibleOutlined } from '@ant-design/icons';-import { useTransClient } from '@/app/i18n/client';-import { getSentPosts } from '@/api/sent';-import { SentPost } from '@/api/types/sent.types';-import styles from './listMode.module.scss';-import { PublishStatus } from '@/api/plat/types/publish.types';-import dayjs from 'dayjs';-import { useAccountStore } from '@/store/account';-import { useShallow } from 'zustand/react/shallow';-import { getOssUrl } from '@/utils/oss';-import { AccountPlatInfoMap } from '@/app/config/platConfig';+import type { SentPost } from '@/api/types/sent.types'+import { AimOutlined, BarChartOutlined, EyeInvisibleOutlined, EyeOutlined, HeartOutlined, LikeOutlined, MessageOutlined, ShareAltOutlined } from '@ant-design/icons'+import { Avatar, Button, Card, Empty, List, Skeleton, Space, Tag, Typography } from 'antd'+import dayjs from 'dayjs'+import React, { useEffect, useMemo, useState } from 'react'+import { useShallow } from 'zustand/react/shallow'+import { getSentPosts } from '@/api/sent'+import { AccountPlatInfoMap } from '@/app/config/platConfig'+import { useTransClient } from '@/app/i18n/client'+import { useAccountStore } from '@/store/account'+import { getOssUrl } from '@/utils/oss'+import styles from './listMode.module.scss'-const { Text, Title } = Typography;+const { Text, Title } = Typographyinterface SentListProps {- platform: string;- uid: string;- onDataChange?: (count: number) => void;+ platform: string+ uid: string+ onDataChange?: (count: number) => voidaccountInfo?: {- avatar: string;- nickname: string;- account: string;- };+ avatar: string+ nickname: string+ account: string+ }}const SentList: React.FC<SentListProps> = ({ platform, uid, onDataChange, accountInfo }) => {- const { t } = useTransClient("account");- const [posts, setPosts] = useState<SentPost[]>([]);- const [loading, setLoading] = useState(false);- const [hasMore, setHasMore] = useState(false);- const [page, setPage] = useState(1);+ const { t } = useTransClient('account')+ const [posts, setPosts] = useState<SentPost[]>([])+ const [loading, setLoading] = useState(false)+ const [hasMore, setHasMore] = useState(false)+ const [page, setPage] = useState(1)- // 获取账户列表用于映射+ // Get account list for mappingconst { accountList } = useAccountStore(- useShallow((state) => ({+ useShallow(state => ({accountList: state.accountList,})),- );+ )- // 创建 accountId 到账户信息的映射+ // Create mapping from accountId to account informationconst accountMap = useMemo(() => {- const map = new Map();- accountList.forEach(account => {- map.set(account.id, account);- });- return map;- }, [accountList]);+ const map = new Map()+ accountList.forEach((account) => {+ map.set(account.id, account)+ })+ return map+ }, [accountList])const loadPosts = async (pageNum: number = 1, append: boolean = false) => {- setLoading(true);+ setLoading(true)try {- // 构建请求参数,如果没有 platform 和 uid 就不传+ // Build request parameters, if platform and uid are not passed, don't passconst params: any = {- // page: pageNum,- // pageSize: 20-- status: PublishStatus.RELEASED,- // 开始时间:一个月前;结束时间:现在time: [dayjs().subtract(1, 'month').utc().format(), dayjs().utc().format()],- };-+ }+if (platform) {- params.accountType = platform;+ params.accountType = platform}-+if (uid) {- params.uid = uid;+ params.uid = uid}-- const response = await getSentPosts(params);-- // 处理新的API响应格式- const responseData = (response as any)?.data || response;-- console.log('SentList API Response:', {- code: (response as any)?.code,- message: (response as any)?.message,- data: responseData,- params- });-- // 处理响应数据,直接使用responseData作为数组- const postsData = Array.isArray(responseData) ? responseData : (responseData?.posts || responseData?.list || []);-++ const response = await getSentPosts(params)++ // Handle new API response format+ const responseData = (response as any)?.data || response++ // Handle response data, directly use responseData as an array+ const postsData = Array.isArray(responseData) ? responseData : (responseData?.posts || responseData?.list || [])+if (append) {- setPosts(prev => [...prev, ...postsData]);- } else {- setPosts(postsData);+ setPosts(prev => [...prev, ...postsData])}- setHasMore(responseData?.hasMore || false);-- // 通知父组件数据变化+ else {+ setPosts(postsData)+ }+ setHasMore(responseData?.hasMore || false)++ // Notify parent component of data changeif (onDataChange) {- onDataChange(responseData?.total || postsData.length);+ onDataChange(responseData?.total || postsData.length)}- } catch (error) {- console.error('Failed to load sent posts:', error);- // 发生错误时重置数据+ }+ catch (error) {+ console.error('Failed to load sent posts:', error)+ // When an error occurs, reset dataif (!append) {- setPosts([]);- setHasMore(false);+ setPosts([])+ setHasMore(false)if (onDataChange) {- onDataChange(0);+ onDataChange(0)}}- } finally {- setLoading(false);}- };+ finally {+ setLoading(false)+ }+ }useEffect(() => {- // 进入页面就调用,不管有没有 platform 和 uid- loadPosts(1, false);- }, [platform, uid]);+ // Enter the page and call it, regardless of whether there is platform and uid+ loadPosts(1, false)+ }, [platform, uid])const loadMore = () => {- const nextPage = page + 1;- setPage(nextPage);- loadPosts(nextPage, true);- };+ const nextPage = page + 1+ setPage(nextPage)+ loadPosts(nextPage, true)+ }const formatTime = (timestamp: string | number) => {- const date = typeof timestamp === 'string' ? new Date(timestamp) : new Date(timestamp);+ const date = typeof timestamp === 'string' ? new Date(timestamp) : new Date(timestamp)return {date: date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' }),- time: date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false })- };- };+ time: date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false }),+ }+ }const getMediaTypeTag = (mediaType: string) => {const typeMap = {video: { color: 'red', text: '视频' },image: { color: 'blue', text: '图片' },- article: { color: 'green', text: '文章' }- };- return typeMap[mediaType as keyof typeof typeMap] || { color: 'default', text: mediaType };- };+ article: { color: 'green', text: '文章' },+ }+ return typeMap[mediaType as keyof typeof typeMap] || { color: 'default', text: mediaType }+ }const renderPostItem = (post: SentPost) => {- // 根据 accountId 获取账户信息- const account = accountMap.get(post.accountId);- const platInfo = AccountPlatInfoMap.get(post.accountType as any);-- const timeInfo = formatTime(post.publishTime);- const postTime = typeof post.publishTime === 'string' ? new Date(post.publishTime).getTime() : post.publishTime;- const daysAgo = Math.floor((Date.now() - postTime) / (1000 * 60 * 60 * 24));+ // Get account information based on accountId+ const account = accountMap.get(post.accountId)+ const platInfo = AccountPlatInfoMap.get(post.accountType as any)++ const timeInfo = formatTime(post.publishTime)+ const postTime = typeof post.publishTime === 'string' ? new Date(post.publishTime).getTime() : post.publishTime+ const daysAgo = Math.floor((Date.now() - postTime) / (1000 * 60 * 60 * 24))return (<div key={post.id} className={styles.sentPostItem}><div className={styles.postCard}>- {/* 日期时间头部 */}+ {/* Date time header */}<div className={styles.postDateHeader}><div className={styles.dateTime}><span className={styles.dateText}>{timeInfo.date}</span>@@ -158,13 +148,13 @@ const SentList: React.FC<SentListProps> = ({ platform, uid, onDataChange, accoun</div></div>- {/* 帖子内容 */}+ {/* Post content */}<div className={styles.postContent}>- {/* 用户信息 */}+ {/* User information */}<div className={styles.userInfo}>- <Avatar- size={40}- src={getOssUrl(account?.avatar || '')}+ <Avatar+ size={40}+ src={getOssUrl(account?.avatar || '')}className={styles.userAvatar}>{account?.nickname?.charAt(0) || account?.account?.charAt(0) || post.title?.charAt(0) || '?'}@@ -180,22 +170,19 @@ const SentList: React.FC<SentListProps> = ({ platform, uid, onDataChange, accoun<span>{platInfo?.name || post.accountType}</span></div></div>- {/* <div className={styles.chatIcon}>💬</div> */}</div>- {/* 帖子文本 */}+ {/* Post text */}<div className={styles.postText}>{post.desc}</div>--- {/* 媒体内容 */}+ {/* Media content */}{post.coverUrl && (<div className={styles.mediaContainer}><div className={styles.mediaWrapper}>- <img- src={post.coverUrl}+ <img+ src={post.coverUrl}alt={post.title || post.desc}className={styles.mediaImage}/>@@ -208,7 +195,7 @@ const SentList: React.FC<SentListProps> = ({ platform, uid, onDataChange, accoun</div>)}- {/* 互动数据 */}+ {/* Interactive data */}<div className={styles.engagementMetrics}><div className={styles.metricsRow}><div className={styles.metricItem}>@@ -250,22 +237,24 @@ const SentList: React.FC<SentListProps> = ({ platform, uid, onDataChange, accoun</div></div>- {/* 底部信息 */}+ {/* Bottom information */}<div className={styles.postFooter}><div className={styles.creationInfo}>{t('listMode.createdDaysAgo' as any, { days: daysAgo })}</div><div className={styles.actionButtons}>- <Button- type="link"+ <Button+ type="link"size="small"className={styles.viewPostBtn}onClick={() => window.open(post.workLink, '_blank')}>- {t('listMode.viewPost' as any)} ↗️+ {t('listMode.viewPost' as any)}+ {' '}+ ↗️</Button>- <Button- type="text"+ <Button+ type="text"size="small"className={styles.moreBtn}>@@ -276,13 +265,13 @@ const SentList: React.FC<SentListProps> = ({ platform, uid, onDataChange, accoun</div></div></div>- );- };+ )+ }- // 过滤掉无法在账户列表中匹配到的数据+ // Filter out data that cannot be matched in the account listconst validPosts = useMemo(() => {- return posts.filter(post => accountMap.has(post.accountId));- }, [posts, accountMap]);+ return posts.filter(post => accountMap.has(post.accountId))+ }, [posts, accountMap])if (loading && posts.length === 0) {return (@@ -293,37 +282,39 @@ const SentList: React.FC<SentListProps> = ({ platform, uid, onDataChange, accoun<Skeleton active paragraph={{ rows: 3 }} /></div></div>- );+ )}return (<div className={styles.sentList}>- {validPosts.length > 0 ? (- <>- <div className={styles.postsContainer}>- {validPosts.map(renderPostItem)}- </div>- {hasMore && (- <div className={styles.loadMoreContainer}>- <Button- loading={loading}- onClick={loadMore}- className={styles.loadMoreButton}- >- 加载更多- </Button>+ {validPosts.length > 0+ ? (+ <>+ <div className={styles.postsContainer}>+ {validPosts.map(renderPostItem)}+ </div>+ {hasMore && (+ <div className={styles.loadMoreContainer}>+ <Button+ loading={loading}+ onClick={loadMore}+ className={styles.loadMoreButton}+ >+ Load more...+ </Button>+ </div>+ )}+ </>+ )+ : (+ <div className={styles.emptyState}>+ <Empty+ description={t('listMode.noSentPosts' as any)}+ /></div>)}- </>- ) : (- <div className={styles.emptyState}>- <Empty- description={t('listMode.noSentPosts' as any)}- />- </div>- )}</div>- );-};+ )+}-export default SentList;+export default SentListdiff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/ListMode/index.tsx b/project/web/src/app/[lng]/accounts/components/CalendarTiming/ListMode/index.tsxindex 5777e458..7d1f2033 100644--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/ListMode/index.tsx+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/ListMode/index.tsx@@ -1,42 +1,43 @@-import { ForwardedRef, forwardRef, memo, useState } from "react";-import styles from "./listMode.module.scss";-import { Skeleton, Empty, Tabs } from "antd";-import { useTransClient } from "@/app/i18n/client";-import { useCalendarTiming } from "@/app/[lng]/accounts/components/CalendarTiming/useCalendarTiming";-import { useShallow } from "zustand/react/shallow";-import { PublishRecordItem } from "@/api/plat/types/publish.types";-import { HTML5Backend } from "react-dnd-html5-backend";-import { DndProvider } from "react-dnd";-import SentList from "./SentList";-import QueueItem from "./QueueItem";-import { useAccountStore } from "@/store/account";+import type { ForwardedRef } from 'react'+import type { PublishRecordItem } from '@/api/plat/types/publish.types'+import { Empty, Skeleton, Tabs } from 'antd'+import { forwardRef, memo, useState } from 'react'+import { DndProvider } from 'react-dnd'+import { HTML5Backend } from 'react-dnd-html5-backend'+import { useShallow } from 'zustand/react/shallow'+import { useCalendarTiming } from '@/app/[lng]/accounts/components/CalendarTiming/useCalendarTiming'+import { useTransClient } from '@/app/i18n/client'+import { useAccountStore } from '@/store/account'+import styles from './listMode.module.scss'+import QueueItem from './QueueItem'+import SentList from './SentList'export interface IListModeRef {}export interface IListModeProps {- onClickPub?: (date: string) => void;+ onClickPub?: (date: string) => void}const ListMode = memo(forwardRef(({ onClickPub }: IListModeProps, ref: ForwardedRef<IListModeRef>) => {- const { t } = useTransClient("account");+ const { t } = useTransClient('account')const { recordMap, listLoading } = useCalendarTiming(- useShallow((state) => ({+ useShallow(state => ({recordMap: state.recordMap,listLoading: state.listLoading,})),- );+ )const { accountActive } = useAccountStore(- useShallow((state) => ({+ useShallow(state => ({accountActive: state.accountActive,})),- );+ )- const [sentCount, setSentCount] = useState(0);+ const [sentCount, setSentCount] = useState(0)// 将所有记录转换为列表格式,保持后端原始顺序- const queueRecords = Array.from(recordMap.values()).flat();+ const queueRecords = Array.from(recordMap.values()).flat()const renderRecordItem = (record: PublishRecordItem) => {return (@@ -45,19 +46,19 @@ const ListMode = memo(record={record}onRetry={(record) => {// TODO: 实现重试逻辑- console.log('Retry record:', record);+ console.log('Retry record:', record)}}onEdit={(record) => {// TODO: 实现编辑逻辑- console.log('Edit record:', record);+ console.log('Edit record:', record)}}onMore={(record) => {// TODO: 实现更多操作逻辑- console.log('More actions for record:', record);+ console.log('More actions for record:', record)}}/>- );- };+ )+ }if (listLoading) {return (@@ -68,57 +69,66 @@ const ListMode = memo(</div></div><div className={styles.listContent}>- {[1, 2, 3, 4, 5].map((i) => (+ {[1, 2, 3, 4, 5].map(i => (<div key={i} className={styles.skeletonItem}><Skeleton active /></div>))}</div></div>- );+ )}-const queueTabContent = (<div className={styles.tabContent}><DndProvider backend={HTML5Backend}>- {queueRecords.length > 0 ? (- <div className={styles.queueList}>- {queueRecords.map(renderRecordItem)}- </div>- ) : (- <Empty- description={t('listMode.noRecords' as any)}- className={styles.emptyState}- />- )}+ {queueRecords.length > 0+ ? (+ <div className={styles.queueList}>+ {queueRecords.map(renderRecordItem)}+ </div>+ )+ : (+ <Empty+ description={t('listMode.noRecords' as any)}+ className={styles.emptyState}+ />+ )}</DndProvider></div>- );+ )const sentTabContent = (- <SentList+ <SentListplatform={accountActive?.type || ''}uid={accountActive?.uid || ''}onDataChange={setSentCount}- accountInfo={accountActive ? {- avatar: accountActive.avatar,- nickname: accountActive.nickname,- account: accountActive.account- } : undefined}+ accountInfo={accountActive+ ? {+ avatar: accountActive.avatar,+ nickname: accountActive.nickname,+ account: accountActive.account,+ }+ : undefined}/>- );+ )- const tabItems = [+ const tabItems = [{key: 'queue',label: (<div className={styles.tabLabel}><span>{t('listMode.queue' as any)}</span>- {queueRecords.length>0?<span className={styles.tabBadge}>- {queueRecords.length}- </span>:<span className={styles.tabBadgeNone}>- </span>}+ {queueRecords.length > 0+ ? (+ <span className={styles.tabBadge}>+ {queueRecords.length}+ </span>+ )+ : (+ <span className={styles.tabBadgeNone}>+ </span>+ )}</div>),children: queueTabContent,@@ -128,12 +138,12 @@ const ListMode = memo(label: (<div className={styles.tabLabel}><span>{t('listMode.sent' as any)}</span>- {sentCount>0?<span className={styles.tabBadge}>{sentCount}</span>:''}+ {sentCount > 0 ? <span className={styles.tabBadge}>{sentCount}</span> : ''}</div>),children: sentTabContent,},- ];+ ]return (<div className={styles.listMode}>@@ -143,9 +153,9 @@ const ListMode = memo(size="small"/></div>- );+ )},),-);+)-export default ListMode;\ No newline at end of file+export default ListModediff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/ListMode/listMode.module.scss b/project/web/src/app/[lng]/accounts/components/CalendarTiming/ListMode/listMode.module.scssindex 048ff2e6..acb6ebff 100644--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/ListMode/listMode.module.scss+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/ListMode/listMode.module.scss@@ -226,7 +226,7 @@.searchInput {width: 100%;-+:global {.ant-input {border-radius: 6px;@@ -718,7 +718,7 @@.loadingContainer {padding: 20px 0;-+:global {.ant-skeleton {margin-bottom: 20px;@@ -726,4 +726,4 @@}}}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/calendarTiming.module.scss b/project/web/src/app/[lng]/accounts/components/CalendarTiming/calendarTiming.module.scssindex e56afa90..390c09a6 100644--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/calendarTiming.module.scss+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/calendarTiming.module.scss@@ -25,7 +25,6 @@}}&-options {-}}@@ -36,7 +35,8 @@margin: 0 15px 0 10px;font-size: 18px;}- &-left, &-right {+ &-left,+ &-right {display: flex;align-items: center;margin-bottom: 10px;@@ -51,12 +51,12 @@.ant-tabs-tab {padding: 4px 12px;font-size: var(--fs-sm);-+.anticon {margin-right: 4px;}}-+.ant-tabs-tab-active {background: var(--colorPrimary1);border-radius: 6px;@@ -120,7 +120,9 @@.slideLeftEnterActive {opacity: 1;transform: translateX(0);- transition: opacity 300ms, transform 300ms;+ transition:+ opacity 300ms,+ transform 300ms;}.slideLeftExit {opacity: 1;@@ -129,7 +131,9 @@.slideLeftExitActive {opacity: 0;transform: translateX(-50px);- transition: opacity 300ms, transform 300ms;+ transition:+ opacity 300ms,+ transform 300ms;}.slideRightEnter {opacity: 0;@@ -138,7 +142,9 @@.slideRightEnterActive {opacity: 1;transform: translateX(0);- transition: opacity 300ms, transform 300ms;+ transition:+ opacity 300ms,+ transform 300ms;}.slideRightExit {opacity: 1;@@ -147,7 +153,9 @@.slideRightExitActive {opacity: 0;transform: translateX(50px);- transition: opacity 300ms, transform 300ms;+ transition:+ opacity 300ms,+ transform 300ms;}.fadeEnter {opacity: 0;@@ -258,7 +266,7 @@.searchInput {width: 100%;-+:global {.ant-input {border-radius: 6px;@@ -354,4 +362,4 @@font-size: 14px;padding: 40px 16px;}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils.ts b/project/web/src/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils.tsindex bb949674..7e3ea9d2 100644--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils.ts+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils.ts@@ -1,55 +1,57 @@-import styles from "./calendarTiming.module.scss";-import dayjs from "dayjs";-import utc from "dayjs/plugin/utc";-import timezone from "dayjs/plugin/timezone";+import dayjs from 'dayjs'+import timezone from 'dayjs/plugin/timezone'+import utc from 'dayjs/plugin/utc'+import styles from './calendarTiming.module.scss'-dayjs.extend(utc);-dayjs.extend(timezone);+dayjs.extend(utc)+dayjs.extend(timezone)// 日历国际化-export const getFullCalendarLang = (lang: string) => {+export function getFullCalendarLang(lang: string) {switch (lang) {- case "zh-CN":- return "zh-cn";- case "en":- return "en-gb";+ case 'zh-CN':+ return 'zh-cn'+ case 'en':+ return 'en-gb'}- return "en-gb";-};+ return 'en-gb'+}// 封装classNames切换方法-export function getTransitionClassNames(direction: "left" | "right" | "fade") {- if (direction === "left") {+export function getTransitionClassNames(direction: 'left' | 'right' | 'fade') {+ if (direction === 'left') {return {enter: styles.slideLeftEnter,enterActive: styles.slideLeftEnterActive,exit: styles.slideLeftExit,exitActive: styles.slideLeftExitActive,- };- } else if (direction === "right") {+ }+ }+ else if (direction === 'right') {return {enter: styles.slideRightEnter,enterActive: styles.slideRightEnterActive,exit: styles.slideRightExit,exitActive: styles.slideRightExitActive,- };- } else {+ }+ }+ else {// fade 动画return {enter: styles.fadeEnter,enterActive: styles.fadeEnterActive,exit: styles.fadeExit,exitActive: styles.fadeExitActive,- };+ }}}// 获取UTC daysexport function getUtcDays(date: dayjs.ConfigType) {- return dayjs(date).utc();+ return dayjs(date).utc()}// 获取当前时区的daysexport function getDays(date?: dayjs.ConfigType) {- return dayjs(date);+ return dayjs(date)}diff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/index.tsx b/project/web/src/app/[lng]/accounts/components/CalendarTiming/index.tsxindex b7440106..c156dca0 100644--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/index.tsx+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/index.tsx@@ -1,49 +1,52 @@-import {+import type { DatesSetArg } from '@fullcalendar/core'+import type {ForwardedRef,+} from 'react'+import type { IPublishDialogRef } from '@/components/PublishDialog'+import {+ CalendarOutlined,+ DownOutlined,+ LeftOutlined,+ PlusOutlined,+ RightOutlined,+ SearchOutlined,+ UnorderedListOutlined,+} from '@ant-design/icons'+import dayGridPlugin from '@fullcalendar/daygrid'+import FullCalendar from '@fullcalendar/react'+import { Avatar, Button, Dropdown, Input, Tabs } from 'antd'+import dayjs from 'dayjs'+import { useSearchParams } from 'next/navigation'+import {forwardRef,memo,useEffect,useRef,useState,-} from "react";-import { useSearchParams } from "next/navigation";-import styles from "./calendarTiming.module.scss";-import FullCalendar from "@fullcalendar/react";-import dayGridPlugin from "@fullcalendar/daygrid";-import { useGetClientLng } from "@/hooks/useSystem";+} from 'react'+import { DndProvider } from 'react-dnd'+import { HTML5Backend } from 'react-dnd-html5-backend'+import { CSSTransition } from 'react-transition-group'+import { useShallow } from 'zustand/react/shallow'+import AllPlatIcon from '@/app/[lng]/accounts/components/CalendarTiming/AllPlatIcon'import {getDays,getFullCalendarLang,getTransitionClassNames,-} from "@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils";-import { CSSTransition } from "react-transition-group";-import { DatesSetArg } from "@fullcalendar/core";-import { Button, Tabs, Input, Avatar, Dropdown } from "antd";-import {- LeftOutlined,- PlusOutlined,- RightOutlined,- CalendarOutlined,- UnorderedListOutlined,- SearchOutlined,- DownOutlined,-} from "@ant-design/icons";-import { useTransClient } from "@/app/i18n/client";-import CalendarTimingItem from "@/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem";-import PublishDialog, { IPublishDialogRef } from "@/components/PublishDialog";-import { useAccountStore } from "@/store/account";-import { useShallow } from "zustand/react/shallow";-import { AccountPlatInfoMap } from "@/app/config/platConfig";-import { getOssUrl } from "@/utils/oss";-import { AccountStatus } from "@/app/config/accountConfig";-import { HTML5Backend } from "react-dnd-html5-backend";-import { DndProvider } from "react-dnd";-import { useCalendarTiming } from "@/app/[lng]/accounts/components/CalendarTiming/useCalendarTiming";-import AvatarPlat from "@/components/AvatarPlat";-import AllPlatIcon from "@/app/[lng]/accounts/components/CalendarTiming/AllPlatIcon";-import ListMode from "@/app/[lng]/accounts/components/CalendarTiming/ListMode";-import { usePublishDialog } from "@/components/PublishDialog/usePublishDialog";-import dayjs from "dayjs";+} from '@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils'+import CalendarTimingItem from '@/app/[lng]/accounts/components/CalendarTiming/CalendarTimingItem'+import ListMode from '@/app/[lng]/accounts/components/CalendarTiming/ListMode'+import { useCalendarTiming } from '@/app/[lng]/accounts/components/CalendarTiming/useCalendarTiming'+import { AccountStatus } from '@/app/config/accountConfig'+import { AccountPlatInfoMap } from '@/app/config/platConfig'+import { useTransClient } from '@/app/i18n/client'+import AvatarPlat from '@/components/AvatarPlat'+import PublishDialog from '@/components/PublishDialog'+import { usePublishDialog } from '@/components/PublishDialog/usePublishDialog'+import { useGetClientLng } from '@/hooks/useSystem'+import { useAccountStore } from '@/store/account'+import { getOssUrl } from '@/utils/oss'+import styles from './calendarTiming.module.scss'export interface ICalendarTimingRef {}export interface ICalendarTimingProps {}@@ -51,256 +54,260 @@ export interface ICalendarTimingProps {}const CalendarTiming = memo(forwardRef(({}: ICalendarTimingProps, ref: ForwardedRef<ICalendarTimingRef>) => {- const lng = useGetClientLng();- const searchParams = useSearchParams();- const calendarRef = useRef<FullCalendar | null>(null);- const [animating, setAnimating] = useState(false);+ const lng = useGetClientLng()+ const searchParams = useSearchParams()+ const calendarRef = useRef<FullCalendar | null>(null)+ const [animating, setAnimating] = useState(false)// 方向:'left'(下月)、'right'(上月)、'fade' (今天)- const [direction, setDirection] = useState<"left" | "right" | "fade">(- "left",- );- const { t } = useTransClient("account");- const [currentDate, setCurrentDate] = useState<Date>(new Date());- const [activeMode, setActiveMode] = useState<"calendar" | "list">(- "calendar",- );+ const [direction, setDirection] = useState<'left' | 'right' | 'fade'>(+ 'left',+ )+ const { t } = useTransClient('account')+ const [currentDate, setCurrentDate] = useState<Date>(new Date())+ const [activeMode, setActiveMode] = useState<'calendar' | 'list'>(+ 'calendar',+ )const handleDatesSet = (arg: DatesSetArg) => {- const date = calendarRef.current?.getApi().getDate();+ const date = calendarRef.current?.getApi().getDate()if (date) {- setCurrentDate(date);+ setCurrentDate(date)}- };- const calendarTimingCalendarRef = useRef<HTMLDivElement>(null);- const [publishDialogOpen, setPublishDialogOpen] = useState(false);+ }+ const calendarTimingCalendarRef = useRef<HTMLDivElement>(null)+ const [publishDialogOpen, setPublishDialogOpen] = useState(false)const { accountList, accountActive, setAccountActive } = useAccountStore(- useShallow((state) => ({+ useShallow(state => ({accountList: state.accountList,accountActive: state.accountActive,setAccountActive: state.setAccountActive,})),- );+ )// 频道筛选相关状态- const [channelSearchText, setChannelSearchText] = useState("");+ const [channelSearchText, setChannelSearchText] = useState('')// 筛选后的账户列表 - 只显示在线账户const filteredAccounts = accountList.filter(- (account) =>- account.status === AccountStatus.USABLE &&- (account.nickname+ account =>+ account.status === AccountStatus.USABLE+ && (account.nickname.toLowerCase()- .includes(channelSearchText.toLowerCase()) ||- account.account+ .includes(channelSearchText.toLowerCase())+ || account.account.toLowerCase().includes(channelSearchText.toLowerCase())),- );+ )// 处理账户选择 - 与 AccountSidebar 同步const handleChannelSelect = (account: any) => {- setAccountActive(account);- };+ setAccountActive(account)+ }// Channel 筛选器下拉菜单内容const channelDropdownContent = (<divstyle={{- width: "280px",- background: "white",- borderRadius: "8px",- boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)",- overflow: "hidden",+ width: '280px',+ background: 'white',+ borderRadius: '8px',+ boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',+ overflow: 'hidden',}}>- <div style={{ padding: "16px 16px 0 16px" }}>+ <div style={{ padding: '16px 16px 0 16px' }}><Input- placeholder={t("listMode.searchChannels" as any)}+ placeholder={t('listMode.searchChannels' as any)}prefix={<SearchOutlined />}value={channelSearchText}- onChange={(e) => setChannelSearchText(e.target.value)}- style={{ width: "100%" }}+ onChange={e => setChannelSearchText(e.target.value)}+ style={{ width: '100%' }}/></div><div- style={{ maxHeight: "300px", overflowY: "auto", padding: "8px 0" }}+ style={{ maxHeight: '300px', overflowY: 'auto', padding: '8px 0' }}>- {filteredAccounts.length > 0 ? (- filteredAccounts.map((account) => {- const platInfo = AccountPlatInfoMap.get(account.type);- return (- <div- key={account.id}- style={{- padding: "8px 16px",- cursor: "pointer",- transition: "all 0.2s ease",- borderBottom: "1px solid #f5f5f5",- backgroundColor:+ {filteredAccounts.length > 0+ ? (+ filteredAccounts.map((account) => {+ const platInfo = AccountPlatInfoMap.get(account.type)+ return (+ <div+ key={account.id}+ style={{+ padding: '8px 16px',+ cursor: 'pointer',+ transition: 'all 0.2s ease',+ borderBottom: '1px solid #f5f5f5',+ backgroundColor:accountActive?.id === account.id- ? "#e6f7ff"- : "transparent",- }}- onClick={() => handleChannelSelect(account)}- onMouseEnter={(e) => {- if (accountActive?.id !== account.id) {- e.currentTarget.style.backgroundColor = "#f5f5f5";- }- }}- onMouseLeave={(e) => {- if (accountActive?.id !== account.id) {- e.currentTarget.style.backgroundColor = "transparent";- }- }}- >- <div- style={{- display: "flex",- alignItems: "center",- gap: "12px",- }}- >- <Avatar- src={getOssUrl(account.avatar)}- size={32}- style={{ flexShrink: 0, border: "1px solid #f0f0f0" }}+ ? '#e6f7ff'+ : 'transparent',+ }}+ onClick={() => handleChannelSelect(account)}+ onMouseEnter={(e) => {+ if (accountActive?.id !== account.id) {+ e.currentTarget.style.backgroundColor = '#f5f5f5'+ }+ }}+ onMouseLeave={(e) => {+ if (accountActive?.id !== account.id) {+ e.currentTarget.style.backgroundColor = 'transparent'+ }+ }}>- {account.nickname?.[0] || account.account?.[0]}- </Avatar>- <div style={{ flex: 1, minWidth: 0 }}>- <div- style={{- fontSize: "14px",- color: "#333",- fontWeight: 500,- marginBottom: "4px",- overflow: "hidden",- textOverflow: "ellipsis",- whiteSpace: "nowrap",- }}- >- {account.nickname || account.account}- </div><divstyle={{- display: "flex",- alignItems: "center",- gap: "6px",- fontSize: "12px",- color: "#666",+ display: 'flex',+ alignItems: 'center',+ gap: '12px',}}>- <img- src={platInfo?.icon}- alt={platInfo?.name}- style={{- width: "16px",- height: "16px",- borderRadius: "2px",- }}- />- <span>{platInfo?.name}</span>+ <Avatar+ src={getOssUrl(account.avatar)}+ size={32}+ style={{ flexShrink: 0, border: '1px solid #f0f0f0' }}+ >+ {account.nickname?.[0] || account.account?.[0]}+ </Avatar>+ <div style={{ flex: 1, minWidth: 0 }}>+ <div+ style={{+ fontSize: '14px',+ color: '#333',+ fontWeight: 500,+ marginBottom: '4px',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}+ >+ {account.nickname || account.account}+ </div>+ <div+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: '6px',+ fontSize: '12px',+ color: '#666',+ }}+ >+ <img+ src={platInfo?.icon}+ alt={platInfo?.name}+ style={{+ width: '16px',+ height: '16px',+ borderRadius: '2px',+ }}+ />+ <span>{platInfo?.name}</span>+ </div>+ </div></div></div>- </div>- </div>- );- })- ) : (- <div- style={{- textAlign: "center",- color: "#999",- fontSize: "14px",- padding: "40px 16px",- }}- >- {accountList.length === 0- ? "暂无账户"- : accountList.filter(- (account) => account.status === AccountStatus.USABLE,+ )+ })+ )+ : (+ <div+ style={{+ textAlign: 'center',+ color: '#999',+ fontSize: '14px',+ padding: '40px 16px',+ }}+ >+ {accountList.length === 0+ ? '暂无账户'+ : accountList.filter(+ account => account.status === AccountStatus.USABLE,).length === 0- ? "暂无在线账户"- : t("listMode.noChannelsFound" as any)}- </div>- )}+ ? '暂无在线账户'+ : t('listMode.noChannelsFound' as any)}+ </div>+ )}</div></div>- );+ )// Channel 筛选器按钮const channelFilter = (<div- style={{ display: "flex", alignItems: "center", marginTop: "-15px" }}+ style={{ display: 'flex', alignItems: 'center', marginTop: '-15px' }}><Dropdownmenu={{- items: [{ key: "channelFilter", label: channelDropdownContent }],+ items: [{ key: 'channelFilter', label: channelDropdownContent }],}}- trigger={["click"]}+ trigger={['click']}placement="bottomRight"><Buttonstyle={{- height: "32px",- padding: "0 12px",- borderRadius: "6px",- border: "none",- background: "white",- transition: "all 0.2s ease",+ height: '32px',+ padding: '0 12px',+ borderRadius: '6px',+ border: 'none',+ background: 'white',+ transition: 'all 0.2s ease',}}><divstyle={{- display: "flex",- alignItems: "center",- gap: "8px",- paddingBottom: "2px",+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ paddingBottom: '2px',}}>- {accountActive ? (- <>- <Avatar- src={getOssUrl(accountActive.avatar)}- size={20}- style={{ flexShrink: 0 }}- >- {accountActive.nickname?.[0] ||- accountActive.account?.[0]}- </Avatar>- <span- style={{- fontSize: "14px",- color: "#333",- width: "52px",- overflow: "hidden",- textOverflow: "ellipsis",- whiteSpace: "nowrap",- }}- >- {accountActive.nickname || accountActive.account}- </span>- </>- ) : (- <span- style={{- fontSize: "14px",- color: "#333",- width: "80px",- overflow: "hidden",- textOverflow: "ellipsis",- whiteSpace: "nowrap",- }}- >- {t("listMode.selectChannel" as any)}- </span>- )}+ {accountActive+ ? (+ <>+ <Avatar+ src={getOssUrl(accountActive.avatar)}+ size={20}+ style={{ flexShrink: 0 }}+ >+ {accountActive.nickname?.[0]+ || accountActive.account?.[0]}+ </Avatar>+ <span+ style={{+ fontSize: '14px',+ color: '#333',+ width: '52px',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}+ >+ {accountActive.nickname || accountActive.account}+ </span>+ </>+ )+ : (+ <span+ style={{+ fontSize: '14px',+ color: '#333',+ width: '80px',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ }}+ >+ {t('listMode.selectChannel' as any)}+ </span>+ )}<DownOutlined- style={{ fontSize: "12px", color: "#666", flexShrink: 0 }}+ style={{ fontSize: '12px', color: '#666', flexShrink: 0 }}/></div></Button></Dropdown></div>- );+ )const {setCalendarCallWidth,listLoading,@@ -309,7 +316,7 @@ const CalendarTiming = memo(getPubRecord,getQueueRecord,} = useCalendarTiming(- useShallow((state) => ({+ useShallow(state => ({setCalendarCallWidth: state.setCalendarCallWidth,listLoading: state.listLoading,recordMap: state.recordMap,@@ -317,115 +324,117 @@ const CalendarTiming = memo(getQueueRecord: state.getQueueRecord,setCalendarRef: state.setCalendarRef,})),- );- const publishDialogRef = useRef<IPublishDialogRef>(null);+ )+ const publishDialogRef = useRef<IPublishDialogRef>(null)useEffect(() => {- setCalendarRef(calendarRef.current!);- window.addEventListener("resize", handleResize);- if (activeMode === "list") {- getQueueRecord(0);- } else {- getPubRecord();+ setCalendarRef(calendarRef.current!)+ window.addEventListener('resize', handleResize)+ if (activeMode === 'list') {+ getQueueRecord(0)+ }+ else {+ getPubRecord()}setTimeout(() => {- handleResize();- }, 1);+ handleResize()+ }, 1)// 清理事件监听- return () => window.removeEventListener("resize", handleResize);- }, []);+ return () => window.removeEventListener('resize', handleResize)+ }, [])// 监听 URL 参数,自动打开发布弹窗useEffect(() => {- const openPublish = searchParams.get("openPublish");- const fromSignIn = searchParams.get("fromSignIn");+ const openPublish = searchParams.get('openPublish')+ const fromSignIn = searchParams.get('fromSignIn')- if (openPublish === "true" && fromSignIn === "true") {- setPublishDialogOpen(true);+ if (openPublish === 'true' && fromSignIn === 'true') {+ setPublishDialogOpen(true)// 清除 URL 参数,避免刷新页面时重复打开- const url = new URL(window.location.href);- url.searchParams.delete("openPublish");- url.searchParams.delete("fromSignIn");- window.history.replaceState({}, "", url.toString());+ const url = new URL(window.location.href)+ url.searchParams.delete('openPublish')+ url.searchParams.delete('fromSignIn')+ window.history.replaceState({}, '', url.toString())}- }, [searchParams]);+ }, [searchParams])// 监听自定义事件,打开发布弹窗useEffect(() => {const handleOpenPublishDialog = (event: CustomEvent) => {if (event.detail?.fromSignIn) {- setPublishDialogOpen(true);+ setPublishDialogOpen(true)}- };+ }window.addEventListener(- "openPublishDialog",+ 'openPublishDialog',handleOpenPublishDialog as EventListener,- );+ )return () => {window.removeEventListener(- "openPublishDialog",+ 'openPublishDialog',handleOpenPublishDialog as EventListener,- );- };- }, []);+ )+ }+ }, [])useEffect(() => {- if (activeMode === "list") {- getQueueRecord(0);- } else {- getPubRecord();+ if (activeMode === 'list') {+ getQueueRecord(0)}- }, [accountActive, activeMode, getPubRecord, getQueueRecord]);+ else {+ getPubRecord()+ }+ }, [accountActive, activeMode, getPubRecord, getQueueRecord])// 处理窗口大小变化const handleResize = () => {setTimeout(() => {- const el = document.querySelector(".calendarTimingItem--js")!;- const style = window.getComputedStyle(el);- const paddingLeft = parseFloat(style.paddingLeft);- const paddingRight = parseFloat(style.paddingRight);+ const el = document.querySelector('.calendarTimingItem--js')!+ const style = window.getComputedStyle(el)+ const paddingLeft = Number.parseFloat(style.paddingLeft)+ const paddingRight = Number.parseFloat(style.paddingRight)- setCalendarCallWidth(el.clientWidth - (paddingLeft + paddingRight));- }, 100);- };+ setCalendarCallWidth(el.clientWidth - (paddingLeft + paddingRight))+ }, 100)+ }// 动画触发函数- const triggerAnimation = (dir: "left" | "right" | "fade") => {- calendarTimingCalendarRef.current!.scrollTop = 0;- setDirection(dir);- setAnimating(true);- };+ const triggerAnimation = (dir: 'left' | 'right' | 'fade') => {+ calendarTimingCalendarRef.current!.scrollTop = 0+ setDirection(dir)+ setAnimating(true)+ }// 点击上/下月按钮时const handlePrev = () => {- triggerAnimation("right");+ triggerAnimation('right')setTimeout(() => {- calendarRef.current?.getApi().prev();- setAnimating(false);- getPubRecord();- }, 300);- };+ calendarRef.current?.getApi().prev()+ setAnimating(false)+ getPubRecord()+ }, 300)+ }const handleNext = () => {- triggerAnimation("left");+ triggerAnimation('left')setTimeout(() => {- calendarRef.current?.getApi().next();- setAnimating(false);- getPubRecord();- }, 300);- };+ calendarRef.current?.getApi().next()+ setAnimating(false)+ getPubRecord()+ }, 300)+ }// 点击Today按钮时const handleToday = () => {- triggerAnimation("fade");+ triggerAnimation('fade')setTimeout(() => {- calendarRef.current?.getApi().today();- setAnimating(false);- getPubRecord();- }, 300);- };+ calendarRef.current?.getApi().today()+ setAnimating(false)+ getPubRecord()+ }, 300)+ }return (<div className={styles.calendarTiming}>@@ -435,57 +444,59 @@ const CalendarTiming = memo(open={publishDialogOpen}onClose={() => setPublishDialogOpen(false)}onPubSuccess={() => {- getPubRecord();+ getPubRecord()}}accounts={accountList}/><div className="calendarTiming-header"><div className="calendarTiming-header-user">- {!accountActive ? (- <>- <AllPlatIcon />- <div className="calendarTiming-header-user-details">- <div className="calendarTiming-header-user-details-name">- {t("allPlatforms")}- </div>- </div>- </>- ) : (- <>- <AvatarPlat- account={accountActive!}- avatarWidth={50}- width={18}- />- <div className="calendarTiming-header-user-details">- <div className="calendarTiming-header-user-details-name">- {accountActive.nickname}- </div>- </div>- </>- )}+ {!accountActive+ ? (+ <>+ <AllPlatIcon />+ <div className="calendarTiming-header-user-details">+ <div className="calendarTiming-header-user-details-name">+ {t('allPlatforms')}+ </div>+ </div>+ </>+ )+ : (+ <>+ <AvatarPlat+ account={accountActive!}+ avatarWidth={50}+ width={18}+ />+ <div className="calendarTiming-header-user-details">+ <div className="calendarTiming-header-user-details-name">+ {accountActive.nickname}+ </div>+ </div>+ </>+ )}</div><div className="calendarTiming-header-options"><Buttonsize="large"icon={<PlusOutlined />}onClick={() => {- setPublishDialogOpen(true);+ setPublishDialogOpen(true)usePublishDialog.getState().setPubTime(- dayjs(Date.now()).format("YYYY-MM-DD HH:mm:ss"),- );+ dayjs(Date.now()).format('YYYY-MM-DD HH:mm:ss'),+ )}}>- {t("newWork")}+ {t('newWork')}</Button></div></div><div className="calendarTiming-toolbar"><div className="calendarTiming-toolbar-left">- {activeMode === "calendar" && (+ {activeMode === 'calendar' && (<><Buttontype="text"@@ -498,9 +509,11 @@ const CalendarTiming = memo(onClick={handleNext}/><h1>- {currentDate.getFullYear()}-{currentDate.getMonth() + 1}+ {currentDate.getFullYear()}+ -+ {currentDate.getMonth() + 1}</h1>- <Button onClick={handleToday}>{t("today")}</Button>+ <Button onClick={handleToday}>{t('today')}</Button></>)}</div>@@ -508,27 +521,27 @@ const CalendarTiming = memo(<TabsactiveKey={activeMode}onChange={(key) => {- const mode = key as "calendar" | "list";+ const mode = key as 'calendar' | 'list'if (mode !== activeMode) {- setActiveMode(mode);+ setActiveMode(mode)}}}items={[{- key: "calendar",+ key: 'calendar',label: (<span><CalendarOutlined />- {t("calendarMode")}+ {t('calendarMode')}</span>),},{- key: "list",+ key: 'list',label: (<span><UnorderedListOutlined />- {t("listModeTab")}+ {t('listModeTab')}</span>),},@@ -539,58 +552,60 @@ const CalendarTiming = memo({channelFilter}</div></div>- {activeMode === "calendar" ? (- <CSSTransition- in={!animating}- timeout={300}- classNames={getTransitionClassNames(direction)}- unmountOnExit- >- <div- className="calendarTiming-calendar"- ref={calendarTimingCalendarRef}- >- <DndProvider backend={HTML5Backend}>- <FullCalendar- ref={calendarRef}- locale={getFullCalendarLang(lng)}- plugins={[dayGridPlugin]}- initialView="dayGridMonth"- initialDate={currentDate}- headerToolbar={false}- stickyFooterScrollbar={true}- dayCellContent={(arg) => {- const dateStr = getDays(arg.date).format("YYYY-MM-DD");- return (- <CalendarTimingItem- key={dateStr}- records={recordMap.get(dateStr)}- loading={listLoading}- arg={arg}- onClickPub={(date) => {- publishDialogRef.current!.setPubTime(date);- setPublishDialogOpen(true);- }}- />- );- }}- datesSet={handleDatesSet}- />- </DndProvider>- </div>- </CSSTransition>- ) : (- <ListMode- onClickPub={(date) => {- publishDialogRef.current!.setPubTime(date);- setPublishDialogOpen(true);- }}- />- )}+ {activeMode === 'calendar'+ ? (+ <CSSTransition+ in={!animating}+ timeout={300}+ classNames={getTransitionClassNames(direction)}+ unmountOnExit+ >+ <div+ className="calendarTiming-calendar"+ ref={calendarTimingCalendarRef}+ >+ <DndProvider backend={HTML5Backend}>+ <FullCalendar+ ref={calendarRef}+ locale={getFullCalendarLang(lng)}+ plugins={[dayGridPlugin]}+ initialView="dayGridMonth"+ initialDate={currentDate}+ headerToolbar={false}+ stickyFooterScrollbar={true}+ dayCellContent={(arg) => {+ const dateStr = getDays(arg.date).format('YYYY-MM-DD')+ return (+ <CalendarTimingItem+ key={dateStr}+ records={recordMap.get(dateStr)}+ loading={listLoading}+ arg={arg}+ onClickPub={(date) => {+ publishDialogRef.current!.setPubTime(date)+ setPublishDialogOpen(true)+ }}+ />+ )+ }}+ datesSet={handleDatesSet}+ />+ </DndProvider>+ </div>+ </CSSTransition>+ )+ : (+ <ListMode+ onClickPub={(date) => {+ publishDialogRef.current!.setPubTime(date)+ setPublishDialogOpen(true)+ }}+ />+ )}</div>- );+ )},),-);+)-export default CalendarTiming;+export default CalendarTimingdiff --git a/project/web/src/app/[lng]/accounts/components/CalendarTiming/useCalendarTiming.ts b/project/web/src/app/[lng]/accounts/components/CalendarTiming/useCalendarTiming.tsindex eac28ba5..096ccac6 100644--- a/project/web/src/app/[lng]/accounts/components/CalendarTiming/useCalendarTiming.ts+++ b/project/web/src/app/[lng]/accounts/components/CalendarTiming/useCalendarTiming.ts@@ -1,21 +1,21 @@-import { create } from "zustand";-import { combine } from "zustand/middleware";-import lodash from "lodash";-import { PublishRecordItem } from "@/api/plat/types/publish.types";-import { getPublishList, getPublishQueue } from "@/api/plat/publish";-import FullCalendar from "@fullcalendar/react";-import { getDays } from "@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils";-import { useAccountStore } from "@/store/account";+import type FullCalendar from '@fullcalendar/react'+import type { PublishRecordItem } from '@/api/plat/types/publish.types'+import lodash from 'lodash'+import { create } from 'zustand'+import { combine } from 'zustand/middleware'+import { getPublishList, getPublishQueue } from '@/api/plat/publish'+import { getDays } from '@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils'+import { useAccountStore } from '@/store/account'export interface ICalendarTimingStore {// 日历单元格宽度- calendarCallWidth: number;+ calendarCallWidth: number// 发布记录数据,key=年月日,value=发布记录- recordMap: Map<string, PublishRecordItem[]>;+ recordMap: Map<string, PublishRecordItem[]>// 请求发布记录loading- listLoading: boolean;+ listLoading: boolean// 当前日历ref- calendarRef?: FullCalendar;+ calendarRef?: FullCalendar}const store: ICalendarTimingStore = {@@ -23,11 +23,11 @@ const store: ICalendarTimingStore = {recordMap: new Map(),listLoading: false,calendarRef: undefined,-};+}-const getStore = () => {- return lodash.cloneDeep(store);-};+function getStore() {+ return lodash.cloneDeep(store)+}export const useCalendarTiming = create(combine(@@ -37,120 +37,122 @@ export const useCalendarTiming = create((set, get, storeApi) => {const methods = {setCalendarCallWidth(calendarCallWidth: number) {- set({ calendarCallWidth });+ set({ calendarCallWidth })},setRecordMap(recordMap: Map<string, PublishRecordItem[]>) {- set({ recordMap });+ set({ recordMap })},setListLoading(listLoading: boolean) {- set({ listLoading });+ set({ listLoading })},setCalendarRef(calendarRef: FullCalendar) {- set({ calendarRef });+ set({ calendarRef })},// 获取发布记录数据async getPubRecord(status?: number) {try {- methods.setListLoading(true);- const calendarApi = get().calendarRef?.getApi();- const view = calendarApi?.view;- const visibleStart = view?.activeStart;- const visibleEnd = view?.activeEnd;- const startDay = getDays(visibleStart).startOf("day");- const endDay = getDays(visibleEnd).subtract(1, "day").endOf("day");+ methods.setListLoading(true)+ const calendarApi = get().calendarRef?.getApi()+ const view = calendarApi?.view+ const visibleStart = view?.activeStart+ const visibleEnd = view?.activeEnd+ const startDay = getDays(visibleStart).startOf('day')+ const endDay = getDays(visibleEnd).subtract(1, 'day').endOf('day')const res = await getPublishList({time: [startDay.utc().format(), endDay.utc().format()],accountType: useAccountStore.getState().accountActive?.type,- status: status,- publishingChannel: "internal",- });- methods.setListLoading(false);+ status,+ publishingChannel: 'internal',+ })+ methods.setListLoading(false)// 检查响应数据是否有效if (!res || !res.data || !Array.isArray(res.data)) {- console.warn("获取发布记录数据失败或数据格式不正确:", res);- methods.setRecordMap(new Map());- return;+ console.warn('获取发布记录数据失败或数据格式不正确:', res)+ methods.setRecordMap(new Map())+ return}- const recordMap = new Map<string, PublishRecordItem[]>();+ const recordMap = new Map<string, PublishRecordItem[]>()// 将数据分拣到对应天中res.data.map((v) => {- const days = getDays(v.publishTime);- const timeStr = days.format("YYYY-MM-DD");- let list = recordMap.get(timeStr);+ const days = getDays(v.publishTime)+ const timeStr = days.format('YYYY-MM-DD')+ let list = recordMap.get(timeStr)if (!list) {- list = [];- recordMap.set(timeStr, list);+ list = []+ recordMap.set(timeStr, list)}- list.push(v);- recordMap.set(timeStr, list);- });+ list.push(v)+ recordMap.set(timeStr, list)+ })// 对每一天的记录按照 publishTime 时间从早到晚排序recordMap.forEach((v, k) => {- let list = recordMap.get(k);+ let list = recordMap.get(k)if (list) {list = list.sort((a, b) =>- new Date(a?.publishTime ?? 0).getTime() -- new Date(b?.publishTime ?? 0).getTime(),- );- recordMap.set(k, list);+ new Date(a?.publishTime ?? 0).getTime()+ - new Date(b?.publishTime ?? 0).getTime(),+ )+ recordMap.set(k, list)}- });- methods.setRecordMap(recordMap);- } catch (error) {- console.error("获取发布记录数据时发生错误:", error);- methods.setListLoading(false);- methods.setRecordMap(new Map());+ })+ methods.setRecordMap(recordMap)+ }+ catch (error) {+ console.error('获取发布记录数据时发生错误:', error)+ methods.setListLoading(false)+ methods.setRecordMap(new Map())}},// 获取列表模式队列数据(不依赖日历可视范围)async getQueueRecord(status?: number) {try {- methods.setListLoading(true);+ methods.setListLoading(true)const res = await getPublishQueue({accountType: useAccountStore.getState().accountActive?.type,- status: status,- publishingChannel: "internal",- });- methods.setListLoading(false);+ status,+ publishingChannel: 'internal',+ })+ methods.setListLoading(false)if (!res || !res.data || !Array.isArray(res.data)) {- console.warn("获取发布队列数据失败或数据格式不正确:", res);- methods.setRecordMap(new Map());- return;+ console.warn('获取发布队列数据失败或数据格式不正确:', res)+ methods.setRecordMap(new Map())+ return}- const recordMap = new Map<string, PublishRecordItem[]>();+ const recordMap = new Map<string, PublishRecordItem[]>()res.data.forEach((v) => {- const days = getDays(v.publishTime);- const timeStr = days.format("YYYY-MM-DD");- let list = recordMap.get(timeStr);+ const days = getDays(v.publishTime)+ const timeStr = days.format('YYYY-MM-DD')+ let list = recordMap.get(timeStr)if (!list) {- list = [];- recordMap.set(timeStr, list);+ list = []+ recordMap.set(timeStr, list)}- list.push(v);- });- methods.setRecordMap(recordMap);- } catch (error) {- console.error("获取发布队列时发生错误:", error);- methods.setListLoading(false);- methods.setRecordMap(new Map());+ list.push(v)+ })+ methods.setRecordMap(recordMap)+ }+ catch (error) {+ console.error('获取发布队列时发生错误:', error)+ methods.setListLoading(false)+ methods.setRecordMap(new Map())}},clear() {set({...getStore(),- });+ })},- };- return methods;+ }+ return methods},),-);+)diff --git a/project/web/src/app/[lng]/accounts/components/ProxyInput/index.tsx b/project/web/src/app/[lng]/accounts/components/ProxyInput/index.tsxindex 48adafd0..1e47d482 100644--- a/project/web/src/app/[lng]/accounts/components/ProxyInput/index.tsx+++ b/project/web/src/app/[lng]/accounts/components/ProxyInput/index.tsx@@ -1,87 +1,90 @@-import { ForwardedRef, forwardRef, memo, useEffect, useState } from "react";-import styles from "./proxyInput.module.scss";-import { Button, Input, message } from "antd";+import type { ForwardedRef } from 'react'+import { Button, Input, message } from 'antd'+import { forwardRef, memo, useEffect, useState } from 'react'+import styles from './proxyInput.module.scss'export interface IProxyInputRef {}export interface IProxyInputProps {- onChange: (name: string) => void;+ onChange: (name: string) => void}export interface ProxyInfo {// 协议: 如 http, socks5- protocol: string;+ protocol: string// IP+端口: 如 192.168.0.1:8000- ipAndPort: string;+ ipAndPort: string// 代理账号: 可选- username?: string;+ username?: string// 代理密码: 可选- password?: string;+ password?: string// 刷新URL: 可选- refreshUrl?: string;+ refreshUrl?: string// 备注: 可选- remark?: string;+ remark?: string}export function parseProxyString(proxyString: string): ProxyInfo | false {- const regex =- /^(?:(\w+):\/\/)?([\d.]+:\d+)(?::([^:]+):([^{}\s]+))?(?:\[(.*?)\])?(?:{(.*?)})?$/;+ const regex+ = /^(?:(\w+):\/\/)?([\d.]+:\d+)(?::([^:]+):([^{}\s[\]]+))?(?:\[([^\]]+)\])?(?:\{([^}]+)\})?$/- const match = proxyString.match(regex);+ const match = proxyString.match(regex)if (!match) {- return false; // 无法解析则返回 false+ return false // 无法解析则返回 false}- const [, protocol, ipAndPort, username, password, refreshUrl, remark] = match;+ const [, protocol, ipAndPort, username, password, refreshUrl, remark] = matchreturn {- protocol: protocol || "http", // 如果未提供协议,默认为 http+ protocol: protocol || 'http', // 如果未提供协议,默认为 httpipAndPort,username,password,refreshUrl,remark,- };+ }}// 验证代理地址export async function verifyProxy(proxyName: string) {- const proxyInfo = parseProxyString(proxyName);- if (proxyInfo === false) return false;- return true;+ const proxyInfo = parseProxyString(proxyName)+ if (proxyInfo === false)+ return false+ return true}const ProxyInput = memo(forwardRef(({ onChange }: IProxyInputProps, ref: ForwardedRef<IProxyInputRef>) => {- const [proxyLoading, setProxyLoading] = useState(false);- const [proxyName, setProxyName] = useState("");+ const [proxyLoading, setProxyLoading] = useState(false)+ const [proxyName, setProxyName] = useState('')useEffect(() => {- onChange(proxyName);- }, [onChange, proxyName]);+ onChange(proxyName)+ }, [onChange, proxyName])return (<><divclassName={`${styles.createGroup} ${styles.proxyInput}`}- style={{ marginBottom: "20px" }}+ style={{ marginBottom: '20px' }}><label>代理地址</label><Inputvalue={proxyName}placeholder="请输入代理地址"- onChange={(e) => setProxyName(e.target.value)}+ onChange={e => setProxyName(e.target.value)}/><Buttondisabled={proxyName.length === 0}loading={proxyLoading}onClick={async () => {- const verifyRes = await verifyProxy(proxyName);+ const verifyRes = await verifyProxy(proxyName)if (verifyRes) {- message.success("代理地址可用");- } else {- message.error("代理地址不可用");+ message.success('代理地址可用')+ }+ else {+ message.error('代理地址不可用')}}}>@@ -91,14 +94,23 @@ const ProxyInput = memo(<div className={styles.proxyHint}><p>1. 代理类型仅支持HTTP、HTTPS、Socks5;</p><p>支持以下填写格式</p>- <p>192.168.0.1:8000{`{备注}`}</p>- <p>192.168.0.1:8000:代理账号:代理密码{`{备注}`}</p>- <p>socks5://192.168.0.1:8000:代理账号:代理密码{`{备注}`}</p>+ <p>+ 192.168.0.1:8000+ {`{备注}`}+ </p>+ <p>+ 192.168.0.1:8000:代理账号:代理密码+ {`{备注}`}+ </p>+ <p>+ socks5://192.168.0.1:8000:代理账号:代理密码+ {`{备注}`}+ </p></div></>- );+ )},),-);+)-export default ProxyInput;+export default ProxyInputdiff --git a/project/web/src/app/[lng]/accounts/components/ProxyInput/proxyInput.module.scss b/project/web/src/app/[lng]/accounts/components/ProxyInput/proxyInput.module.scssindex 27eb2c6f..ba63ce34 100644--- a/project/web/src/app/[lng]/accounts/components/ProxyInput/proxyInput.module.scss+++ b/project/web/src/app/[lng]/accounts/components/ProxyInput/proxyInput.module.scss@@ -24,4 +24,4 @@white-space: nowrap;margin-right: 10px;}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/accounts/page.tsx b/project/web/src/app/[lng]/accounts/page.tsxindex cbc22f06..e8f970d4 100644--- a/project/web/src/app/[lng]/accounts/page.tsx+++ b/project/web/src/app/[lng]/accounts/page.tsx@@ -1,27 +1,27 @@-import AccountPageCore from "@/app/[lng]/accounts/accountCore";-import { PageParams } from "@/app/globals";-import { useTranslation } from "@/app/i18n";-import { getMetadata } from "@/utils/general";+import type { PageParams } from '@/app/globals'+import AccountPageCore from '@/app/[lng]/accounts/accountCore'+import { useTranslation } from '@/app/i18n'+import { getMetadata } from '@/utils/general'export async function generateMetadata({ params }: PageParams) {- const { lng } = await params;- const { t } = await useTranslation(lng, "account");+ const { lng } = await params+ const { t } = await useTranslation(lng, 'account')return await getMetadata({- title: t("title"),- description: t("describe"),+ title: t('title'),+ description: t('describe'),},lng,- );+ )}interface AccountsPageProps {searchParams: {- platform?: string;- spaceId?: string;- };+ platform?: string+ spaceId?: string+ }}export default function Page({ searchParams }: AccountsPageProps) {- return <AccountPageCore searchParams={searchParams} />;+ return <AccountPageCore searchParams={searchParams} />}diff --git a/project/web/src/app/[lng]/accounts/plat/BilibiliLogin.ts b/project/web/src/app/[lng]/accounts/plat/BilibiliLogin.tsindex 7727dca2..748028fc 100644--- a/project/web/src/app/[lng]/accounts/plat/BilibiliLogin.ts+++ b/project/web/src/app/[lng]/accounts/plat/BilibiliLogin.ts@@ -1,84 +1,84 @@-import qs from "qs";-import { PlatType } from "@/app/config/platConfig";-import { apiGetBilibiliLoginUrl, apiCheckBilibiliAuth } from "@/api/plat/bilibili";-import { useAccountStore } from "@/store/account";-import { useUserStore } from "@/store/user";-+import { apiCheckBilibiliAuth, apiGetBilibiliLoginUrl } from '@/api/plat/bilibili'+import { PlatType } from '@/app/config/platConfig'+import { useAccountStore } from '@/store/account'+import { useUserStore } from '@/store/user'/*** b站被点击* @param platType*/export async function bilibiliSkip(platType: PlatType, spaceId?: string) {- if (platType !== PlatType.BILIBILI) return;+ if (platType !== PlatType.BILIBILI)+ return- const res: any = await apiGetBilibiliLoginUrl('pc', spaceId);- if (res?.code == 1) {- useUserStore.getState().logout();+ const res: any = await apiGetBilibiliLoginUrl('pc', spaceId)+ if (res?.code === 1) {+ useUserStore.getState().logout()return}- if (res?.code !== 0) return;- const url = res.data.url;- window.open(`${url}`);+ if (res?.code !== 0)+ return+ const url = res.data.url+ window.open(`${url}`)- const bilibiliLoginRes = await bilibiliLogin(res.data.taskId);-+ await bilibiliLogin(res.data.taskId)}-export function bilibiliLogin(taskId:any): Promise<any> {+export function bilibiliLogin(taskId: any): Promise<any> {return new Promise(async (resolve, reject) => {try {- let pollCount = 0;- const maxPollCount = 30; // 最大轮询次数+ let pollCount = 0+ const maxPollCount = 30 // 最大轮询次数- // 开始轮询检查授权状态- const checkAuthStatus = async () => {- try {- pollCount++;- const authRess:any = await apiCheckBilibiliAuth(taskId);- let authRes = authRess;- if (authRes?.code === 0 && authRes?.data.status == 1) {- // message.success('授权成功');- // useAccountStore- const accountStore = useAccountStore.getState();- await accountStore.getAccountList();- resolve(authRes);- return true;- }-- // 检查是否达到最大轮询次数- if (pollCount >= maxPollCount) {- console.log('达到最大轮询次数,停止轮询');- return true;- }-- // return false;- } catch (error) {- console.error('检查授权状态失败:', error);- return false;+ // 开始轮询检查授权状态+ const checkAuthStatus = async () => {+ try {+ pollCount+++ const authRess: any = await apiCheckBilibiliAuth(taskId)+ const authRes = authRess+ if (authRes?.code === 0 && authRes?.data.status == 1) {+ // message.success('授权成功');+ // useAccountStore+ const accountStore = useAccountStore.getState()+ await accountStore.getAccountList()+ resolve(authRes)+ return true}- };- // 设置轮询间隔- const interval = setInterval(async () => {- const isSuccess = await checkAuthStatus();- if (isSuccess) {- clearInterval(interval);- if (pollCount >= maxPollCount) {- reject(new Error('授权超时,已达到最大轮询次数'));- }+ // 检查是否达到最大轮询次数+ if (pollCount >= maxPollCount) {+ console.log('达到最大轮询次数,停止轮询')+ return true}- }, 2000);- // 5分钟后自动停止轮询- setTimeout(() => {- clearInterval(interval);- // message.error('授权超时,请重试');- reject(new Error('授权超时'));- }, 5 * 60 * 1000);-- } catch (e) {- reject(e);+ // return false;+ }+ catch (error) {+ console.error('检查授权状态失败:', error)+ return false+ }+ }++ // 设置轮询间隔+ const interval = setInterval(async () => {+ const isSuccess = await checkAuthStatus()+ if (isSuccess) {+ clearInterval(interval)+ if (pollCount >= maxPollCount) {+ reject(new Error('授权超时,已达到最大轮询次数'))+ }+ }+ }, 2000)++ // 5分钟后自动停止轮询+ setTimeout(() => {+ clearInterval(interval)+ // message.error('授权超时,请重试');+ reject(new Error('授权超时'))+ }, 5 * 60 * 1000)+ }+ catch (e) {+ reject(e)}- });+ })}diff --git a/project/web/src/app/[lng]/accounts/plat/FacebookLogin.ts b/project/web/src/app/[lng]/accounts/plat/FacebookLogin.tsindex 7cd6f037..a09ac797 100644--- a/project/web/src/app/[lng]/accounts/plat/FacebookLogin.ts+++ b/project/web/src/app/[lng]/accounts/plat/FacebookLogin.ts@@ -1,88 +1,90 @@-import qs from "qs";-import { PlatType } from "@/app/config/platConfig";-import { getFacebookAuthUrlApi, checkMetaAuthApi } from "@/api/platAuth";-import { useAccountStore } from "@/store/account";-+import qs from 'qs'+import { checkMetaAuthApi, getFacebookAuthUrlApi } from '@/api/platAuth'+import { PlatType } from '@/app/config/platConfig'// 导入Facebook页面选择弹窗-import FacebookPagesModal from "@/components/FacebookPagesModal";-import { useUserStore } from "@/store/user";+import FacebookPagesModal from '@/components/FacebookPagesModal'++import { useAccountStore } from '@/store/account'+import { useUserStore } from '@/store/user'/*** Facebook被点击* @param platType*/export async function facebookSkip(platType: PlatType, spaceId?: string) {- if (platType !== PlatType.Facebook) return;+ if (platType !== PlatType.Facebook)+ return- const res: any = await getFacebookAuthUrlApi('pc', spaceId);- if (res?.code == 1) {- useUserStore.getState().logout();- return- }- if (res?.code !== 0) return;- const url = res.data.url;- window.open(`${url}`);+ const res: any = await getFacebookAuthUrlApi('pc', spaceId)+ if (res?.code == 1) {+ useUserStore.getState().logout()+ return+ }+ if (res?.code !== 0)+ return+ const url = res.data.url+ window.open(`${url}`)- const facebookLoginRes = await facebookLogin(res.data.taskId);-+ const facebookLoginRes = await facebookLogin(res.data.taskId)}export function facebookLogin(taskId: any): Promise<any> {return new Promise(async (resolve, reject) => {try {- let pollCount = 0;- const maxPollCount = 30; // 最大轮询次数+ let pollCount = 0+ const maxPollCount = 30 // 最大轮询次数// 开始轮询检查授权状态const checkAuthStatus = async () => {try {- pollCount++;- const authRess: any = await checkMetaAuthApi(taskId);- let authRes = authRess;+ pollCount+++ const authRess: any = await checkMetaAuthApi(taskId)+ const authRes = authRessconsole.log('authRes', authRes)if (authRes?.code === 0 && authRes?.data.status == 1) {// 授权成功,不再直接刷新账户列表// 而是触发页面选择弹窗- resolve(authRes);- return true;+ resolve(authRes)+ return true}-+// 检查是否达到最大轮询次数if (pollCount >= maxPollCount) {- console.log('达到最大轮询次数,停止轮询');- return true;+ console.log('达到最大轮询次数,停止轮询')+ return true}-+// return false;- } catch (error) {- console.error('检查授权状态失败:', error);- return false;}- };+ catch (error) {+ console.error('检查授权状态失败:', error)+ return false+ }+ }// 设置轮询间隔const interval = setInterval(async () => {- const isSuccess = await checkAuthStatus();+ const isSuccess = await checkAuthStatus()if (isSuccess) {- clearInterval(interval);+ clearInterval(interval)if (pollCount >= maxPollCount) {- reject(new Error('授权超时,已达到最大轮询次数'));+ reject(new Error('授权超时,已达到最大轮询次数'))}}- }, 2000);+ }, 2000)// 5分钟后自动停止轮询setTimeout(() => {- clearInterval(interval);+ clearInterval(interval)// message.error('授权超时,请重试');- reject(new Error('授权超时'));- }, 5 * 60 * 1000);-- } catch (e) {- reject(e);+ reject(new Error('授权超时'))+ }, 5 * 60 * 1000)+ }+ catch (e) {+ reject(e)}- });+ })}// 导出Facebook页面选择弹窗组件,供外部使用-export { FacebookPagesModal };+export { FacebookPagesModal }diff --git a/project/web/src/app/[lng]/accounts/plat/InstagramLogin.ts b/project/web/src/app/[lng]/accounts/plat/InstagramLogin.tsindex c230a450..539c2110 100644--- a/project/web/src/app/[lng]/accounts/plat/InstagramLogin.ts+++ b/project/web/src/app/[lng]/accounts/plat/InstagramLogin.ts@@ -1,85 +1,86 @@-import qs from "qs";-import { PlatType } from "@/app/config/platConfig";-import { getInstagramAuthUrlApi, checkMetaAuthApi } from "@/api/platAuth";-import { useAccountStore } from "@/store/account";-import { useUserStore } from "@/store/user";-+import qs from 'qs'+import { checkMetaAuthApi, getInstagramAuthUrlApi } from '@/api/platAuth'+import { PlatType } from '@/app/config/platConfig'+import { useAccountStore } from '@/store/account'+import { useUserStore } from '@/store/user'/*** b站被点击* @param platType*/export async function instagramSkip(platType: PlatType, spaceId?: string) {- if (platType !== PlatType.Instagram) return;+ if (platType !== PlatType.Instagram)+ return- const res: any = await getInstagramAuthUrlApi('pc', spaceId);+ const res: any = await getInstagramAuthUrlApi('pc', spaceId)if (res?.code == 1) {- useUserStore.getState().logout();- return- }- if (res?.code !== 0) return;- const url = res.data.url;- window.open(`${url}`);+ useUserStore.getState().logout()+ return+ }+ if (res?.code !== 0)+ return+ const url = res.data.url+ window.open(`${url}`)- const instagramLoginRes = await instagramLogin(res.data.taskId);-+ const instagramLoginRes = await instagramLogin(res.data.taskId)}-export function instagramLogin(taskId:any): Promise<any> {+export function instagramLogin(taskId: any): Promise<any> {return new Promise(async (resolve, reject) => {try {- let pollCount = 0;- const maxPollCount = 30; // 最大轮询次数+ let pollCount = 0+ const maxPollCount = 30 // 最大轮询次数- // 开始轮询检查授权状态- const checkAuthStatus = async () => {- try {- pollCount++;- const authRess:any = await checkMetaAuthApi(taskId);- let authRes = authRess;- console.log('authRes', authRes)- if (authRes?.code === 0 && authRes?.data.status == 1) {- // message.success('授权成功');- // useAccountStore- const accountStore = useAccountStore.getState();- await accountStore.getAccountList();- resolve(authRes);- return true;- }-- // 检查是否达到最大轮询次数- if (pollCount >= maxPollCount) {- console.log('达到最大轮询次数,停止轮询');- return true;- }-- // return false;- } catch (error) {- console.error('检查授权状态失败:', error);- return false;+ // 开始轮询检查授权状态+ const checkAuthStatus = async () => {+ try {+ pollCount+++ const authRess: any = await checkMetaAuthApi(taskId)+ const authRes = authRess+ console.log('authRes', authRes)+ if (authRes?.code === 0 && authRes?.data.status == 1) {+ // message.success('授权成功');+ // useAccountStore+ const accountStore = useAccountStore.getState()+ await accountStore.getAccountList()+ resolve(authRes)+ return true}- };- // 设置轮询间隔- const interval = setInterval(async () => {- const isSuccess = await checkAuthStatus();- if (isSuccess) {- clearInterval(interval);- if (pollCount >= maxPollCount) {- reject(new Error('授权超时,已达到最大轮询次数'));- }+ // 检查是否达到最大轮询次数+ if (pollCount >= maxPollCount) {+ console.log('达到最大轮询次数,停止轮询')+ return true}- }, 2000);- // 5分钟后自动停止轮询- setTimeout(() => {- clearInterval(interval);- // message.error('授权超时,请重试');- reject(new Error('授权超时'));- }, 5 * 60 * 1000);-- } catch (e) {- reject(e);+ // return false;+ }+ catch (error) {+ console.error('检查授权状态失败:', error)+ return false+ }+ }++ // 设置轮询间隔+ const interval = setInterval(async () => {+ const isSuccess = await checkAuthStatus()+ if (isSuccess) {+ clearInterval(interval)+ if (pollCount >= maxPollCount) {+ reject(new Error('授权超时,已达到最大轮询次数'))+ }+ }+ }, 2000)++ // 5分钟后自动停止轮询+ setTimeout(() => {+ clearInterval(interval)+ // message.error('授权超时,请重试');+ reject(new Error('授权超时'))+ }, 5 * 60 * 1000)+ }+ catch (e) {+ reject(e)}- });+ })}diff --git a/project/web/src/app/[lng]/accounts/plat/LinkedinLogin.ts b/project/web/src/app/[lng]/accounts/plat/LinkedinLogin.tsindex 479917a2..c72b24fc 100644--- a/project/web/src/app/[lng]/accounts/plat/LinkedinLogin.ts+++ b/project/web/src/app/[lng]/accounts/plat/LinkedinLogin.ts@@ -1,25 +1,27 @@-import { PlatType } from "@/app/config/platConfig";-import { getLinkedInAuthUrlApi, checkMetaAuthApi } from "@/api/platAuth";-import { useUserStore } from "@/store/user";-import { useAccountStore } from "@/store/account";+import { checkMetaAuthApi, getLinkedInAuthUrlApi } from '@/api/platAuth'+import { PlatType } from '@/app/config/platConfig'+import { useAccountStore } from '@/store/account'+import { useUserStore } from '@/store/user'/*** LinkedIn 被点击* @param platType 平台类型*/export async function linkedinSkip(platType: PlatType, spaceId?: string) {- if (platType !== PlatType.LinkedIn) return;+ if (platType !== PlatType.LinkedIn)+ return- const res: any = await getLinkedInAuthUrlApi('pc', spaceId);+ const res: any = await getLinkedInAuthUrlApi('pc', spaceId)if (res?.code == 1) {- useUserStore.getState().logout();- return;+ useUserStore.getState().logout()+ return}- if (res?.code !== 0) return;- const url = res.data.url;- window.open(`${url}`);+ if (res?.code !== 0)+ return+ const url = res.data.url+ window.open(`${url}`)- await linkedinLogin(res.data.taskId);+ await linkedinLogin(res.data.taskId)}/**@@ -29,46 +31,46 @@ export async function linkedinSkip(platType: PlatType, spaceId?: string) {export function linkedinLogin(taskId: any): Promise<any> {return new Promise(async (resolve, reject) => {try {- let pollCount = 0;- const maxPollCount = 30;+ let pollCount = 0+ const maxPollCount = 30const checkAuthStatus = async () => {try {- pollCount++;- const authRess: any = await checkMetaAuthApi(taskId);- const authRes = authRess;+ pollCount+++ const authRess: any = await checkMetaAuthApi(taskId)+ const authRes = authRessif (authRes?.code === 0 && authRes?.data.status == 1) {- const accountStore = useAccountStore.getState();- await accountStore.getAccountList();- resolve(authRes);- return true;+ const accountStore = useAccountStore.getState()+ await accountStore.getAccountList()+ resolve(authRes)+ return true}if (pollCount >= maxPollCount) {- return true;+ return true}- } catch (error) {- return false;}- };+ catch (error) {+ return false+ }+ }const interval = setInterval(async () => {- const isSuccess = await checkAuthStatus();+ const isSuccess = await checkAuthStatus()if (isSuccess) {- clearInterval(interval);+ clearInterval(interval)if (pollCount >= maxPollCount) {- reject(new Error('授权超时,已达到最大轮询次数'));+ reject(new Error('授权超时,已达到最大轮询次数'))}}- }, 2000);+ }, 2000)setTimeout(() => {- clearInterval(interval);- reject(new Error('授权超时'));- }, 5 * 60 * 1000);- } catch (e) {- reject(e);+ clearInterval(interval)+ reject(new Error('授权超时'))+ }, 5 * 60 * 1000)+ }+ catch (e) {+ reject(e)}- });+ })}--diff --git a/project/web/src/app/[lng]/accounts/plat/PinterestLogin.ts b/project/web/src/app/[lng]/accounts/plat/PinterestLogin.tsindex 21b5e110..8e560690 100644--- a/project/web/src/app/[lng]/accounts/plat/PinterestLogin.ts+++ b/project/web/src/app/[lng]/accounts/plat/PinterestLogin.ts@@ -1,85 +1,86 @@-import qs from "qs";-import { PlatType } from "@/app/config/platConfig";-import { getPinterestAuthUrlApi, checkPinterestAuthApi } from "@/api/platAuth";-import { useAccountStore } from "@/store/account";-import { useUserStore } from "@/store/user";-+import qs from 'qs'+import { checkPinterestAuthApi, getPinterestAuthUrlApi } from '@/api/platAuth'+import { PlatType } from '@/app/config/platConfig'+import { useAccountStore } from '@/store/account'+import { useUserStore } from '@/store/user'/*** Pinterest被点击* @param platType*/export async function pinterestSkip(platType: PlatType, spaceId?: string) {- if (platType !== PlatType.Pinterest) return;+ if (platType !== PlatType.Pinterest)+ return- const res: any = await getPinterestAuthUrlApi('pc', spaceId);+ const res: any = await getPinterestAuthUrlApi('pc', spaceId)if (res?.code == 1) {- useUserStore.getState().logout();- return- }- if (res?.code !== 0) return;- const url = res.data.uri;- window.open(`${url}`);+ useUserStore.getState().logout()+ return+ }+ if (res?.code !== 0)+ return+ const url = res.data.uri+ window.open(`${url}`)- const pinterestLoginRes = await pinterestLogin(res.data.taskId);-+ const pinterestLoginRes = await pinterestLogin(res.data.taskId)}-export function pinterestLogin(taskId:any): Promise<any> {+export function pinterestLogin(taskId: any): Promise<any> {return new Promise(async (resolve, reject) => {try {- let pollCount = 0;- const maxPollCount = 30; // 最大轮询次数+ let pollCount = 0+ const maxPollCount = 30 // 最大轮询次数- // 开始轮询检查授权状态- const checkAuthStatus = async () => {- try {- pollCount++;- const authRess:any = await checkPinterestAuthApi(taskId);- let authRes = authRess;- console.log('authRes', authRes)- if (authRes?.code === 0 && authRes?.data.status == 1) {- // message.success('授权成功');- // useAccountStore- const accountStore = useAccountStore.getState();- await accountStore.getAccountList();- resolve(authRes);- return true;- }-- // 检查是否达到最大轮询次数- if (pollCount >= maxPollCount) {- console.log('达到最大轮询次数,停止轮询');- return true;- }-- // return false;- } catch (error) {- console.error('检查授权状态失败:', error);- return false;+ // 开始轮询检查授权状态+ const checkAuthStatus = async () => {+ try {+ pollCount+++ const authRess: any = await checkPinterestAuthApi(taskId)+ const authRes = authRess+ console.log('authRes', authRes)+ if (authRes?.code === 0 && authRes?.data.status == 1) {+ // message.success('授权成功');+ // useAccountStore+ const accountStore = useAccountStore.getState()+ await accountStore.getAccountList()+ resolve(authRes)+ return true}- };- // 设置轮询间隔- const interval = setInterval(async () => {- const isSuccess = await checkAuthStatus();- if (isSuccess) {- clearInterval(interval);- if (pollCount >= maxPollCount) {- reject(new Error('授权超时,已达到最大轮询次数'));- }+ // 检查是否达到最大轮询次数+ if (pollCount >= maxPollCount) {+ console.log('达到最大轮询次数,停止轮询')+ return true}- }, 2000);- // 5分钟后自动停止轮询- setTimeout(() => {- clearInterval(interval);- // message.error('授权超时,请重试');- reject(new Error('授权超时'));- }, 5 * 60 * 1000);-- } catch (e) {- reject(e);+ // return false;+ }+ catch (error) {+ console.error('检查授权状态失败:', error)+ return false+ }+ }++ // 设置轮询间隔+ const interval = setInterval(async () => {+ const isSuccess = await checkAuthStatus()+ if (isSuccess) {+ clearInterval(interval)+ if (pollCount >= maxPollCount) {+ reject(new Error('授权超时,已达到最大轮询次数'))+ }+ }+ }, 2000)++ // 5分钟后自动停止轮询+ setTimeout(() => {+ clearInterval(interval)+ // message.error('授权超时,请重试');+ reject(new Error('授权超时'))+ }, 5 * 60 * 1000)+ }+ catch (e) {+ reject(e)}- });+ })}diff --git a/project/web/src/app/[lng]/accounts/plat/ThreadsLogin.ts b/project/web/src/app/[lng]/accounts/plat/ThreadsLogin.tsindex 07ee17b4..7da69999 100644--- a/project/web/src/app/[lng]/accounts/plat/ThreadsLogin.ts+++ b/project/web/src/app/[lng]/accounts/plat/ThreadsLogin.ts@@ -1,86 +1,87 @@-import qs from "qs";-import { PlatType } from "@/app/config/platConfig";-import { getThreadsAuthUrlApi, checkMetaAuthApi } from "@/api/platAuth";-import { useAccountStore } from "@/store/account";-import { useUserStore } from "@/store/user";-+import qs from 'qs'+import { checkMetaAuthApi, getThreadsAuthUrlApi } from '@/api/platAuth'+import { PlatType } from '@/app/config/platConfig'+import { useAccountStore } from '@/store/account'+import { useUserStore } from '@/store/user'/*** b站被点击* @param platType*/export async function threadsSkip(platType: PlatType, spaceId?: string) {- if (platType !== PlatType.Threads) return;+ if (platType !== PlatType.Threads)+ return- const res: any = await getThreadsAuthUrlApi('pc', spaceId);+ const res: any = await getThreadsAuthUrlApi('pc', spaceId)if (res?.code == 1) {- useUserStore.getState().logout();- return- }+ useUserStore.getState().logout()+ return+ }- if (res?.code !== 0) return;- const url = res.data.url;- window.open(`${url}`);+ if (res?.code !== 0)+ return+ const url = res.data.url+ window.open(`${url}`)- const threadsLoginRes = await threadsLogin(res.data.taskId);-+ const threadsLoginRes = await threadsLogin(res.data.taskId)}-export function threadsLogin(taskId:any): Promise<any> {+export function threadsLogin(taskId: any): Promise<any> {return new Promise(async (resolve, reject) => {try {- let pollCount = 0;- const maxPollCount = 30; // 最大轮询次数+ let pollCount = 0+ const maxPollCount = 30 // 最大轮询次数++ // 开始轮询检查授权状态+ const checkAuthStatus = async () => {+ try {+ pollCount+++ const authRess: any = await checkMetaAuthApi(taskId)+ const authRes = authRess+ console.log('authRes', authRes)+ if (authRes?.code === 0 && authRes?.data.status == 1) {+ // message.success('授权成功');+ // useAccountStore+ const accountStore = useAccountStore.getState()+ await accountStore.getAccountList()+ resolve(authRes)+ return true+ }- // 开始轮询检查授权状态- const checkAuthStatus = async () => {- try {- pollCount++;- const authRess:any = await checkMetaAuthApi(taskId);- let authRes = authRess;- console.log('authRes', authRes)- if (authRes?.code === 0 && authRes?.data.status == 1) {- // message.success('授权成功');- // useAccountStore- const accountStore = useAccountStore.getState();- await accountStore.getAccountList();- resolve(authRes);- return true;- }-- // 检查是否达到最大轮询次数- if (pollCount >= maxPollCount) {- console.log('达到最大轮询次数,停止轮询');- return true;- }-- // return false;- } catch (error) {- console.error('检查授权状态失败:', error);- return false;+ // 检查是否达到最大轮询次数+ if (pollCount >= maxPollCount) {+ console.log('达到最大轮询次数,停止轮询')+ return true}- };- // 设置轮询间隔- const interval = setInterval(async () => {- const isSuccess = await checkAuthStatus();- if (isSuccess) {- clearInterval(interval);- if (pollCount >= maxPollCount) {- reject(new Error('授权超时,已达到最大轮询次数'));- }+ // return false;+ }+ catch (error) {+ console.error('检查授权状态失败:', error)+ return false+ }+ }++ // 设置轮询间隔+ const interval = setInterval(async () => {+ const isSuccess = await checkAuthStatus()+ if (isSuccess) {+ clearInterval(interval)+ if (pollCount >= maxPollCount) {+ reject(new Error('授权超时,已达到最大轮询次数'))}- }, 2000);+ }+ }, 2000)- // 5分钟后自动停止轮询- setTimeout(() => {- clearInterval(interval);- // message.error('授权超时,请重试');- reject(new Error('授权超时'));- }, 5 * 60 * 1000);-- } catch (e) {- reject(e);+ // 5分钟后自动停止轮询+ setTimeout(() => {+ clearInterval(interval)+ // message.error('授权超时,请重试');+ reject(new Error('授权超时'))+ }, 5 * 60 * 1000)+ }+ catch (e) {+ reject(e)}- });+ })}diff --git a/project/web/src/app/[lng]/accounts/plat/TiktokLogin.ts b/project/web/src/app/[lng]/accounts/plat/TiktokLogin.tsindex dbab29fa..f080900e 100644--- a/project/web/src/app/[lng]/accounts/plat/TiktokLogin.ts+++ b/project/web/src/app/[lng]/accounts/plat/TiktokLogin.ts@@ -1,85 +1,86 @@-import qs from "qs";-import { PlatType } from "@/app/config/platConfig";-import { checkTiktokAuthApi, getTiktokAuthUrlApi } from "@/api/platAuth";-import { useAccountStore } from "@/store/account";-import { useUserStore } from "@/store/user";-+import qs from 'qs'+import { checkTiktokAuthApi, getTiktokAuthUrlApi } from '@/api/platAuth'+import { PlatType } from '@/app/config/platConfig'+import { useAccountStore } from '@/store/account'+import { useUserStore } from '@/store/user'/*** Tiktok被点击* @param platType*/export async function tiktokSkip(platType: PlatType, spaceId?: string) {- if (platType !== PlatType.Tiktok) return;+ if (platType !== PlatType.Tiktok)+ return- const res: any = await getTiktokAuthUrlApi('pc', spaceId);- if (res?.code == 1) {- useUserStore.getState().logout();- return- }- if (res?.code !== 0) return;- const url = res.data.url;- window.open(`${url}`);+ const res: any = await getTiktokAuthUrlApi('pc', spaceId)+ if (res?.code == 1) {+ useUserStore.getState().logout()+ return+ }+ if (res?.code !== 0)+ return+ const url = res.data.url+ window.open(`${url}`)- const tiktokLoginRes = await tiktokLogin(res.data.taskId);-+ const tiktokLoginRes = await tiktokLogin(res.data.taskId)}-export function tiktokLogin(taskId:any): Promise<any> {+export function tiktokLogin(taskId: any): Promise<any> {return new Promise(async (resolve, reject) => {try {- let pollCount = 0;- const maxPollCount = 30; // 最大轮询次数+ let pollCount = 0+ const maxPollCount = 30 // 最大轮询次数++ // 开始轮询检查授权状态+ const checkAuthStatus = async () => {+ try {+ pollCount+++ const authRess: any = await checkTiktokAuthApi(taskId)+ const authRes = authRess+ console.log('authRes', authRes)+ if (authRes?.code === 0 && authRes?.data.status == 1) {+ // message.success('授权成功');+ // useAccountStore+ const accountStore = useAccountStore.getState()+ await accountStore.getAccountList()+ resolve(authRes)+ return true+ }- // 开始轮询检查授权状态- const checkAuthStatus = async () => {- try {- pollCount++;- const authRess:any = await checkTiktokAuthApi(taskId);- let authRes = authRess;- console.log('authRes', authRes)- if (authRes?.code === 0 && authRes?.data.status == 1) {- // message.success('授权成功');- // useAccountStore- const accountStore = useAccountStore.getState();- await accountStore.getAccountList();- resolve(authRes);- return true;- }-- // 检查是否达到最大轮询次数- if (pollCount >= maxPollCount) {- console.log('达到最大轮询次数,停止轮询');- return true;- }-- // return false;- } catch (error) {- console.error('检查授权状态失败:', error);- return false;+ // 检查是否达到最大轮询次数+ if (pollCount >= maxPollCount) {+ console.log('达到最大轮询次数,停止轮询')+ return true}- };- // 设置轮询间隔- const interval = setInterval(async () => {- const isSuccess = await checkAuthStatus();- if (isSuccess) {- clearInterval(interval);- if (pollCount >= maxPollCount) {- reject(new Error('授权超时,已达到最大轮询次数'));- }+ // return false;+ }+ catch (error) {+ console.error('检查授权状态失败:', error)+ return false+ }+ }++ // 设置轮询间隔+ const interval = setInterval(async () => {+ const isSuccess = await checkAuthStatus()+ if (isSuccess) {+ clearInterval(interval)+ if (pollCount >= maxPollCount) {+ reject(new Error('授权超时,已达到最大轮询次数'))}- }, 2000);+ }+ }, 2000)- // 5分钟后自动停止轮询- setTimeout(() => {- clearInterval(interval);- // message.error('授权超时,请重试');- reject(new Error('授权超时'));- }, 5 * 60 * 1000);-- } catch (e) {- reject(e);+ // 5分钟后自动停止轮询+ setTimeout(() => {+ clearInterval(interval)+ // message.error('授权超时,请重试');+ reject(new Error('授权超时'))+ }, 5 * 60 * 1000)+ }+ catch (e) {+ reject(e)}- });+ })}diff --git a/project/web/src/app/[lng]/accounts/plat/TwtterLogin.ts b/project/web/src/app/[lng]/accounts/plat/TwtterLogin.tsindex c0b72fe8..13b73238 100644--- a/project/web/src/app/[lng]/accounts/plat/TwtterLogin.ts+++ b/project/web/src/app/[lng]/accounts/plat/TwtterLogin.ts@@ -1,85 +1,86 @@-import qs from "qs";-import { PlatType } from "@/app/config/platConfig";-import { getTwitterAuthUrlApi, apiCheckTwitterAuth } from "@/api/twitter";-import { useAccountStore } from "@/store/account";-import { useUserStore } from "@/store/user";-+import qs from 'qs'+import { apiCheckTwitterAuth, getTwitterAuthUrlApi } from '@/api/twitter'+import { PlatType } from '@/app/config/platConfig'+import { useAccountStore } from '@/store/account'+import { useUserStore } from '@/store/user'/*** b站被点击* @param platType*/export async function twitterSkip(platType: PlatType, spaceId?: string) {- if (platType !== PlatType.Twitter) return;+ if (platType !== PlatType.Twitter)+ return- const res: any = await getTwitterAuthUrlApi('pc', spaceId);- if (res?.code == 1) {- useUserStore.getState().logout();- return- }- if (res?.code !== 0) return;- const url = res.data.url;- window.open(`${url}`);+ const res: any = await getTwitterAuthUrlApi('pc', spaceId)+ if (res?.code == 1) {+ useUserStore.getState().logout()+ return+ }+ if (res?.code !== 0)+ return+ const url = res.data.url+ window.open(`${url}`)- const twitterLoginRes = await twitterLogin(res.data.taskId);-+ const twitterLoginRes = await twitterLogin(res.data.taskId)}-export function twitterLogin(taskId:any): Promise<any> {+export function twitterLogin(taskId: any): Promise<any> {return new Promise(async (resolve, reject) => {try {- let pollCount = 0;- const maxPollCount = 30; // 最大轮询次数+ let pollCount = 0+ const maxPollCount = 30 // 最大轮询次数- // 开始轮询检查授权状态- const checkAuthStatus = async () => {- try {- pollCount++;- const authRess:any = await apiCheckTwitterAuth(taskId);- let authRes = authRess;- console.log('authRes', authRes)- if (authRes?.code === 0 && authRes?.data.status == 1) {- // message.success('授权成功');- // useAccountStore- const accountStore = useAccountStore.getState();- await accountStore.getAccountList();- resolve(authRes);- return true;- }-- // 检查是否达到最大轮询次数- if (pollCount >= maxPollCount) {- console.log('达到最大轮询次数,停止轮询');- return true;- }-- // return false;- } catch (error) {- console.error('检查授权状态失败:', error);- return false;+ // 开始轮询检查授权状态+ const checkAuthStatus = async () => {+ try {+ pollCount+++ const authRess: any = await apiCheckTwitterAuth(taskId)+ const authRes = authRess+ console.log('authRes', authRes)+ if (authRes?.code === 0 && authRes?.data.status == 1) {+ // message.success('授权成功');+ // useAccountStore+ const accountStore = useAccountStore.getState()+ await accountStore.getAccountList()+ resolve(authRes)+ return true}- };- // 设置轮询间隔- const interval = setInterval(async () => {- const isSuccess = await checkAuthStatus();- if (isSuccess) {- clearInterval(interval);- if (pollCount >= maxPollCount) {- reject(new Error('授权超时,已达到最大轮询次数'));- }+ // 检查是否达到最大轮询次数+ if (pollCount >= maxPollCount) {+ console.log('达到最大轮询次数,停止轮询')+ return true}- }, 2000);- // 5分钟后自动停止轮询- setTimeout(() => {- clearInterval(interval);- // message.error('授权超时,请重试');- reject(new Error('授权超时'));- }, 5 * 60 * 1000);-- } catch (e) {- reject(e);+ // return false;+ }+ catch (error) {+ console.error('检查授权状态失败:', error)+ return false+ }+ }++ // 设置轮询间隔+ const interval = setInterval(async () => {+ const isSuccess = await checkAuthStatus()+ if (isSuccess) {+ clearInterval(interval)+ if (pollCount >= maxPollCount) {+ reject(new Error('授权超时,已达到最大轮询次数'))+ }+ }+ }, 2000)++ // 5分钟后自动停止轮询+ setTimeout(() => {+ clearInterval(interval)+ // message.error('授权超时,请重试');+ reject(new Error('授权超时'))+ }, 5 * 60 * 1000)+ }+ catch (e) {+ reject(e)}- });+ })}diff --git a/project/web/src/app/[lng]/accounts/plat/WxGzh.ts b/project/web/src/app/[lng]/accounts/plat/WxGzh.tsindex 12ce90e9..4af553cd 100644--- a/project/web/src/app/[lng]/accounts/plat/WxGzh.ts+++ b/project/web/src/app/[lng]/accounts/plat/WxGzh.ts@@ -1,85 +1,86 @@-import qs from "qs";-import { PlatType } from "@/app/config/platConfig";-import { checkWxGzAuthApi, getWxGzhAuthUrlApi } from "@/api/platAuth";-import { useAccountStore } from "@/store/account";-import { useUserStore } from "@/store/user";-+import qs from 'qs'+import { checkWxGzAuthApi, getWxGzhAuthUrlApi } from '@/api/platAuth'+import { PlatType } from '@/app/config/platConfig'+import { useAccountStore } from '@/store/account'+import { useUserStore } from '@/store/user'/*** 微信被点击* @param platType*/export async function wxGzhSkip(platType: PlatType, spaceId?: string) {- if (platType !== PlatType.WxGzh) return;+ if (platType !== PlatType.WxGzh)+ return- const res: any = await getWxGzhAuthUrlApi('pc', spaceId);+ const res: any = await getWxGzhAuthUrlApi('pc', spaceId)if (res?.code == 1) {- useUserStore.getState().logout();- return- }- if (res?.code !== 0) return;- const url = res.data.url;- window.open(`${url}`);+ useUserStore.getState().logout()+ return+ }+ if (res?.code !== 0)+ return+ const url = res.data.url+ window.open(`${url}`)- const wxGzhLoginRes = await wxGzhLogin(res.data.id);-+ const wxGzhLoginRes = await wxGzhLogin(res.data.id)}-export function wxGzhLogin(taskId:any): Promise<any> {+export function wxGzhLogin(taskId: any): Promise<any> {return new Promise(async (resolve, reject) => {try {- let pollCount = 0;- const maxPollCount = 30; // 最大轮询次数+ let pollCount = 0+ const maxPollCount = 30 // 最大轮询次数- // 开始轮询检查授权状态- const checkAuthStatus = async () => {- try {- pollCount++;- const authRess:any = await checkWxGzAuthApi(taskId);- let authRes = authRess;- console.log('authRes', authRes)- if (authRes?.code === 0 && authRes?.data.status == 1) {- // message.success('授权成功');- // useAccountStore- const accountStore = useAccountStore.getState();- await accountStore.getAccountList();- resolve(authRes);- return true;- }-- // 检查是否达到最大轮询次数- if (pollCount >= maxPollCount) {- console.log('达到最大轮询次数,停止轮询');- return true;- }-- // return false;- } catch (error) {- console.error('检查授权状态失败:', error);- return false;+ // 开始轮询检查授权状态+ const checkAuthStatus = async () => {+ try {+ pollCount+++ const authRess: any = await checkWxGzAuthApi(taskId)+ const authRes = authRess+ console.log('authRes', authRes)+ if (authRes?.code === 0 && authRes?.data.status == 1) {+ // message.success('授权成功');+ // useAccountStore+ const accountStore = useAccountStore.getState()+ await accountStore.getAccountList()+ resolve(authRes)+ return true}- };- // 设置轮询间隔- const interval = setInterval(async () => {- const isSuccess = await checkAuthStatus();- if (isSuccess) {- clearInterval(interval);- if (pollCount >= maxPollCount) {- reject(new Error('授权超时,已达到最大轮询次数'));- }+ // 检查是否达到最大轮询次数+ if (pollCount >= maxPollCount) {+ console.log('达到最大轮询次数,停止轮询')+ return true}- }, 2000);- // 5分钟后自动停止轮询- setTimeout(() => {- clearInterval(interval);- // message.error('授权超时,请重试');- reject(new Error('授权超时'));- }, 5 * 60 * 1000);-- } catch (e) {- reject(e);+ // return false;+ }+ catch (error) {+ console.error('检查授权状态失败:', error)+ return false+ }+ }++ // 设置轮询间隔+ const interval = setInterval(async () => {+ const isSuccess = await checkAuthStatus()+ if (isSuccess) {+ clearInterval(interval)+ if (pollCount >= maxPollCount) {+ reject(new Error('授权超时,已达到最大轮询次数'))+ }+ }+ }, 2000)++ // 5分钟后自动停止轮询+ setTimeout(() => {+ clearInterval(interval)+ // message.error('授权超时,请重试');+ reject(new Error('授权超时'))+ }, 5 * 60 * 1000)+ }+ catch (e) {+ reject(e)}- });+ })}diff --git a/project/web/src/app/[lng]/accounts/plat/YoutubeLogin.ts b/project/web/src/app/[lng]/accounts/plat/YoutubeLogin.tsindex a3fc113a..0a2ce475 100644--- a/project/web/src/app/[lng]/accounts/plat/YoutubeLogin.ts+++ b/project/web/src/app/[lng]/accounts/plat/YoutubeLogin.ts@@ -1,85 +1,86 @@-import qs from "qs";-import { PlatType } from "@/app/config/platConfig";-import { getYouTubeAuthUrlApi, apiCheckYoutubeAuth } from "@/api/platAuth";-import { useAccountStore } from "@/store/account";-import { useUserStore } from "@/store/user";-+import qs from 'qs'+import { apiCheckYoutubeAuth, getYouTubeAuthUrlApi } from '@/api/platAuth'+import { PlatType } from '@/app/config/platConfig'+import { useAccountStore } from '@/store/account'+import { useUserStore } from '@/store/user'/*** b站被点击* @param platType*/export async function youtubeSkip(platType: PlatType, spaceId?: string) {- if (platType !== PlatType.YouTube) return;+ if (platType !== PlatType.YouTube)+ return- const res: any = await getYouTubeAuthUrlApi('pc', spaceId);+ const res: any = await getYouTubeAuthUrlApi('pc', spaceId)if (res?.code == 1) {- useUserStore.getState().logout();- return- }- if (res?.code !== 0) return;- const url = res.data.url;- window.open(`${url}`);+ useUserStore.getState().logout()+ return+ }+ if (res?.code !== 0)+ return+ const url = res.data.url+ window.open(`${url}`)- const youtubeLoginRes = await youtubeLogin(res.data.taskId);-+ const youtubeLoginRes = await youtubeLogin(res.data.taskId)}-export function youtubeLogin(taskId:any): Promise<any> {+export function youtubeLogin(taskId: any): Promise<any> {return new Promise(async (resolve, reject) => {try {- let pollCount = 0;- const maxPollCount = 30; // 最大轮询次数+ let pollCount = 0+ const maxPollCount = 30 // 最大轮询次数- // 开始轮询检查授权状态- const checkAuthStatus = async () => {- try {- pollCount++;- const authRess:any = await apiCheckYoutubeAuth(taskId);- let authRes = authRess;- console.log('authRes', authRes)- if (authRes?.code === 0 && authRes?.data.status == 1) {- // message.success('授权成功');- // useAccountStore- const accountStore = useAccountStore.getState();- await accountStore.getAccountList();- resolve(authRes);- return true;- }-- // 检查是否达到最大轮询次数- if (pollCount >= maxPollCount) {- console.log('达到最大轮询次数,停止轮询');- return true;- }-- // return false;- } catch (error) {- console.error('检查授权状态失败:', error);- return false;+ // 开始轮询检查授权状态+ const checkAuthStatus = async () => {+ try {+ pollCount+++ const authRess: any = await apiCheckYoutubeAuth(taskId)+ const authRes = authRess+ console.log('authRes', authRes)+ if (authRes?.code === 0 && authRes?.data.status == 1) {+ // message.success('授权成功');+ // useAccountStore+ const accountStore = useAccountStore.getState()+ await accountStore.getAccountList()+ resolve(authRes)+ return true}- };- // 设置轮询间隔- const interval = setInterval(async () => {- const isSuccess = await checkAuthStatus();- if (isSuccess) {- clearInterval(interval);- if (pollCount >= maxPollCount) {- reject(new Error('授权超时,已达到最大轮询次数'));- }+ // 检查是否达到最大轮询次数+ if (pollCount >= maxPollCount) {+ console.log('达到最大轮询次数,停止轮询')+ return true}- }, 2000);- // 5分钟后自动停止轮询- setTimeout(() => {- clearInterval(interval);- // message.error('授权超时,请重试');- reject(new Error('授权超时'));- }, 5 * 60 * 1000);-- } catch (e) {- reject(e);+ // return false;+ }+ catch (error) {+ console.error('检查授权状态失败:', error)+ return false+ }+ }++ // 设置轮询间隔+ const interval = setInterval(async () => {+ const isSuccess = await checkAuthStatus()+ if (isSuccess) {+ clearInterval(interval)+ if (pollCount >= maxPollCount) {+ reject(new Error('授权超时,已达到最大轮询次数'))+ }+ }+ }, 2000)++ // 5分钟后自动停止轮询+ setTimeout(() => {+ clearInterval(interval)+ // message.error('授权超时,请重试');+ reject(new Error('授权超时'))+ }, 5 * 60 * 1000)+ }+ catch (e) {+ reject(e)}- });+ })}diff --git a/project/web/src/app/[lng]/accounts/plat/kwaiLogin.ts b/project/web/src/app/[lng]/accounts/plat/kwaiLogin.tsindex 6e871b30..ee00560e 100644--- a/project/web/src/app/[lng]/accounts/plat/kwaiLogin.ts+++ b/project/web/src/app/[lng]/accounts/plat/kwaiLogin.ts@@ -1,36 +1,38 @@-import { PlatType } from "@/app/config/platConfig";-import { createKwaiAuth, getKwaiAuthStatus } from "@/api/plat/kwai";-import { sleep } from "@/utils";-import { useAccountStore } from "@/store/account";-import { useUserStore } from "@/store/user";+import type { PlatType } from '@/app/config/platConfig'+import { createKwaiAuth, getKwaiAuthStatus } from '@/api/plat/kwai'+import { useAccountStore } from '@/store/account'+import { useUserStore } from '@/store/user'+import { sleep } from '@/utils'export async function kwaiSkip(platType: PlatType, spaceId?: string) {- const res = await createKwaiAuth("pc", spaceId);+ const res = await createKwaiAuth('pc', spaceId)if (res?.code == 1) {- useUserStore.getState().logout();- return- }- if (!res?.data) return;- window.open(res?.data.url);+ useUserStore.getState().logout()+ return+ }+ if (!res?.data)+ return+ window.open(res?.data.url)++ let queryCount = 0+ const maxQueryCount = 30 // 最大轮询次数- let queryCount = 0;- const maxQueryCount = 30; // 最大轮询次数-while (queryCount < maxQueryCount) {- const autoStatusRes = await getKwaiAuthStatus(res.data.taskId);-- if (!autoStatusRes?.data) break;+ const autoStatusRes = await getKwaiAuthStatus(res.data.taskId)++ if (!autoStatusRes?.data)+ breakif (autoStatusRes.data.status === 1) {- useAccountStore.getState().getAccountList();- break;+ useAccountStore.getState().getAccountList()+ break}- queryCount++;- await sleep(1000);+ queryCount+++ await sleep(1000)}-+// 如果达到最大轮询次数仍未成功,记录日志if (queryCount >= maxQueryCount) {- console.log('快手授权达到最大轮询次数,停止轮询');+ console.log('快手授权达到最大轮询次数,停止轮询')}}diff --git a/project/web/src/app/[lng]/aiRank/aiRanking/aiRanking.module.scss b/project/web/src/app/[lng]/aiRank/aiRanking/aiRanking.module.scssindex ff9566c4..8890fb3e 100644--- a/project/web/src/app/[lng]/aiRank/aiRanking/aiRanking.module.scss+++ b/project/web/src/app/[lng]/aiRank/aiRanking/aiRanking.module.scss@@ -22,7 +22,8 @@.ant-tag {margin-top: 6px;}- &-up, &-down {+ &-up,+ &-down {width: 100%;display: flex;align-items: center;@@ -57,7 +58,7 @@.aiRanking-topthree {width: 30px;color: #fff;- background: url("../images/bg-rank-index.png") no-repeat center / cover;+ background: url('../images/bg-rank-index.png') no-repeat center / cover;}.ant-table-thead {th {diff --git a/project/web/src/app/[lng]/aiRank/aiRanking/echarts-weekPie.ts b/project/web/src/app/[lng]/aiRank/aiRanking/echarts-weekPie.tsindex c59721fd..68967d1b 100644--- a/project/web/src/app/[lng]/aiRank/aiRanking/echarts-weekPie.ts+++ b/project/web/src/app/[lng]/aiRank/aiRanking/echarts-weekPie.ts@@ -1,43 +1,42 @@-import * as echarts from "echarts";+import * as echarts from 'echarts'-type EChartsOption = echarts.EChartsOption;+type EChartsOption = echarts.EChartsOption-const initWeepPie = (- chartDom: HTMLDivElement,- data: {- value: number;- name: string;- }[],-) => {- if (!chartDom) return;- const myChart = echarts.init(chartDom);+function initWeepPie(chartDom: HTMLDivElement, data: {+ value: number+ name: string+}[]) {+ if (!chartDom)+ return+ const myChart = echarts.init(chartDom)const option: EChartsOption = {tooltip: {- trigger: "item",+ trigger: 'item',formatter: (params: any) => {- const total = data.reduce((sum, item) => sum + item.value, 0);- const percent = (((params.value as number) / total) * 100).toFixed(2); // 计算百分比并保留两位小数- return `${params.name}: ${params.value} (${percent}%)`; // 格式化显示文本+ const total = data.reduce((sum, item) => sum + item.value, 0)+ const percent = (((params.value as number) / total) * 100).toFixed(2) // 计算百分比并保留两位小数+ return `${params.name}: ${params.value} (${percent}%)` // 格式化显示文本},},series: [{- type: "pie",- radius: "60%",+ type: 'pie',+ radius: '60%',label: {formatter: (params: any) => {- const total = data.reduce((sum, item) => sum + item.value, 0);- const percent = ((params.value / total) * 100).toFixed(0); // 百分比- return `${params.name} ${params.value}(${percent}%) `; // 自定义显示名称、数值和百分比+ const total = data.reduce((sum, item) => sum + item.value, 0)+ const percent = ((params.value / total) * 100).toFixed(0) // 百分比+ return `${params.name} ${params.value}(${percent}%) ` // 自定义显示名称、数值和百分比},},data,},],- };+ }- if (option) myChart.setOption(option);-};+ if (option)+ myChart.setOption(option)+}-export default initWeepPie;+export default initWeepPiediff --git a/project/web/src/app/[lng]/aiRank/aiRanking/page.tsx b/project/web/src/app/[lng]/aiRank/aiRanking/page.tsxindex 46d68257..ecae81c1 100644--- a/project/web/src/app/[lng]/aiRank/aiRanking/page.tsx+++ b/project/web/src/app/[lng]/aiRank/aiRanking/page.tsx@@ -1,123 +1,132 @@-"use client";+'use client'-import styles from "./aiRanking.module.scss";-import RankingTags from "../components/RankingTags";-import Cycleselects, { CycleTypeEnum } from "../components/CycleSelects";-import { useEffect, useMemo, useRef, useState } from "react";-import { Avatar, Popover, Table, TableProps, Tag, Tooltip } from "antd";+import type { TableProps } from 'antd'+import type {+ AiToolsRankingItemType,+ GetAiToolsRankingApiParams,+} from '@/api/types/platform.type'import {CaretDownOutlined,CaretUpOutlined,QuestionCircleOutlined,SearchOutlined,-} from "@ant-design/icons";-import initWeepPie from "./echarts-weekPie";-import {- AiToolsRankingItemType,- GetAiToolsRankingApiParams,-} from "@/api/types/platform.type";-import { platformApi } from "@/api/hot";+} from '@ant-design/icons'+import { Avatar, Popover, Table, Tag, Tooltip } from 'antd'+import { useEffect, useMemo, useRef, useState } from 'react'+import { platformApi } from '@/api/hot'+import Cycleselects, { CycleTypeEnum } from '../components/CycleSelects'+import RankingTags from '../components/RankingTags'+import styles from './aiRanking.module.scss'+import initWeepPie from './echarts-weekPie'const optionsTags = [{- label: "总榜",- value: "1",+ label: '总榜',+ value: '1',},{- label: "国内榜",- value: "2",+ label: '国内榜',+ value: '2',},{- label: "国外榜",- value: "3",+ label: '国外榜',+ value: '3',},-];+]function parseChineseNumber(input: string): number {- if (!input) return 0;+ if (!input)+ return 0const units: { [key: string]: number } = {千: 1000,万: 10000,亿: 100000000,- };+ }- let result = 0;- let currentNumber = 0;- let decimalPart = 0;- let isDecimal = false;- let decimalScale = 0.1;+ let result = 0+ let currentNumber = 0+ let decimalPart = 0+ let isDecimal = false+ let decimalScale = 0.1for (const char of input) {- if (char === ".") {- isDecimal = true; // 标记进入小数部分- continue;+ if (char === '.') {+ isDecimal = true // 标记进入小数部分+ continue}if (char in units) {if (isDecimal) {- result += (currentNumber + decimalPart) * units[char];- } else {- result += currentNumber * units[char];+ result += (currentNumber + decimalPart) * units[char]+ }+ else {+ result += currentNumber * units[char]}- currentNumber = 0;- decimalPart = 0;- isDecimal = false;- decimalScale = 0.1;- } else {- const num = parseInt(char, 10);- if (!isNaN(num)) {+ currentNumber = 0+ decimalPart = 0+ isDecimal = false+ decimalScale = 0.1+ }+ else {+ const num = Number.parseInt(char, 10)+ if (!Number.isNaN(num)) {if (isDecimal) {- decimalPart += num * decimalScale;- decimalScale *= 0.1;- } else {- currentNumber = currentNumber * 10 + num;+ decimalPart += num * decimalScale+ decimalScale *= 0.1+ }+ else {+ currentNumber = currentNumber * 10 + num}}}}// 如果最后还有剩余的数字或小数部分,直接加到结果里- result += currentNumber + decimalPart;+ result += currentNumber + decimalPart- return result;+ return result}export default function Page() {const [params, setParams] = useState<GetAiToolsRankingApiParams>({- dateType: "",- startDate: "",- area: "1",- });- const [loading, setLoading] = useState(false);- const [data, setData] = useState<AiToolsRankingItemType[]>([]);- const aiRankingContentRef = useRef<HTMLDivElement>(null);+ dateType: '',+ startDate: '',+ area: '1',+ })+ const [loading, setLoading] = useState(false)+ const [data, setData] = useState<AiToolsRankingItemType[]>([])+ const aiRankingContentRef = useRef<HTMLDivElement>(null)useEffect(() => {- if (params.dateType === "" || params.startDate === "") return;- if (loading) return;- setLoading(true);+ if (params.dateType === '' || params.startDate === '')+ return+ if (loading)+ return+ setLoading(true)platformApi.getAiToolsRankingApi(params).then((res) => {- setLoading(false);- setData(res?.data.items ?? []);- document.querySelector(".ant-table-body")!.scrollTo(0, 0);+ setLoading(false)+ setData(res?.data.items ?? [])+ document.querySelector('.ant-table-body')!.scrollTo(0, 0)})- .catch(() => setLoading(false));- }, [params]);+ .catch(() => setLoading(false))+ }, [params])const columns = useMemo(() => {- const columns: TableProps<AiToolsRankingItemType>["columns"] = [+ const columns: TableProps<AiToolsRankingItemType>['columns'] = [{- title: () => <p style={{ textAlign: "center" }}>#</p>,+ title: () => <p style={{ textAlign: 'center' }}>#</p>,render: (text, prm, ind) => {return (<div className="aiRanking-rank">- {ind <= 2 ? (- <div className="aiRanking-topthree">{ind + 1}</div>- ) : (- <span>{ind + 1}</span>- )}+ {ind <= 2+ ? (+ <div className="aiRanking-topthree">{ind + 1}</div>+ )+ : (+ <span>{ind + 1}</span>+ )}{prm.rankChange > 0 && (<Tag className="aiRanking-rank-up" color="error"><CaretUpOutlined />@@ -131,19 +140,19 @@ export default function Page() {</Tag>)}</div>- );+ )},- width: "40px",- key: "序号",+ width: '40px',+ key: '序号',},{- title: "产品名",+ title: '产品名',render: (text, prm) => {return (<div className="aiRanking-productName"><Avatar src={prm.cover} size="large" /><div className="aiRanking-productName-con">- <label style={{ marginBottom: "4px", display: "inline-block" }}>+ <label style={{ marginBottom: '4px', display: 'inline-block' }}>{prm.title}</label><div@@ -154,13 +163,13 @@ export default function Page() {</div></div></div>- );+ )},width: 250,- key: "title",+ key: 'title',},{- title: "标签",+ title: '标签',render: (text, prm) => {return (<div className="aiRanking-productName">@@ -168,31 +177,31 @@ export default function Page() {{prm.intro}</div></div>- );+ )},width: 200,- key: "title",+ key: 'title',},{- title: "月访问量",+ title: '月访问量',render: (text, prm) => {- return prm.stats.viewCount;+ return prm.stats.viewCount},sorter: (a, b) =>- parseChineseNumber(b.stats.viewCount) -- parseChineseNumber(a.stats.viewCount),+ parseChineseNumber(b.stats.viewCount)+ - parseChineseNumber(a.stats.viewCount),width: 80,- key: "title",+ key: 'title',},{- title: "月下载量",+ title: '月下载量',render: (text, prm) => {- return prm.downCount;+ return prm.downCount},sorter: (a, b) =>parseChineseNumber(b.downCount) - parseChineseNumber(a.downCount),width: 80,- key: "月下载量",+ key: '月下载量',},{title: () => {@@ -203,7 +212,7 @@ export default function Page() {</Tooltip>周提及量</>- );+ )},sorter: (a, b) => b.referCount - a.referCount,render: (text, prm, ind) => {@@ -216,10 +225,10 @@ export default function Page() {<><divclassName={`weekChat${ind}`}- style={{ width: "350px", height: "200px" }}+ style={{ width: '350px', height: '200px' }}/></>- );+ )}}onOpenChange={() => {setTimeout(() => {@@ -228,20 +237,20 @@ export default function Page() {Object.keys(prm.detail).map((key) => {return {name: key,- value: prm.detail[key as "抖音"],- };+ value: prm.detail[key as '抖音'],+ }}),- );- }, 10);+ )+ }, 10)}}><SearchOutlined /></Popover></>- );+ )},width: 90,- key: "referCount",+ key: 'referCount',},{title: () => {@@ -252,14 +261,14 @@ export default function Page() {</Tooltip>声望值</>- );+ )},sorter: (a, b) => b.volumeCount - a.volumeCount,render: (text, prm) => {- return prm.volumeCount;+ return prm.volumeCount},width: 80,- key: "volumeCount",+ key: 'volumeCount',},{title: () => {@@ -270,28 +279,32 @@ export default function Page() {</Tooltip>综合评分</>- );+ )},sorter: (a, b) => b.exponentCount - a.exponentCount,render: (text, prm) => {return (- <span style={{ color: "var(--colorPrimary6)" }}>+ <span style={{ color: 'var(--colorPrimary6)' }}>{prm.exponentCount}</span>- );+ )},width: 90,- key: "exponentCount",+ key: 'exponentCount',},- ];- return columns;- }, []);+ ]+ return columns+ }, [])return (<div className={styles.aiRanking}><div className="aiRanking-title">- AI工具排行榜 · {optionsTags.find((v) => v.value === params.area)?.label}{" "}- ·{params.dateType === CycleTypeEnum.Week ? "周榜" : "月榜"}+ AI工具排行榜 ·+ {' '}+ {optionsTags.find(v => v.value === params.area)?.label}+ {' '}+ ·+ {params.dateType === CycleTypeEnum.Week ? '周榜' : '月榜'}</div><div className="aiRanking-head"><div className="aiRanking-head-item">@@ -301,10 +314,10 @@ export default function Page() {defaultValue={optionsTags[0].value}onChange={(val) => {setParams((prevState) => {- const newState = { ...prevState };- newState.area = val;- return newState;- });+ const newState = { ...prevState }+ newState.area = val+ return newState+ })}}/></div>@@ -315,11 +328,11 @@ export default function Page() {defaultType={CycleTypeEnum.Week}onChange={(v) => {setParams((prevState) => {- const newState = { ...prevState };- newState.dateType = v.type;- newState.startDate = v.value;- return newState;- });+ const newState = { ...prevState }+ newState.dateType = v.type+ newState.startDate = v.value+ return newState+ })}}/></div>@@ -340,5 +353,5 @@ export default function Page() {/></div></div>- );+ )}diff --git a/project/web/src/app/[lng]/aiRank/components/CycleSelects/cycleSelects.module.scss b/project/web/src/app/[lng]/aiRank/components/CycleSelects/cycleSelects.module.scssindex f76f73fc..3ce9f09d 100644--- a/project/web/src/app/[lng]/aiRank/components/CycleSelects/cycleSelects.module.scss+++ b/project/web/src/app/[lng]/aiRank/components/CycleSelects/cycleSelects.module.scss@@ -21,4 +21,4 @@}}}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/aiRank/components/CycleSelects/index.tsx b/project/web/src/app/[lng]/aiRank/components/CycleSelects/index.tsxindex fb1074f8..a0e07fe1 100644--- a/project/web/src/app/[lng]/aiRank/components/CycleSelects/index.tsx+++ b/project/web/src/app/[lng]/aiRank/components/CycleSelects/index.tsx@@ -1,30 +1,31 @@-import { ForwardedRef, forwardRef, memo, useEffect, useState } from "react";-import styles from "./cycleSelects.module.scss";-import { Button, Select } from "antd";-import dayjs from "dayjs";-import isoWeek from "dayjs/plugin/isoWeek";+import type { ForwardedRef } from 'react'+import { Button, Select } from 'antd'+import dayjs from 'dayjs'+import isoWeek from 'dayjs/plugin/isoWeek'+import { forwardRef, memo, useEffect, useState } from 'react'+import styles from './cycleSelects.module.scss'-dayjs.extend(isoWeek);+dayjs.extend(isoWeek)export enum CycleTypeEnum {- Week = "week",- Month = "month",+ Week = 'week',+ Month = 'month',}-type CycleItemType = {- value: string;- label: string;-};+interface CycleItemType {+ value: string+ label: string+}export interface ICycleselectsRef {}export interface ICycleselectsProps {- onChange: (params: { type: CycleTypeEnum; value: string }) => void;- defaultType: CycleTypeEnum;- disable?: boolean;+ onChange: (params: { type: CycleTypeEnum, value: string }) => void+ defaultType: CycleTypeEnum+ disable?: boolean}-const CycleseCore = ({+function CycleseCore({title,options,onChange,@@ -32,27 +33,29 @@ const CycleseCore = ({isActive,value,}: {- onChange: (value: string) => void;- title: string;- options: CycleItemType[];- onActiveClick: () => void;- isActive: boolean;- value: string;-}) => {+ onChange: (value: string) => void+ title: string+ options: CycleItemType[]+ onActiveClick: () => void+ isActive: boolean+ value: string+}) {return (<div className="cycleSelects-item">{isActive}- {isActive ? (- <>- <div className="cycleSelects-item-label">{title}</div>- <Select options={options} value={value} onChange={onChange}></Select>- </>- ) : (- <Button onClick={onActiveClick}>{title}</Button>- )}+ {isActive+ ? (+ <>+ <div className="cycleSelects-item-label">{title}</div>+ <Select options={options} value={value} onChange={onChange}></Select>+ </>+ )+ : (+ <Button onClick={onActiveClick}>{title}</Button>+ )}</div>- );-};+ )+}/*** 获取指定数量的月份@@ -60,18 +63,18 @@ const CycleseCore = ({* @param {number} numberOfMonths 获取的月份数*/function getMonths(skipMonths: number, numberOfMonths: number) {- const currentMonth = dayjs().startOf("month"); // 当前月的开始时间- const months: CycleItemType[] = [];+ const currentMonth = dayjs().startOf('month') // 当前月的开始时间+ const months: CycleItemType[] = []for (let i = 0; i < numberOfMonths; i++) {- const month = currentMonth.subtract(skipMonths + i + 1, "month");+ const month = currentMonth.subtract(skipMonths + i + 1, 'month')months.push({- label: month.format("YYYY年MM月"),- value: month.format("YYYY-MM-DD"),- });+ label: month.format('YYYY年MM月'),+ value: month.format('YYYY-MM-DD'),+ })}- return months;+ return months}/**@@ -80,21 +83,21 @@ function getMonths(skipMonths: number, numberOfMonths: number) {* @param {number} numberOfWeeks 获取的周数*/function getWeekRanges(skipWeeks: number, numberOfWeeks: number) {- const currentWeekStart = dayjs().startOf("isoWeek"); // 当前周的开始时间(周一)- const ranges: CycleItemType[] = [];+ const currentWeekStart = dayjs().startOf('isoWeek') // 当前周的开始时间(周一)+ const ranges: CycleItemType[] = []for (let i = 0; i < numberOfWeeks; i++) {const startOfWeek = currentWeekStart- .subtract(skipWeeks + i + 1, "week")- .startOf("isoWeek");- const endOfWeek = startOfWeek.endOf("isoWeek");+ .subtract(skipWeeks + i + 1, 'week')+ .startOf('isoWeek')+ const endOfWeek = startOfWeek.endOf('isoWeek')ranges.push({- label: `${startOfWeek.format("MM月DD日")} - ${endOfWeek.format("MM月DD日")}`,- value: startOfWeek.format("YYYY-MM-DD"),- });+ label: `${startOfWeek.format('MM月DD日')} - ${endOfWeek.format('MM月DD日')}`,+ value: startOfWeek.format('YYYY-MM-DD'),+ })}- return ranges;+ return ranges}/**@@ -103,18 +106,18 @@ function getWeekRanges(skipWeeks: number, numberOfWeeks: number) {* @param {number} numberOfDays 获取的天数*/function getDays(skipDays: number, numberOfDays: number) {- const currentDay = dayjs().startOf("day"); // 当前天的起始时间- const days: CycleItemType[] = [];+ const currentDay = dayjs().startOf('day') // 当前天的起始时间+ const days: CycleItemType[] = []for (let i = 0; i < numberOfDays; i++) {- const day = currentDay.subtract(skipDays + i + 1, "day");+ const day = currentDay.subtract(skipDays + i + 1, 'day')days.push({- value: day.format("YYYY年MM月DD日"),- label: day.format("YYYY-MM-DD"),- });+ value: day.format('YYYY年MM月DD日'),+ label: day.format('YYYY-MM-DD'),+ })}- return days;+ return days}const Cycleselects = memo(@@ -124,41 +127,43 @@ const Cycleselects = memo(ref: ForwardedRef<ICycleselectsRef>,) => {// 1周榜 2=月榜- const [active, setActive] = useState<CycleTypeEnum>(defaultType);- const [value, setValue] = useState("");- const [weekOptions, setWeekOptions] = useState<CycleItemType[]>([]);- const [monthsOptions, setMonthsOptions] = useState<CycleItemType[]>([]);+ const [active, setActive] = useState<CycleTypeEnum>(defaultType)+ const [value, setValue] = useState('')+ const [weekOptions, setWeekOptions] = useState<CycleItemType[]>([])+ const [monthsOptions, setMonthsOptions] = useState<CycleItemType[]>([])useEffect(() => {- const weekOptions = getWeekRanges(1, 3);- setWeekOptions(weekOptions);+ const weekOptions = getWeekRanges(1, 3)+ setWeekOptions(weekOptions)- const monthsOptions = getMonths(0, 3);- setMonthsOptions(monthsOptions);+ const monthsOptions = getMonths(0, 3)+ setMonthsOptions(monthsOptions)if (defaultType === CycleTypeEnum.Week) {- setValue(weekOptions[0].value);+ setValue(weekOptions[0].value)}- }, []);+ }, [])useEffect(() => {- if (!value) return;+ if (!value)+ returnonChange({type: active,value,- });- }, [value]);+ })+ }, [value])useEffect(() => {if (active === CycleTypeEnum.Week) {- if (weekOptions[0]?.value) setValue(weekOptions[0]?.value);- return;+ if (weekOptions[0]?.value)+ setValue(weekOptions[0]?.value)+ return}if (active === CycleTypeEnum.Month) {- if (monthsOptions[0]?.value) setValue(monthsOptions[0]?.value);- return;+ if (monthsOptions[0]?.value)+ setValue(monthsOptions[0]?.value)}- }, [active]);+ }, [active])return (<div className={styles.cycleSelects}>@@ -166,8 +171,9 @@ const Cycleselects = memo(value={value}isActive={active === CycleTypeEnum.Week}onActiveClick={() => {- if (disable) return;- setActive(CycleTypeEnum.Week);+ if (disable)+ return+ setActive(CycleTypeEnum.Week)}}onChange={setValue}title="周榜"@@ -178,18 +184,19 @@ const Cycleselects = memo(value={value}isActive={active === CycleTypeEnum.Month}onActiveClick={() => {- if (disable) return;- setActive(CycleTypeEnum.Month);+ if (disable)+ return+ setActive(CycleTypeEnum.Month)}}onChange={setValue}title="月榜"options={monthsOptions}/></div>- );+ )},),-);-Cycleselects.displayName = "Cycleselects";+)+Cycleselects.displayName = 'Cycleselects'-export default Cycleselects;+export default Cycleselectsdiff --git a/project/web/src/app/[lng]/aiRank/components/RankingTags/index.tsx b/project/web/src/app/[lng]/aiRank/components/RankingTags/index.tsxindex 882c9819..b300b1bf 100644--- a/project/web/src/app/[lng]/aiRank/components/RankingTags/index.tsx+++ b/project/web/src/app/[lng]/aiRank/components/RankingTags/index.tsx@@ -1,16 +1,17 @@-import { ForwardedRef, forwardRef, memo, useState } from "react";-import styles from "./rankingTags.module.scss";+import type { ForwardedRef } from 'react'+import { forwardRef, memo, useState } from 'react'+import styles from './rankingTags.module.scss'export interface IRankingtagsRef {}export interface IRankingtagsProps {options: {- label: string;- value: string;- }[];- defaultValue: string;- disable?: boolean;- onChange: (value: string) => void;+ label: string+ value: string+ }[]+ defaultValue: string+ disable?: boolean+ onChange: (value: string) => void}const Rankingtags = memo(@@ -19,7 +20,7 @@ const Rankingtags = memo({ options, defaultValue, disable, onChange }: IRankingtagsProps,ref: ForwardedRef<IRankingtagsRef>,) => {- const [activeValue, setActiveValue] = useState(defaultValue);+ const [activeValue, setActiveValue] = useState(defaultValue)return (<div className={styles.rankingTags}>@@ -27,25 +28,26 @@ const Rankingtags = memo(return (<divclassName={[- "rankingTags-tag",- activeValue === v.value ? "rankingTags-tag--active" : "",- ].join(" ")}+ 'rankingTags-tag',+ activeValue === v.value ? 'rankingTags-tag--active' : '',+ ].join(' ')}key={v.value}onClick={() => {- if (disable) return;- onChange(v.value);- setActiveValue(v.value);+ if (disable)+ return+ onChange(v.value)+ setActiveValue(v.value)}}>{v.label}</div>- );+ )})}</div>- );+ )},),-);-Rankingtags.displayName = "Rankingtags";+)+Rankingtags.displayName = 'Rankingtags'-export default Rankingtags;+export default Rankingtagsdiff --git a/project/web/src/app/[lng]/aiRank/components/RankingTags/rankingTags.module.scss b/project/web/src/app/[lng]/aiRank/components/RankingTags/rankingTags.module.scssindex 2d22f8dc..1445889a 100644--- a/project/web/src/app/[lng]/aiRank/components/RankingTags/rankingTags.module.scss+++ b/project/web/src/app/[lng]/aiRank/components/RankingTags/rankingTags.module.scss@@ -20,4 +20,4 @@}}}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/aiRank/layout.tsx b/project/web/src/app/[lng]/aiRank/layout.tsxindex 8ea3d6dd..2cef5094 100644--- a/project/web/src/app/[lng]/aiRank/layout.tsx+++ b/project/web/src/app/[lng]/aiRank/layout.tsx@@ -1,53 +1,54 @@-"use client";-import { Menu, MenuProps } from "antd";-import styles from "./aiRank.module.scss";-import Ranking from "./svgs/ranking.svg";-import Icon from "@ant-design/icons";-import { usePathname, useRouter, useSearchParams } from "next/navigation";-import { useEffect, useState } from "react";-import { removeLocalePrefix } from "@/app/layout/layout.utils";+'use client'+import type { MenuProps } from 'antd'+import Icon from '@ant-design/icons'+import { Menu } from 'antd'+import { usePathname, useRouter, useSearchParams } from 'next/navigation'+import { useEffect, useState } from 'react'+import { removeLocalePrefix } from '@/app/layout/layout.utils'+import styles from './aiRank.module.scss'+import Ranking from './svgs/ranking.svg'-type MenuItem = Required<MenuProps>["items"][number];+type MenuItem = Required<MenuProps>['items'][number]const items: MenuItem[] = [{- key: "/aiRank/aiRanking",- label: "AI工具排行榜",+ key: '/aiRank/aiRanking',+ label: 'AI工具排行榜',icon: <Icon component={Ranking} />,},].map((v) => {// @ts-ignore- v.label = <span title={v.label}>{v.label}</span>;- return v;-});+ v.label = <span title={v.label}>{v.label}</span>+ return v+})export default function AiRankLayout({children,}: {- children: React.ReactNode;+ children: React.ReactNode}) {- const router = useRouter();- const pathname = usePathname();- const searchParams = useSearchParams();- const [currChooseRoute, setCurrChooseRoute] = useState<string>();+ const router = useRouter()+ const pathname = usePathname()+ const searchParams = useSearchParams()+ const [currChooseRoute, setCurrChooseRoute] = useState<string>()useEffect(() => {- setCurrChooseRoute(removeLocalePrefix(pathname));- }, [pathname, searchParams]);+ setCurrChooseRoute(removeLocalePrefix(pathname))+ }, [pathname, searchParams])return (<div className={styles.aiRank}><Menu- selectedKeys={[currChooseRoute || ""]}+ selectedKeys={[currChooseRoute || '']}style={{ width: 200 }}inlineIndent={15}mode="inline"items={items}onClick={(e) => {- router.push(e.key as string);+ router.push(e.key as string)}}/>{children}</div>- );+ )}diff --git a/project/web/src/app/[lng]/aiRank/page.tsx b/project/web/src/app/[lng]/aiRank/page.tsxindex 1551ab49..89b94f8d 100644--- a/project/web/src/app/[lng]/aiRank/page.tsx+++ b/project/web/src/app/[lng]/aiRank/page.tsx@@ -1,16 +1,16 @@-"use client";+'use client'-import { useRouter } from "next/navigation";-import { useEffect } from "react";+import { useRouter } from 'next/navigation'+import { useEffect } from 'react'-const App = () => {- const router = useRouter();+function App() {+ const router = useRouter()useEffect(() => {- router.replace("/aiRank/aiRanking");- }, [router]);+ router.replace('/aiRank/aiRanking')+ }, [router])- return null;-};+ return null+}-export default App;+export default Appdiff --git a/project/web/src/app/[lng]/cgmaterial/cgmaterialPageCore.tsx b/project/web/src/app/[lng]/cgmaterial/cgmaterialPageCore.tsxindex d28c4fa0..0519c130 100644--- a/project/web/src/app/[lng]/cgmaterial/cgmaterialPageCore.tsx+++ b/project/web/src/app/[lng]/cgmaterial/cgmaterialPageCore.tsx@@ -1,161 +1,162 @@-"use client";--import { useEffect, useState } from "react";-import { Button, Form, Input, Select, Modal, message, Space, InputNumber, List, Card, Spin, Avatar } from "antd";-import styles from "./styles/cgmaterial.module.scss";-import publishDialogStyles from "@/components/PublishDialog/publishDialog.module.scss";+'use client'++import type { EngagementPostsParams } from '@/api/types/engagement'+import { DeleteOutlined, EditOutlined, FileTextOutlined, FolderOpenOutlined, ImportOutlined, PlusOutlined, VideoCameraOutlined } from '@ant-design/icons'+import { Avatar, Button, Card, Form, Input, InputNumber, List, message, Modal, Select, Space, Spin } from 'antd'+import { useParams } from 'next/navigation'+import { useEffect, useState } from 'react'+import { getAccountListApi } from '@/api/account'+import { getChatModels } from '@/api/ai'+import { apiGetEngagementPosts } from '@/api/engagement'import {- apiCreateMaterialGroup,- apiGetMaterialGroupList,- apiGetMaterialList,apiCreateMaterial,+ apiCreateMaterialGroup,apiCreateMaterialTask,- apiStartMaterialTask,apiDeleteMaterialGroup,- apiUpdateMaterialGroupInfo,+ apiGetMaterialGroupList,+ apiGetMaterialList,apiPreviewMaterialTask,+ apiStartMaterialTask,apiUpdateMaterial,-} from "@/api/material";-import { getMediaGroupList, getMediaList } from "@/api/media";-import { getOssUrl } from "@/utils/oss";-import { EditOutlined, DeleteOutlined, PlusOutlined, ImportOutlined, FileTextOutlined, FolderOpenOutlined, VideoCameraOutlined } from '@ant-design/icons';-import { getAccountListApi } from "@/api/account";-import { apiGetEngagementPosts } from "@/api/engagement";-import { apiImportPostsRecord, apiGetPostsRecordStatus } from "@/api/statistics";-import { PlatType } from "@/app/config/platConfig";-import { PublishStatus } from "@/api/plat/types/publish.types";-import { EngagementPostsParams, EngagementPostsResponse } from "@/api/types/engagement";-import { useTransClient } from "@/app/i18n/client";-import { PubType } from "@/app/config/publishConfig";-import { useParams } from "next/navigation";-import { getChatModels } from "@/api/ai";-import AvatarPlat from "@/components/AvatarPlat";-import { useUserStore } from "@/store/user";-import VipContentModal from "@/components/modals/VipContentModal";--const { TextArea } = Input;+ apiUpdateMaterialGroupInfo,+} from '@/api/material'+import { getMediaGroupList, getMediaList } from '@/api/media'+import { PublishStatus } from '@/api/plat/types/publish.types'+import { apiGetPostsRecordStatus, apiImportPostsRecord } from '@/api/statistics'+import { EngagementPostsResponse } from '@/api/types/engagement'+import { PlatType } from '@/app/config/platConfig'+import { PubType } from '@/app/config/publishConfig'+import { useTransClient } from '@/app/i18n/client'+import AvatarPlat from '@/components/AvatarPlat'+import VipContentModal from '@/components/modals/VipContentModal'+import publishDialogStyles from '@/components/PublishDialog/publishDialog.module.scss'+import { useUserStore } from '@/store/user'+import { getOssUrl } from '@/utils/oss'+import styles from './styles/cgmaterial.module.scss'++const { TextArea } = Inputexport default function CgMaterialPageCore() {- const { t } = useTransClient('cgmaterial');- const { lng } = useParams();- const userStore = useUserStore();-+ const { t } = useTransClient('cgmaterial')+ const { lng } = useParams()+ const userStore = useUserStore()+// VIP 弹窗相关- const [vipModalVisible, setVipModalVisible] = useState(false);-+ const [vipModalVisible, setVipModalVisible] = useState(false)+// 草稿箱组相关- const [groupList, setGroupList] = useState<any[]>([]);- const [groupLoading, setGroupLoading] = useState(false);- const [createGroupModal, setCreateGroupModal] = useState(false);- const [selectedGroup, setSelectedGroup] = useState<any>(null);+ const [groupList, setGroupList] = useState<any[]>([])+ const [groupLoading, setGroupLoading] = useState(false)+ const [createGroupModal, setCreateGroupModal] = useState(false)+ const [selectedGroup, setSelectedGroup] = useState<any>(null)// 组内草稿素材相关- const [materialList, setMaterialList] = useState<any[]>([]);- const [materialLoading, setMaterialLoading] = useState(false);+ const [materialList, setMaterialList] = useState<any[]>([])+ const [materialLoading, setMaterialLoading] = useState(false)// 创建素材弹窗相关- const [createModal, setCreateModal] = useState(false);- const [mediaGroupModal, setMediaGroupModal] = useState(false);- const [mediaGroups, setMediaGroups] = useState<any[]>([]);- const [selectedMediaGroup, setSelectedMediaGroup] = useState<any>(null);- const [mediaList, setMediaList] = useState<any[]>([]);- const [selectedCover, setSelectedCover] = useState<string | null>(null);- const [selectedMaterials, setSelectedMaterials] = useState<string[]>([]);-+ const [createModal, setCreateModal] = useState(false)+ const [mediaGroupModal, setMediaGroupModal] = useState(false)+ const [mediaGroups, setMediaGroups] = useState<any[]>([])+ const [selectedMediaGroup, setSelectedMediaGroup] = useState<any>(null)+ const [mediaList, setMediaList] = useState<any[]>([])+ const [selectedCover, setSelectedCover] = useState<string | null>(null)+ const [selectedMaterials, setSelectedMaterials] = useState<string[]>([])+// 视频组专用:封面组和视频组分别选择- const [coverGroupModal, setCoverGroupModal] = useState(false);- const [videoGroupModal, setVideoGroupModal] = useState(false);- const [coverGroups, setCoverGroups] = useState<any[]>([]);- const [videoGroups, setVideoGroups] = useState<any[]>([]);- const [selectedCoverGroup, setSelectedCoverGroup] = useState<any>(null);- const [selectedVideoGroup, setSelectedVideoGroup] = useState<any>(null);- const [coverList, setCoverList] = useState<any[]>([]);- const [videoList, setVideoList] = useState<any[]>([]);-+ const [coverGroupModal, setCoverGroupModal] = useState(false)+ const [videoGroupModal, setVideoGroupModal] = useState(false)+ const [coverGroups, setCoverGroups] = useState<any[]>([])+ const [videoGroups, setVideoGroups] = useState<any[]>([])+ const [selectedCoverGroup, setSelectedCoverGroup] = useState<any>(null)+ const [selectedVideoGroup, setSelectedVideoGroup] = useState<any>(null)+ const [coverList, setCoverList] = useState<any[]>([])+ const [videoList, setVideoList] = useState<any[]>([])+// 单个素材位置- const [singleLocation, setSingleLocation] = useState<[number, number]>([0, 0]);+ const [singleLocation, setSingleLocation] = useState<[number, number]>([0, 0])// 创建/批量表单- const [form] = Form.useForm();- const [batchForm] = Form.useForm();- const [createGroupForm] = Form.useForm();- const [creating, setCreating] = useState(false);- const [batchModal, setBatchModal] = useState(false);- const [batchTaskLoading, setBatchTaskLoading] = useState(false);- const [chatModels, setChatModels] = useState<any[]>([]);- const [chatModelsLoading, setChatModelsLoading] = useState(false);+ const [form] = Form.useForm()+ const [batchForm] = Form.useForm()+ const [createGroupForm] = Form.useForm()+ const [creating, setCreating] = useState(false)+ const [batchModal, setBatchModal] = useState(false)+ const [batchTaskLoading, setBatchTaskLoading] = useState(false)+ const [chatModels, setChatModels] = useState<any[]>([])+ const [chatModelsLoading, setChatModelsLoading] = useState(false)// 批量生成草稿相关- const [batchMediaGroups, setBatchMediaGroups] = useState<string[]>([]);- const [batchCoverGroup, setBatchCoverGroup] = useState<string>("");- const [batchLocation, setBatchLocation] = useState<[number, number]>([0, 0]);+ const [batchMediaGroups, setBatchMediaGroups] = useState<string[]>([])+ const [batchCoverGroup, setBatchCoverGroup] = useState<string>('')+ const [batchLocation, setBatchLocation] = useState<[number, number]>([0, 0])// 预览相关- const [currentTaskId, setCurrentTaskId] = useState<string | null>(null);- const [lastTaskParams, setLastTaskParams] = useState<any>(null);- const [previewModal, setPreviewModal] = useState(false);- const [previewLoading, setPreviewLoading] = useState(false);- const [previewList, setPreviewList] = useState<any[]>([]);- const [previewData, setPreviewData] = useState<any>(null);+ const [currentTaskId, setCurrentTaskId] = useState<string | null>(null)+ const [lastTaskParams, setLastTaskParams] = useState<any>(null)+ const [previewModal, setPreviewModal] = useState(false)+ const [previewLoading, setPreviewLoading] = useState(false)+ const [previewList, setPreviewList] = useState<any[]>([])+ const [previewData, setPreviewData] = useState<any>(null)- const [detailModal, setDetailModal] = useState(false);- const [detailData, setDetailData] = useState<any>(null);+ const [detailModal, setDetailModal] = useState(false)+ const [detailData, setDetailData] = useState<any>(null)// 编辑组相关- const [editGroupModal, setEditGroupModal] = useState(false);- const [editGroupName, setEditGroupName] = useState("");- const [editingGroup, setEditingGroup] = useState<any>(null);- const [editLoading, setEditLoading] = useState(false);+ const [editGroupModal, setEditGroupModal] = useState(false)+ const [editGroupName, setEditGroupName] = useState('')+ const [editingGroup, setEditingGroup] = useState<any>(null)+ const [editLoading, setEditLoading] = useState(false)// 编辑素材相关- const [editMaterialModal, setEditMaterialModal] = useState(false);- const [editingMaterial, setEditingMaterial] = useState<any>(null);- const [editMaterialForm] = Form.useForm();- const [editMaterialLoading, setEditMaterialLoading] = useState(false);- const [editMaterialMediaGroups, setEditMaterialMediaGroups] = useState<any[]>([]);- const [editMaterialSelectedGroup, setEditMaterialSelectedGroup] = useState<any>(null);- const [editMaterialMediaList, setEditMaterialMediaList] = useState<any[]>([]);- const [editMaterialSelectedCover, setEditMaterialSelectedCover] = useState<string | null>(null);- const [editMaterialSelectedMaterials, setEditMaterialSelectedMaterials] = useState<string[]>([]);- const [editMaterialLocation, setEditMaterialLocation] = useState<[number, number]>([0, 0]);-+ const [editMaterialModal, setEditMaterialModal] = useState(false)+ const [editingMaterial, setEditingMaterial] = useState<any>(null)+ const [editMaterialForm] = Form.useForm()+ const [editMaterialLoading, setEditMaterialLoading] = useState(false)+ const [editMaterialMediaGroups, setEditMaterialMediaGroups] = useState<any[]>([])+ const [editMaterialSelectedGroup, setEditMaterialSelectedGroup] = useState<any>(null)+ const [editMaterialMediaList, setEditMaterialMediaList] = useState<any[]>([])+ const [editMaterialSelectedCover, setEditMaterialSelectedCover] = useState<string | null>(null)+ const [editMaterialSelectedMaterials, setEditMaterialSelectedMaterials] = useState<string[]>([])+ const [editMaterialLocation, setEditMaterialLocation] = useState<[number, number]>([0, 0])+// 编辑素材:视频组专用状态- const [editMaterialCoverGroups, setEditMaterialCoverGroups] = useState<any[]>([]);- const [editMaterialVideoGroups, setEditMaterialVideoGroups] = useState<any[]>([]);- const [editMaterialSelectedCoverGroup, setEditMaterialSelectedCoverGroup] = useState<any>(null);- const [editMaterialSelectedVideoGroup, setEditMaterialSelectedVideoGroup] = useState<any>(null);- const [editMaterialCoverList, setEditMaterialCoverList] = useState<any[]>([]);- const [editMaterialVideoList, setEditMaterialVideoList] = useState<any[]>([]);-+ const [editMaterialCoverGroups, setEditMaterialCoverGroups] = useState<any[]>([])+ const [editMaterialVideoGroups, setEditMaterialVideoGroups] = useState<any[]>([])+ const [editMaterialSelectedCoverGroup, setEditMaterialSelectedCoverGroup] = useState<any>(null)+ const [editMaterialSelectedVideoGroup, setEditMaterialSelectedVideoGroup] = useState<any>(null)+ const [editMaterialCoverList, setEditMaterialCoverList] = useState<any[]>([])+ const [editMaterialVideoList, setEditMaterialVideoList] = useState<any[]>([])+// 编辑素材弹窗状态- const [editMaterialCoverGroupModal, setEditMaterialCoverGroupModal] = useState(false);- const [editMaterialVideoGroupModal, setEditMaterialVideoGroupModal] = useState(false);+ const [editMaterialCoverGroupModal, setEditMaterialCoverGroupModal] = useState(false)+ const [editMaterialVideoGroupModal, setEditMaterialVideoGroupModal] = useState(false)// 记录显示操作按钮的组id- const [showActionsId, setShowActionsId] = useState<string | null>(null);+ const [showActionsId, setShowActionsId] = useState<string | null>(null)// 导入功能相关- const [importModal, setImportModal] = useState(false);- const [accountList, setAccountList] = useState<any[]>([]);- const [selectedAccount, setSelectedAccount] = useState<any>(null);- const [publishList, setPublishList] = useState<any[]>([]);- const [selectedPublishItems, setSelectedPublishItems] = useState<string[]>([]);- const [importLoading, setImportLoading] = useState(false);-+ const [importModal, setImportModal] = useState(false)+ const [accountList, setAccountList] = useState<any[]>([])+ const [selectedAccount, setSelectedAccount] = useState<any>(null)+ const [publishList, setPublishList] = useState<any[]>([])+ const [selectedPublishItems, setSelectedPublishItems] = useState<string[]>([])+ const [importLoading, setImportLoading] = useState(false)+// 分页相关状态const [pagination, setPagination] = useState({current: 1,pageSize: 10,total: 0,- hasMore: false- });- const [publishListLoading, setPublishListLoading] = useState(false);+ hasMore: false,+ })+ const [publishListLoading, setPublishListLoading] = useState(false)const renderMediaContent = (mediaList?: any[]) => {if (!Array.isArray(mediaList) || mediaList.length === 0) {- return <div style={{ color: '#888', marginTop: 8 }}>{t('detail.noMaterials' as any)}</div>;+ return <div style={{ color: '#888', marginTop: 8 }}>{t('detail.noMaterials' as any)}</div>}- const isSingle = mediaList.length === 1;+ const isSingle = mediaList.length === 1return (<div@@ -168,36 +169,42 @@ export default function CgMaterialPageCore() {>{mediaList.map((media, idx) => (<div key={idx} style={{ width: '100%' }}>- {media.type === 'video' ? (- <video- src={getOssUrl(media.url)}- controls- style={{ width: '100%', height: '320px', objectFit: 'cover', borderRadius: 8 }}- />- ) : (- <img- src={getOssUrl(media.url)}- alt={t('detail.materialImageAlt' as any)}- style={{ width: '100%', height: '320px', objectFit: 'cover', borderRadius: 8 }}- />- )}+ {media.type === 'video'+ ? (+ <video+ src={getOssUrl(media.url)}+ controls+ style={{ width: '100%', height: '320px', objectFit: 'cover', borderRadius: 8 }}+ />+ )+ : (+ <img+ src={getOssUrl(media.url)}+ alt={t('detail.materialImageAlt' as any)}+ style={{ width: '100%', height: '320px', objectFit: 'cover', borderRadius: 8 }}+ />+ )}</div>))}</div>- );- };+ )+ }const getMaterialTypeLabel = (type: string | undefined) => {- if (type === PubType.ImageText) return t('materialType.imageText' as any);- if (type === PubType.VIDEO) return t('materialType.video' as any);- return type || '';- };+ if (type === PubType.ImageText)+ return t('materialType.imageText' as any)+ if (type === PubType.VIDEO)+ return t('materialType.video' as any)+ return type || ''+ }const getMaterialStatusLabel = (status: number | undefined) => {- if (status === 0) return t('materialStatus.generating' as any);- if (status === 1) return t('materialStatus.completed' as any);- return '';- };+ if (status === 0)+ return t('materialStatus.generating' as any)+ if (status === 1)+ return t('materialStatus.completed' as any)+ return ''+ }const getImportStatusText = (status: string) => {const map: Record<string, string> = {@@ -205,224 +212,235 @@ export default function CgMaterialPageCore() {failed: t('import.status.failed' as any),running: t('import.status.running' as any),pending: t('import.status.pending' as any),- };- return map[status] || status;- };+ }+ return map[status] || status+ }// 初始化加载草稿箱组useEffect(() => {- fetchGroupList();- }, []);+ fetchGroupList()+ }, [])async function fetchGroupList() {- setGroupLoading(true);+ setGroupLoading(true)try {- const res = await apiGetMaterialGroupList(1, 50);- setGroupList(res?.data?.list || []);+ const res = await apiGetMaterialGroupList(1, 50)+ setGroupList(res?.data?.list || [])if (!selectedGroup && res?.data?.list?.length) {- setSelectedGroup(res.data.list[0]);+ setSelectedGroup(res.data.list[0])}- } catch (e) {- message.error(t('createGroup.getGroupsFailed'));- } finally {- setGroupLoading(false);+ }+ catch (e) {+ message.error(t('createGroup.getGroupsFailed'))+ }+ finally {+ setGroupLoading(false)}}// 选中组后加载组内素材useEffect(() => {if (selectedGroup && selectedGroup._id) {- fetchMaterialList(selectedGroup._id);+ fetchMaterialList(selectedGroup._id)}- }, [selectedGroup]);+ }, [selectedGroup])async function fetchMaterialList(groupId: string) {- setMaterialLoading(true);+ setMaterialLoading(true)try {- const res = await apiGetMaterialList(groupId, 1, 50);+ const res = await apiGetMaterialList(groupId, 1, 50)// @ts-ignore- setMaterialList(res?.data?.list || []);- } catch (e) {- message.error(t('createGroup.getMaterialsFailed'));- } finally {- setMaterialLoading(false);+ setMaterialList(res?.data?.list || [])+ }+ catch (e) {+ message.error(t('createGroup.getMaterialsFailed'))+ }+ finally {+ setMaterialLoading(false)}}// 创建草稿箱组async function handleCreateGroup() {try {- const values = await createGroupForm.validateFields();- setCreating(true);+ const values = await createGroupForm.validateFields()+ setCreating(true)await apiCreateMaterialGroup({type: values.type,name: values.name,desc: values.desc || '',- });- message.success(t('createGroup.createSuccess'));- setCreateGroupModal(false);- createGroupForm.resetFields();- fetchGroupList();- } catch (e: any) {- if (e?.errorFields) {- message.warning(t('pleaseCompleteForm'));- } else {- message.error(t('createGroup.createFailed'));- }- } finally {- setCreating(false);+ })+ message.success(t('createGroup.createSuccess'))+ setCreateGroupModal(false)+ createGroupForm.resetFields()+ fetchGroupList()+ }+ catch (e: any) {+ if (e?.errorFields) {+ message.warning(t('pleaseCompleteForm'))+ }+ else {+ message.error(t('createGroup.createFailed'))+ }+ }+ finally {+ setCreating(false)}}// 打开创建素材弹窗时,先加载媒体组async function openCreateMaterialModal() {- setCreateModal(true);- setMediaGroupModal(true);- setSelectedMediaGroup(null);- setMediaList([]);- setSelectedCover(null);- setSelectedMaterials([]);-+ setCreateModal(true)+ setMediaGroupModal(true)+ setSelectedMediaGroup(null)+ setMediaList([])+ setSelectedCover(null)+ setSelectedMaterials([])+// 重置视频组专用状态- setSelectedCoverGroup(null);- setSelectedVideoGroup(null);- setCoverList([]);- setVideoList([]);-+ setSelectedCoverGroup(null)+ setSelectedVideoGroup(null)+ setCoverList([])+ setVideoList([])+// 根据草稿箱组类型过滤媒体组- const res = await getMediaGroupList(1, 50);- const allGroups = ((res?.data as any)?.list as any[]) || [];-+ const res = await getMediaGroupList(1, 50)+ const allGroups = ((res?.data as any)?.list as any[]) || []+// 根据当前选中的草稿箱组类型过滤媒体组if (selectedGroup) {if (selectedGroup.type === PubType.ImageText) {// 图文组:只能选择图片组- const filteredGroups = allGroups.filter((g: any) => g.type === 'img');- setMediaGroups(filteredGroups);- } else if (selectedGroup.type === PubType.VIDEO) {+ const filteredGroups = allGroups.filter((g: any) => g.type === 'img')+ setMediaGroups(filteredGroups)+ }+ else if (selectedGroup.type === PubType.VIDEO) {// 视频组:分别设置封面组(图片组)和视频组- const imgGroups = allGroups.filter((g: any) => g.type === 'img');- const videoGroups = allGroups.filter((g: any) => g.type === 'video');- setCoverGroups(imgGroups);- setVideoGroups(videoGroups);- setMediaGroups([]); // 清空普通媒体组+ const imgGroups = allGroups.filter((g: any) => g.type === 'img')+ const videoGroups = allGroups.filter((g: any) => g.type === 'video')+ setCoverGroups(imgGroups)+ setVideoGroups(videoGroups)+ setMediaGroups([]) // 清空普通媒体组}- } else {- setMediaGroups(allGroups);}-+ else {+ setMediaGroups(allGroups)+ }+// 获取地理位置if (navigator.geolocation) {navigator.geolocation.getCurrentPosition((pos) => {- setSingleLocation([pos.coords.longitude, pos.coords.latitude]);- form.setFieldsValue({ location: [pos.coords.longitude, pos.coords.latitude] });+ setSingleLocation([pos.coords.longitude, pos.coords.latitude])+ form.setFieldsValue({ location: [pos.coords.longitude, pos.coords.latitude] })},() => {- setSingleLocation([0, 0]);- form.setFieldsValue({ location: [0, 0] });- }- );- } else {- setSingleLocation([0, 0]);- form.setFieldsValue({ location: [0, 0] });+ setSingleLocation([0, 0])+ form.setFieldsValue({ location: [0, 0] })+ },+ )+ }+ else {+ setSingleLocation([0, 0])+ form.setFieldsValue({ location: [0, 0] })}}// 选择媒体组后,加载资源async function handleSelectMediaGroup(group: any) {- setSelectedMediaGroup(group);- setMediaGroupModal(false);- const res = await getMediaList(group._id, 1, 100);+ setSelectedMediaGroup(group)+ setMediaGroupModal(false)+ const res = await getMediaList(group._id, 1, 100)// @ts-ignore- setMediaList(res?.data?.list || []);- setSelectedCover(null);- setSelectedMaterials([]);+ setMediaList(res?.data?.list || [])+ setSelectedCover(null)+ setSelectedMaterials([])}// 选择封面组后,加载封面资源async function handleSelectCoverGroup(group: any) {- setSelectedCoverGroup(group);- setCoverGroupModal(false);- const res = await getMediaList(group._id, 1, 100);+ setSelectedCoverGroup(group)+ setCoverGroupModal(false)+ const res = await getMediaList(group._id, 1, 100)// @ts-ignore- setCoverList(res?.data?.list || []);- setSelectedCover(null);+ setCoverList(res?.data?.list || [])+ setSelectedCover(null)}// 选择视频组后,加载视频资源async function handleSelectVideoGroup(group: any) {- setSelectedVideoGroup(group);- setVideoGroupModal(false);- const res = await getMediaList(group._id, 1, 100);+ setSelectedVideoGroup(group)+ setVideoGroupModal(false)+ const res = await getMediaList(group._id, 1, 100)// @ts-ignore- setVideoList(res?.data?.list || []);- setSelectedMaterials([]);+ setVideoList(res?.data?.list || [])+ setSelectedMaterials([])}// 创建单个素材async function handleCreateMaterial() {- await form.validateFields(); // 先校验- const values = form.getFieldsValue(); // 再获取所有值-+ await form.validateFields() // 先校验+ const values = form.getFieldsValue() // 再获取所有值+// 根据草稿箱组类型进行不同的验证if (selectedGroup.type === PubType.ImageText) {// 图文组:必须有媒体组、封面和素材,且都是图片if (!selectedMediaGroup) {- message.warning(t('createMaterial.selectMediaGroup'));- return;+ message.warning(t('createMaterial.selectMediaGroup'))+ return}if (!selectedCover || selectedMaterials.length === 0) {- message.warning(t('createMaterial.selectCoverAndMaterials'));- return;+ message.warning(t('createMaterial.selectCoverAndMaterials'))+ return}// 检查是否都是图片类型- const selectedMediaItems = mediaList.filter((m: any) =>- selectedMaterials.includes(m.url) || selectedCover === m.url- );- const hasVideo = selectedMediaItems.some((m: any) => m.type === 'video');+ const selectedMediaItems = mediaList.filter((m: any) =>+ selectedMaterials.includes(m.url) || selectedCover === m.url,+ )+ const hasVideo = selectedMediaItems.some((m: any) => m.type === 'video')if (hasVideo) {- message.warning(t('createMaterial.imageGroupOnly'));- return;+ message.warning(t('createMaterial.imageGroupOnly'))+ return}- } else if (selectedGroup.type === PubType.VIDEO) {+ }+ else if (selectedGroup.type === PubType.VIDEO) {// 视频组:必须有封面组、视频组、封面和视频素材if (!selectedCoverGroup) {- message.warning(t('createMaterial.selectCoverGroupRequired'));- return;+ message.warning(t('createMaterial.selectCoverGroupRequired'))+ return}if (!selectedVideoGroup) {- message.warning(t('createMaterial.selectVideoGroupRequired'));- return;+ message.warning(t('createMaterial.selectVideoGroupRequired'))+ return}if (!selectedCover) {- message.warning(t('createMaterial.selectCoverRequired'));- return;+ message.warning(t('createMaterial.selectCoverRequired'))+ return}if (selectedMaterials.length === 0) {- message.warning(t('createMaterial.selectVideoRequired'));- return;+ message.warning(t('createMaterial.selectVideoRequired'))+ return}// 检查封面是否为图片- const coverItem = coverList.find((m: any) => m.url === selectedCover);+ const coverItem = coverList.find((m: any) => m.url === selectedCover)if (coverItem && coverItem.type !== 'img') {- message.warning(t('createMaterial.coverMustBeImage'));- return;+ message.warning(t('createMaterial.coverMustBeImage'))+ return}// 检查素材是否都是视频- const selectedMediaItems = videoList.filter((m: any) => selectedMaterials.includes(m.url));- const hasImage = selectedMediaItems.some((m: any) => m.type === 'img');+ const selectedMediaItems = videoList.filter((m: any) => selectedMaterials.includes(m.url))+ const hasImage = selectedMediaItems.some((m: any) => m.type === 'img')if (hasImage) {- message.warning(t('createMaterial.videoGroupOnly'));- return;+ message.warning(t('createMaterial.videoGroupOnly'))+ return}}-- setCreating(true);++ setCreating(true)try {// 根据类型使用不同的媒体列表- const finalMediaList = selectedGroup.type === PubType.VIDEO ? videoList : mediaList;-+ const finalMediaList = selectedGroup.type === PubType.VIDEO ? videoList : mediaList+await apiCreateMaterial({groupId: selectedGroup._id,coverUrl: selectedCover || undefined,@@ -437,68 +455,73 @@ export default function CgMaterialPageCore() {desc: values.desc,option: {},location: singleLocation,- });- message.success(t('createMaterial.createSuccess'));- setCreateModal(false);+ })+ message.success(t('createMaterial.createSuccess'))+ setCreateModal(false)// 重置创建素材相关状态- setSelectedMediaGroup(null);- setMediaList([]);- setSelectedCover(null);- setSelectedMaterials([]);- setSelectedCoverGroup(null);- setSelectedVideoGroup(null);- setCoverList([]);- setVideoList([]);- setMediaGroupModal(false);- setCoverGroupModal(false);- setVideoGroupModal(false);- form.resetFields();- fetchMaterialList(selectedGroup._id);- } catch (e) {- message.error(t('createMaterial.createFailed'));- } finally {- setCreating(false);+ setSelectedMediaGroup(null)+ setMediaList([])+ setSelectedCover(null)+ setSelectedMaterials([])+ setSelectedCoverGroup(null)+ setSelectedVideoGroup(null)+ setCoverList([])+ setVideoList([])+ setMediaGroupModal(false)+ setCoverGroupModal(false)+ setVideoGroupModal(false)+ form.resetFields()+ fetchMaterialList(selectedGroup._id)+ }+ catch (e) {+ message.error(t('createMaterial.createFailed'))+ }+ finally {+ setCreating(false)}}// 打开批量生成草稿弹窗时,拉取媒体组和定位async function openBatchModal() {- setBatchModal(true);+ setBatchModal(true)// 拉取媒体组- const res = await getMediaGroupList(1, 50);- setMediaGroups(((res?.data as any)?.list as any[]) || []);+ const res = await getMediaGroupList(1, 50)+ setMediaGroups(((res?.data as any)?.list as any[]) || [])// 拉取聊天大模型try {- setChatModelsLoading(true);- const chatRes = await getChatModels();- setChatModels(((chatRes?.data as any[]) || []));- } catch (e) {+ setChatModelsLoading(true)+ const chatRes = await getChatModels()+ setChatModels(((chatRes?.data as any[]) || []))+ }+ catch (e) {// 忽略加载失败,不阻塞弹窗- setChatModels([]);- } finally {- setChatModelsLoading(false);+ setChatModels([])+ }+ finally {+ setChatModelsLoading(false)}// 获取地理位置if (navigator.geolocation) {navigator.geolocation.getCurrentPosition((pos) => {- setBatchLocation([pos.coords.longitude, pos.coords.latitude]);- batchForm.setFieldsValue({ location: [pos.coords.longitude, pos.coords.latitude] });+ setBatchLocation([pos.coords.longitude, pos.coords.latitude])+ batchForm.setFieldsValue({ location: [pos.coords.longitude, pos.coords.latitude] })},() => {- setBatchLocation([0, 0]);- batchForm.setFieldsValue({ location: [0, 0] });- }- );- } else {- setBatchLocation([0, 0]);- batchForm.setFieldsValue({ location: [0, 0] });+ setBatchLocation([0, 0])+ batchForm.setFieldsValue({ location: [0, 0] })+ },+ )+ }+ else {+ setBatchLocation([0, 0])+ batchForm.setFieldsValue({ location: [0, 0] })}}// 生成任务参数function getBatchTaskParams() {- const values = batchForm.getFieldsValue();+ const values = batchForm.getFieldsValue()return {groupId: selectedGroup?._id,num: values.num,@@ -511,238 +534,250 @@ export default function CgMaterialPageCore() {mediaGroups: batchMediaGroups,coverGroup: batchCoverGroup,option: {},- };+ }}// 预览批量生成草稿async function handlePreviewMaterial() {- const values = await batchForm.validateFields();- const params: any = getBatchTaskParams();+ const values = await batchForm.validateFields()+ const params: any = getBatchTaskParams()// 判断参数是否变化if (!lastTaskParams || JSON.stringify(params) !== JSON.stringify(lastTaskParams)) {- setCurrentTaskId(null);- setLastTaskParams(params);+ setCurrentTaskId(null)+ setLastTaskParams(params)}- setPreviewLoading(true);- let taskId = currentTaskId;+ setPreviewLoading(true)+ let taskId = currentTaskIdtry {if (!taskId) {- const res = await apiCreateMaterialTask(params);- taskId = res?.data?._id || null;- setCurrentTaskId(taskId ?? null);+ const res = await apiCreateMaterialTask(params)+ taskId = res?.data?._id || null+ setCurrentTaskId(taskId ?? null)}if (taskId) {- const res = await apiPreviewMaterialTask(taskId);+ const res = await apiPreviewMaterialTask(taskId)// @ts-ignore- setPreviewData(res?.data?.data || null);- setPreviewModal(true);- } else {- message.error(t('batchGenerate.previewFailed'));+ setPreviewData(res?.data?.data || null)+ setPreviewModal(true)}- } catch (e) {- message.error(t('batchGenerate.previewFailed'));- } finally {- setPreviewLoading(false);+ else {+ message.error(t('batchGenerate.previewFailed'))+ }+ }+ catch (e) {+ message.error(t('batchGenerate.previewFailed'))+ }+ finally {+ setPreviewLoading(false)}}// 批量生成草稿async function handleBatchMaterial() {- const values = await batchForm.validateFields();- const params: any = getBatchTaskParams();- setBatchTaskLoading(true);+ const values = await batchForm.validateFields()+ const params: any = getBatchTaskParams()+ setBatchTaskLoading(true)try {- let taskId = currentTaskId;+ let taskId = currentTaskId// 如果参数变化或没有taskId,重新创建if (!lastTaskParams || JSON.stringify(params) !== JSON.stringify(lastTaskParams)) {- const res = await apiCreateMaterialTask(params);- taskId = res?.data?._id || null;- setCurrentTaskId(taskId ?? null);- setLastTaskParams(params);+ const res = await apiCreateMaterialTask(params)+ taskId = res?.data?._id || null+ setCurrentTaskId(taskId ?? null)+ setLastTaskParams(params)}if (taskId) {- await apiStartMaterialTask(taskId);- message.success(t('batchGenerate.taskStarted'));- setBatchModal(false);- batchForm.resetFields();- fetchMaterialList(selectedGroup._id);- setCurrentTaskId(null);- setLastTaskParams(null);+ await apiStartMaterialTask(taskId)+ message.success(t('batchGenerate.taskStarted'))+ setBatchModal(false)+ batchForm.resetFields()+ fetchMaterialList(selectedGroup._id)+ setCurrentTaskId(null)+ setLastTaskParams(null)}- } catch (e) {- message.error(t('batchGenerate.generateFailed'));- } finally {- setBatchTaskLoading(false);+ }+ catch (e) {+ message.error(t('batchGenerate.generateFailed'))+ }+ finally {+ setBatchTaskLoading(false)}}// 处理编辑组async function handleEditGroup() {- if (!editGroupName) return message.warning(t('editGroup.enterName' as any));- setEditLoading(true);+ if (!editGroupName)+ return message.warning(t('editGroup.enterName' as any))+ setEditLoading(true)try {- await apiUpdateMaterialGroupInfo(editingGroup._id, { name: editGroupName });- message.success(t('sidebar.updateSuccess'));- setEditGroupModal(false);- setEditGroupName("");- setEditingGroup(null);- fetchGroupList();- } catch {- message.error(t('sidebar.updateFailed'));- } finally {- setEditLoading(false);+ await apiUpdateMaterialGroupInfo(editingGroup._id, { name: editGroupName })+ message.success(t('sidebar.updateSuccess'))+ setEditGroupModal(false)+ setEditGroupName('')+ setEditingGroup(null)+ fetchGroupList()+ }+ catch {+ message.error(t('sidebar.updateFailed'))+ }+ finally {+ setEditLoading(false)}}// 打开编辑素材弹窗async function openEditMaterialModal(material: any) {- setEditingMaterial(material);- setEditMaterialModal(true);-+ setEditingMaterial(material)+ setEditMaterialModal(true)+// 重置视频组专用状态- setEditMaterialSelectedCoverGroup(null);- setEditMaterialSelectedVideoGroup(null);- setEditMaterialCoverList([]);- setEditMaterialVideoList([]);-+ setEditMaterialSelectedCoverGroup(null)+ setEditMaterialSelectedVideoGroup(null)+ setEditMaterialCoverList([])+ setEditMaterialVideoList([])+// 加载媒体组- const res = await getMediaGroupList(1, 50);- const allGroups = ((res?.data as any)?.list as any[]) || [];-+ const res = await getMediaGroupList(1, 50)+ const allGroups = ((res?.data as any)?.list as any[]) || []+// 根据草稿箱组类型过滤媒体组if (selectedGroup) {if (selectedGroup.type === PubType.ImageText) {// 图文组:只能选择图片组- const filteredGroups = allGroups.filter((g: any) => g.type === 'img');- setEditMaterialMediaGroups(filteredGroups);- } else if (selectedGroup.type === PubType.VIDEO) {+ const filteredGroups = allGroups.filter((g: any) => g.type === 'img')+ setEditMaterialMediaGroups(filteredGroups)+ }+ else if (selectedGroup.type === PubType.VIDEO) {// 视频组:分别设置封面组(图片组)和视频组- const imgGroups = allGroups.filter((g: any) => g.type === 'img');- const videoGroups = allGroups.filter((g: any) => g.type === 'video');- setEditMaterialCoverGroups(imgGroups);- setEditMaterialVideoGroups(videoGroups);- setEditMaterialMediaGroups([]); // 清空普通媒体组+ const imgGroups = allGroups.filter((g: any) => g.type === 'img')+ const videoGroups = allGroups.filter((g: any) => g.type === 'video')+ setEditMaterialCoverGroups(imgGroups)+ setEditMaterialVideoGroups(videoGroups)+ setEditMaterialMediaGroups([]) // 清空普通媒体组}- } else {- setEditMaterialMediaGroups(allGroups);}-+ else {+ setEditMaterialMediaGroups(allGroups)+ }+// 设置表单初始值editMaterialForm.setFieldsValue({title: material.title,desc: material.desc,location: material.location || [0, 0],- });-+ })+// 设置封面和素材- setEditMaterialSelectedCover(material.coverUrl || null);- setEditMaterialSelectedMaterials(material.mediaList?.map((m: any) => m.url) || []);- setEditMaterialLocation(material.location || [0, 0]);-+ setEditMaterialSelectedCover(material.coverUrl || null)+ setEditMaterialSelectedMaterials(material.mediaList?.map((m: any) => m.url) || [])+ setEditMaterialLocation(material.location || [0, 0])+// 获取地理位置if (navigator.geolocation) {navigator.geolocation.getCurrentPosition((pos) => {- setEditMaterialLocation([pos.coords.longitude, pos.coords.latitude]);- editMaterialForm.setFieldsValue({ location: [pos.coords.longitude, pos.coords.latitude] });+ setEditMaterialLocation([pos.coords.longitude, pos.coords.latitude])+ editMaterialForm.setFieldsValue({ location: [pos.coords.longitude, pos.coords.latitude] })},() => {- setEditMaterialLocation([0, 0]);- editMaterialForm.setFieldsValue({ location: [0, 0] });- }- );- } else {- setEditMaterialLocation([0, 0]);- editMaterialForm.setFieldsValue({ location: [0, 0] });+ setEditMaterialLocation([0, 0])+ editMaterialForm.setFieldsValue({ location: [0, 0] })+ },+ )+ }+ else {+ setEditMaterialLocation([0, 0])+ editMaterialForm.setFieldsValue({ location: [0, 0] })}}// 选择编辑素材的媒体组async function handleEditMaterialSelectGroup(group: any) {- setEditMaterialSelectedGroup(group);- const res = await getMediaList(group._id, 1, 100);- setEditMaterialMediaList(((res?.data as any)?.list as any[]) || []);+ setEditMaterialSelectedGroup(group)+ const res = await getMediaList(group._id, 1, 100)+ setEditMaterialMediaList(((res?.data as any)?.list as any[]) || [])}// 选择编辑素材的封面组async function handleEditMaterialSelectCoverGroup(group: any) {- setEditMaterialSelectedCoverGroup(group);- setEditMaterialCoverGroupModal(false);- const res = await getMediaList(group._id, 1, 100);- setEditMaterialCoverList(((res?.data as any)?.list as any[]) || []);+ setEditMaterialSelectedCoverGroup(group)+ setEditMaterialCoverGroupModal(false)+ const res = await getMediaList(group._id, 1, 100)+ setEditMaterialCoverList(((res?.data as any)?.list as any[]) || [])}// 选择编辑素材的视频组async function handleEditMaterialSelectVideoGroup(group: any) {- setEditMaterialSelectedVideoGroup(group);- setEditMaterialVideoGroupModal(false);- const res = await getMediaList(group._id, 1, 100);- setEditMaterialVideoList(((res?.data as any)?.list as any[]) || []);+ setEditMaterialSelectedVideoGroup(group)+ setEditMaterialVideoGroupModal(false)+ const res = await getMediaList(group._id, 1, 100)+ setEditMaterialVideoList(((res?.data as any)?.list as any[]) || [])}// 更新素材async function handleUpdateMaterial() {- await editMaterialForm.validateFields();- const values = editMaterialForm.getFieldsValue();-+ await editMaterialForm.validateFields()+ const values = editMaterialForm.getFieldsValue()+// 根据草稿箱组类型进行不同的验证if (selectedGroup.type === PubType.ImageText) {// 图文组:必须有媒体组、封面和素材,且都是图片if (!editMaterialSelectedGroup) {- message.warning(t('createMaterial.selectMediaGroup'));- return;+ message.warning(t('createMaterial.selectMediaGroup'))+ return}if (!editMaterialSelectedCover || editMaterialSelectedMaterials.length === 0) {- message.warning(t('createMaterial.selectCoverAndMaterials'));- return;+ message.warning(t('createMaterial.selectCoverAndMaterials'))+ return}// 检查是否都是图片类型- const selectedMediaItems = editMaterialMediaList.filter((m: any) =>- editMaterialSelectedMaterials.includes(m.url) || editMaterialSelectedCover === m.url- );- const hasVideo = selectedMediaItems.some((m: any) => m.type === 'video');+ const selectedMediaItems = editMaterialMediaList.filter((m: any) =>+ editMaterialSelectedMaterials.includes(m.url) || editMaterialSelectedCover === m.url,+ )+ const hasVideo = selectedMediaItems.some((m: any) => m.type === 'video')if (hasVideo) {- message.warning(t('createMaterial.imageGroupOnly'));- return;+ message.warning(t('createMaterial.imageGroupOnly'))+ return}- } else if (selectedGroup.type === PubType.VIDEO) {+ }+ else if (selectedGroup.type === PubType.VIDEO) {// 视频组:必须有封面组、视频组、封面和视频素材if (!editMaterialSelectedCoverGroup) {- message.warning(t('createMaterial.selectCoverGroupRequired'));- return;+ message.warning(t('createMaterial.selectCoverGroupRequired'))+ return}if (!editMaterialSelectedVideoGroup) {- message.warning(t('createMaterial.selectVideoGroupRequired'));- return;+ message.warning(t('createMaterial.selectVideoGroupRequired'))+ return}if (!editMaterialSelectedCover) {- message.warning(t('createMaterial.selectCoverRequired'));- return;+ message.warning(t('createMaterial.selectCoverRequired'))+ return}if (editMaterialSelectedMaterials.length === 0) {- message.warning(t('createMaterial.selectVideoRequired'));- return;+ message.warning(t('createMaterial.selectVideoRequired'))+ return}// 检查封面是否为图片- const coverItem = editMaterialCoverList.find((m: any) => m.url === editMaterialSelectedCover);+ const coverItem = editMaterialCoverList.find((m: any) => m.url === editMaterialSelectedCover)if (coverItem && coverItem.type !== 'img') {- message.warning(t('createMaterial.coverMustBeImage'));- return;+ message.warning(t('createMaterial.coverMustBeImage'))+ return}// 检查素材是否都是视频- const selectedMediaItems = editMaterialVideoList.filter((m: any) => editMaterialSelectedMaterials.includes(m.url));- const hasImage = selectedMediaItems.some((m: any) => m.type === 'img');+ const selectedMediaItems = editMaterialVideoList.filter((m: any) => editMaterialSelectedMaterials.includes(m.url))+ const hasImage = selectedMediaItems.some((m: any) => m.type === 'img')if (hasImage) {- message.warning(t('createMaterial.videoGroupOnly'));- return;+ message.warning(t('createMaterial.videoGroupOnly'))+ return}}-- setEditMaterialLoading(true);++ setEditMaterialLoading(true)try {// 根据类型使用不同的媒体列表- const finalMediaList = selectedGroup.type === PubType.VIDEO ? editMaterialVideoList : editMaterialMediaList;-+ const finalMediaList = selectedGroup.type === PubType.VIDEO ? editMaterialVideoList : editMaterialMediaList+await apiUpdateMaterial(editingMaterial._id, {coverUrl: editMaterialSelectedCover || undefined,mediaList: finalMediaList@@ -756,38 +791,40 @@ export default function CgMaterialPageCore() {desc: values.desc,location: editMaterialLocation,option: editingMaterial.option || {},- });-- message.success(t('editMaterial.updateSuccess'));- setEditMaterialModal(false);- setEditingMaterial(null);+ })++ message.success(t('editMaterial.updateSuccess'))+ setEditMaterialModal(false)+ setEditingMaterial(null)// 重置编辑素材相关状态- setEditMaterialSelectedGroup(null);- setEditMaterialMediaList([]);- setEditMaterialSelectedCover(null);- setEditMaterialSelectedMaterials([]);- setEditMaterialSelectedCoverGroup(null);- setEditMaterialSelectedVideoGroup(null);- setEditMaterialCoverList([]);- setEditMaterialVideoList([]);- setEditMaterialCoverGroupModal(false);- setEditMaterialVideoGroupModal(false);- editMaterialForm.resetFields();- fetchMaterialList(selectedGroup._id);- } catch (e) {- message.error(t('editMaterial.updateFailed'));- } finally {- setEditMaterialLoading(false);+ setEditMaterialSelectedGroup(null)+ setEditMaterialMediaList([])+ setEditMaterialSelectedCover(null)+ setEditMaterialSelectedMaterials([])+ setEditMaterialSelectedCoverGroup(null)+ setEditMaterialSelectedVideoGroup(null)+ setEditMaterialCoverList([])+ setEditMaterialVideoList([])+ setEditMaterialCoverGroupModal(false)+ setEditMaterialVideoGroupModal(false)+ editMaterialForm.resetFields()+ fetchMaterialList(selectedGroup._id)+ }+ catch (e) {+ message.error(t('editMaterial.updateFailed'))+ }+ finally {+ setEditMaterialLoading(false)}}// 打开导入弹窗async function openImportModal() {// 检查是否为VIP用户- const isVip =- userStore.userInfo?.vipInfo &&- userStore.userInfo.vipInfo.expireTime &&- new Date(userStore.userInfo.vipInfo.expireTime) > new Date();+ const isVip+ = userStore.userInfo?.vipInfo+ && userStore.userInfo.vipInfo.expireTime+ && new Date(userStore.userInfo.vipInfo.expireTime) > new Date()if (!isVip) {// 如果不是VIP,显示确认对话框@@ -798,184 +835,197 @@ export default function CgMaterialPageCore() {cancelText: t('import.cancel' as any),onOk: () => {// 打开VIP弹窗- setVipModalVisible(true);+ setVipModalVisible(true)},- });- return;+ })+ return}// 如果是VIP,正常打开导入弹窗- setImportModal(true);+ setImportModal(true)try {- const res = await getAccountListApi();- const allAccounts = res?.data || [];-+ const res = await getAccountListApi()+ const allAccounts = res?.data || []+// 只过滤掉离线账户const availableAccounts = allAccounts.filter((account: any) => {// 过滤掉离线账户if (account.status === 0) {- return false;+ return false}-- return true;- });-- setAccountList(availableAccounts);- } catch (e) {- message.error(t('import.getAccountsFailed' as any));++ return true+ })++ setAccountList(availableAccounts)+ }+ catch (e) {+ message.error(t('import.getAccountsFailed' as any))}}// 选择账户后获取发布列表async function handleSelectAccount(account: any) {- setSelectedAccount(account);- setPublishList([]);+ setSelectedAccount(account)+ setPublishList([])setPagination({current: 1,pageSize: 10,total: 0,- hasMore: false- });- await fetchPublishList(account, 1);+ hasMore: false,+ })+ await fetchPublishList(account, 1)}// 获取发布帖子列表(支持分页)async function fetchPublishList(account: any, page: number = 1) {- if (!account) return;-- setPublishListLoading(true);+ if (!account)+ return++ setPublishListLoading(true)try {const params: EngagementPostsParams = {platform: account.type as any,uid: account.uid || account.id,page,- pageSize: pagination.pageSize- };-- const res = await apiGetEngagementPosts(params);+ pageSize: pagination.pageSize,+ }++ const res = await apiGetEngagementPosts(params)if (res?.data) {- const { posts, total, hasMore } = res.data;-+ const { posts, total, hasMore } = res.data+if (page === 1) {// 第一页,替换数据- setPublishList(posts || []);- } else {+ setPublishList(posts || [])+ }+ else {// 后续页,追加数据- setPublishList(prev => [...prev, ...(posts || [])]);+ setPublishList(prev => [...prev, ...(posts || [])])}-+setPagination(prev => ({...prev,current: page,total: total ?? prev.total,- hasMore: hasMore ?? prev.hasMore- }));+ hasMore: hasMore ?? prev.hasMore,+ }))}- } catch (e) {- message.error(t('import.getPublishListFailed'));+ }+ catch (e) {+ message.error(t('import.getPublishListFailed'))if (page === 1) {- setPublishList([]);+ setPublishList([])}- } finally {- setPublishListLoading(false);+ }+ finally {+ setPublishListLoading(false)}}// 加载更多帖子async function loadMorePosts() {- if (!selectedAccount || !pagination.hasMore || publishListLoading) return;-- const nextPage = pagination.current + 1;- await fetchPublishList(selectedAccount, nextPage);+ if (!selectedAccount || !pagination.hasMore || publishListLoading)+ return++ const nextPage = pagination.current + 1+ await fetchPublishList(selectedAccount, nextPage)}// 导入选中的发布内容到草稿箱async function handleImportPublishItems() {if (!selectedAccount || selectedPublishItems.length === 0) {- message.warning(t('import.selectToImport' as any));- return;+ message.warning(t('import.selectToImport' as any))+ return}-+if (!selectedGroup) {- message.warning(t('import.selectGroupFirst' as any));- return;+ message.warning(t('import.selectGroupFirst' as any))+ return}- setImportLoading(true);+ setImportLoading(true)try {// 构造导入记录- const records = selectedPublishItems.map(itemId => {- const publishItem = publishList.find(item => item.postId === itemId);- if (!publishItem) return null;-+ const records = selectedPublishItems.map((itemId) => {+ const publishItem = publishList.find(item => item.postId === itemId)+ if (!publishItem)+ return null+return {accountId: selectedAccount.id,platform: selectedAccount.type,userId: selectedAccount.userId || selectedAccount.id, // 使用账户的用户IDuid: selectedAccount.uid || selectedAccount.id,- postId: publishItem.postId- };- }).filter((record): record is NonNullable<typeof record> => record !== null);+ postId: publishItem.postId,+ }+ }).filter((record): record is NonNullable<typeof record> => record !== null)- console.log('构造的导入记录:', records);- console.log('选中的账户:', selectedAccount);+ console.log('构造的导入记录:', records)+ console.log('选中的账户:', selectedAccount)if (records.length === 0) {- message.warning(t('import.noValidRecords' as any));- return;+ message.warning(t('import.noValidRecords' as any))+ return}// 调用导入接口- console.log('开始调用导入接口...');- const res = await apiImportPostsRecord(records);- console.log('导入接口返回结果:', res);-+ console.log('开始调用导入接口...')+ const res = await apiImportPostsRecord(records)+ console.log('导入接口返回结果:', res)+if (res?.code === 0) {- message.success(t('import.importSuccess' as any, { count: records.length }));--- setImportModal(false);- setSelectedPublishItems([]);- setSelectedAccount(null);- setPublishList([]);- fetchMaterialList(selectedGroup._id);- } else {- message.error(res?.message || t('import.importFailed' as any));+ message.success(t('import.importSuccess' as any, { count: records.length }))++ setImportModal(false)+ setSelectedPublishItems([])+ setSelectedAccount(null)+ setPublishList([])+ fetchMaterialList(selectedGroup._id)}- } catch (e: any) {- console.error('导入失败详情:', e);- message.error(t('import.importFailedWithReason' as any, { reason: e?.message || e || t('import.unknownError' as any) }));- } finally {- setImportLoading(false);+ else {+ message.error(res?.message || t('import.importFailed' as any))+ }+ }+ catch (e: any) {+ console.error('导入失败详情:', e)+ message.error(t('import.importFailedWithReason' as any, { reason: e?.message || e || t('import.unknownError' as any) }))+ }+ finally {+ setImportLoading(false)}}// 检查导入状态async function checkImportStatus() {try {- const res = await apiGetPostsRecordStatus();-+ const res = await apiGetPostsRecordStatus()+if (res?.code === 0 && res?.data && Array.isArray(res.data)) {- const statusData: any[] = res.data;- const successCount = statusData.filter((item: any) => item.status === 'success').length;- const failedCount = statusData.filter((item: any) => item.status === 'failed').length;- const runningCount = statusData.filter((item: any) => item.status === 'running').length;- const pendingCount = statusData.filter((item: any) => item.status === 'pending').length;-- let statusMessage = t('import.importStatus' as any);- if (successCount > 0) statusMessage += t('import.successCount' as any, { count: successCount }) + ' ';- if (failedCount > 0) statusMessage += t('import.failedCount' as any, { count: failedCount }) + ' ';- if (runningCount > 0) statusMessage += t('import.runningCount' as any, { count: runningCount }) + ' ';- if (pendingCount > 0) statusMessage += t('import.pendingCount' as any, { count: pendingCount }) + ' ';-+ const statusData: any[] = res.data+ const successCount = statusData.filter((item: any) => item.status === 'success').length+ const failedCount = statusData.filter((item: any) => item.status === 'failed').length+ const runningCount = statusData.filter((item: any) => item.status === 'running').length+ const pendingCount = statusData.filter((item: any) => item.status === 'pending').length++ let statusMessage = t('import.importStatus' as any)+ if (successCount > 0)+ statusMessage += `${t('import.successCount' as any, { count: successCount })} `+ if (failedCount > 0)+ statusMessage += `${t('import.failedCount' as any, { count: failedCount })} `+ if (runningCount > 0)+ statusMessage += `${t('import.runningCount' as any, { count: runningCount })} `+ if (pendingCount > 0)+ statusMessage += `${t('import.pendingCount' as any, { count: pendingCount })} `+// 显示详细记录信息if (statusData.length > 0) {const detailInfo = statusData.map((item: any) => {- const platformName = getPlatformName(item.platform);- const statusText = getImportStatusText(item.status);- return `${platformName} - ${item.title || t('import.noTitle' as any)} - ${statusText}`;- }).join('\n');-+ const platformName = getPlatformName(item.platform)+ const statusText = getImportStatusText(item.status)+ return `${platformName} - ${item.title || t('import.noTitle' as any)} - ${statusText}`+ }).join('\n')+Modal.info({title: t('import.importRecords' as any),content: (@@ -985,48 +1035,100 @@ export default function CgMaterialPageCore() {</div><div style={{ maxHeight: 400, overflow: 'auto' }}>{statusData.map((item: any, index: number) => (- <div key={index} style={{- marginBottom: 12,- padding: 12,- border: '1px solid #f0f0f0',- borderRadius: 6,- backgroundColor: item.status === 'success' ? '#f6ffed' :- item.status === 'failed' ? '#fff2f0' : '#f0f9ff'- }}>+ <div+ key={index}+ style={{+ marginBottom: 12,+ padding: 12,+ border: '1px solid #f0f0f0',+ borderRadius: 6,+ backgroundColor: item.status === 'success'+ ? '#f6ffed'+ : item.status === 'failed' ? '#fff2f0' : '#f0f9ff',+ }}+ ><div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}><span style={{ fontWeight: 600 }}>- {getPlatformName(item.platform)} - {item.title || t('import.noTitle' as any)}+ {getPlatformName(item.platform)}+ {' '}+ -+ {item.title || t('import.noTitle' as any)}</span>- <span style={{- padding: '2px 8px',- borderRadius: 4,+ <span style={{+ padding: '2px 8px',+ borderRadius: 4,fontSize: 12,- color: item.status === 'success' ? '#52c41a' :- item.status === 'failed' ? '#ff4d4f' : '#1890ff',- backgroundColor: item.status === 'success' ? '#f6ffed' :- item.status === 'failed' ? '#fff2f0' : '#f0f9ff'- }}>+ color: item.status === 'success'+ ? '#52c41a'+ : item.status === 'failed' ? '#ff4d4f' : '#1890ff',+ backgroundColor: item.status === 'success'+ ? '#f6ffed'+ : item.status === 'failed' ? '#fff2f0' : '#f0f9ff',+ }}+ >{getImportStatusText(item.status)}</span></div><div style={{ fontSize: 12, color: '#666', marginBottom: 4 }}>- <div>{t('import.publishTime' as any)}: {new Date(item.publishTime).toLocaleString()}</div>- <div>{t('import.mediaType' as any)}: {item.mediaType === 'image' ? t('import.image' as any) : item.mediaType === 'video' ? t('import.video' as any) : t('import.article' as any)}</div>- {item.desc && <div>{t('import.desc' as any)}: {item.desc}</div>}- <div>{t('import.interactionData' as any)}: {t('import.views' as any)} {item.viewCount} | {t('import.likes' as any)} {item.likeCount} | {t('import.comments' as any)} {item.commentCount} | {t('import.shares' as any)} {item.shareCount}</div>+ <div>+ {t('import.publishTime' as any)}+ :+ {' '}+ {new Date(item.publishTime).toLocaleString()}+ </div>+ <div>+ {t('import.mediaType' as any)}+ :+ {' '}+ {item.mediaType === 'image' ? t('import.image' as any) : item.mediaType === 'video' ? t('import.video' as any) : t('import.article' as any)}+ </div>+ {item.desc && (+ <div>+ {t('import.desc' as any)}+ :+ {' '}+ {item.desc}+ </div>+ )}+ <div>+ {t('import.interactionData' as any)}+ :+ {' '}+ {t('import.views' as any)}+ {' '}+ {item.viewCount}+ {' '}+ |+ {' '}+ {t('import.likes' as any)}+ {' '}+ {item.likeCount}+ {' '}+ |+ {' '}+ {t('import.comments' as any)}+ {' '}+ {item.commentCount}+ {' '}+ |+ {' '}+ {t('import.shares' as any)}+ {' '}+ {item.shareCount}+ </div></div>{item.cover && (<div style={{ marginTop: 8 }}>- <img- src={item.cover}- alt={t('import.cover' as any)}- style={{- width: 60,- height: 60,- objectFit: 'cover',+ <img+ src={item.cover}+ alt={t('import.cover' as any)}+ style={{+ width: 60,+ height: 60,+ objectFit: 'cover',borderRadius: 4,- border: '1px solid #f0f0f0'- }}+ border: '1px solid #f0f0f0',+ }}/></div>)}@@ -1036,108 +1138,112 @@ export default function CgMaterialPageCore() {</div>),width: 800,- okText: t('import.close' as any)- });- } else {- message.info(t('import.noRecords' as any));+ okText: t('import.close' as any),+ })+ }+ else {+ message.info(t('import.noRecords' as any))}}- } catch (e) {- console.error('查询导入状态失败:', e);- message.error(t('import.checkStatusFailed' as any));+ }+ catch (e) {+ console.error('查询导入状态失败:', e)+ message.error(t('import.checkStatusFailed' as any))}}// 组列表项事件:PC端长按,移动端左滑function handleGroupItemEvents(item: any) {- let timer: any = null;- let startX = 0;- let moved = false;+ let timer: any = null+ let startX = 0+ let moved = falsereturn {onPointerDown: (e: any) => {if (e.pointerType === 'touch') {- startX = e.clientX;- moved = false;+ startX = e.clientX+ moved = falseconst move = (ev: any) => {if (Math.abs(ev.clientX - startX) > 40) {- setShowActionsId(item._id);- moved = true;- window.removeEventListener('pointermove', move);+ setShowActionsId(item._id)+ moved = true+ window.removeEventListener('pointermove', move)}- };- window.addEventListener('pointermove', move);+ }+ window.addEventListener('pointermove', move)const up = () => {- window.removeEventListener('pointermove', move);- window.removeEventListener('pointerup', up);- if (!moved) setTimeout(() => setShowActionsId(null), 2000);- };- window.addEventListener('pointerup', up);- } else {+ window.removeEventListener('pointermove', move)+ window.removeEventListener('pointerup', up)+ if (!moved)+ setTimeout(() => setShowActionsId(null), 2000)+ }+ window.addEventListener('pointerup', up)+ }+ else {timer = setTimeout(() => {- setShowActionsId(item._id);- }, 700);+ setShowActionsId(item._id)+ }, 700)const up = () => {- clearTimeout(timer);- window.removeEventListener('pointerup', up);- setTimeout(() => setShowActionsId(null), 2000);- };- window.addEventListener('pointerup', up);+ clearTimeout(timer)+ window.removeEventListener('pointerup', up)+ setTimeout(() => setShowActionsId(null), 2000)+ }+ window.addEventListener('pointerup', up)}},onMouseLeave: () => {- setTimeout(() => setShowActionsId(null), 500);+ setTimeout(() => setShowActionsId(null), 500)},onMouseEnter: () => {- setShowActionsId(item._id);+ setShowActionsId(item._id)},- };+ }}// 获取平台显示名称function getPlatformName(type: string) {if (lng === 'en') {- return type;+ return type}-+// 中文显示名称const platformNames: Record<string, string> = {- 'tiktok': 'TikTok',- 'youtube': 'YouTube',- 'twitter': 'Twitter',- 'bilibili': '哔哩哔哩',- 'KWAI': '快手',- 'douyin': '抖音',- 'xhs': '小红书',- 'wxSph': '微信视频号',- 'wxGzh': '微信公众号',- 'facebook': 'Facebook',- 'instagram': 'Instagram',- 'threads': 'Threads',- };- return platformNames[type] || type;+ tiktok: 'TikTok',+ youtube: 'YouTube',+ twitter: 'Twitter',+ bilibili: '哔哩哔哩',+ KWAI: '快手',+ douyin: '抖音',+ xhs: '小红书',+ wxSph: '微信视频号',+ wxGzh: '微信公众号',+ facebook: 'Facebook',+ instagram: 'Instagram',+ threads: 'Threads',+ }+ return platformNames[type] || type}// 处理离线账户头像点击function handleOfflineAvatarClick(account: any) {// 根据平台类型跳转到对应的授权页面const authUrls: Record<string, string> = {- 'tiktok': '/accounts/plat/TikTokLogin',- 'youtube': '/accounts/plat/YouTubeLogin',- 'twitter': '/accounts/plat/TwitterLogin',- 'bilibili': '/accounts/plat/BilibiliLogin',- 'KWAI': '/accounts/plat/KwaiLogin',- 'douyin': '/accounts/plat/DouyinLogin',- 'xhs': '/accounts/plat/XhsLogin',- 'wxSph': '/accounts/plat/WxSphLogin',- 'wxGzh': '/accounts/plat/WxGzhLogin',- 'facebook': '/accounts/plat/FacebookLogin',- 'instagram': '/accounts/plat/InstagramLogin',- 'threads': '/accounts/plat/ThreadsLogin',- };-- const authUrl = authUrls[account.type];+ tiktok: '/accounts/plat/TikTokLogin',+ youtube: '/accounts/plat/YouTubeLogin',+ twitter: '/accounts/plat/TwitterLogin',+ bilibili: '/accounts/plat/BilibiliLogin',+ KWAI: '/accounts/plat/KwaiLogin',+ douyin: '/accounts/plat/DouyinLogin',+ xhs: '/accounts/plat/XhsLogin',+ wxSph: '/accounts/plat/WxSphLogin',+ wxGzh: '/accounts/plat/WxGzhLogin',+ facebook: '/accounts/plat/FacebookLogin',+ instagram: '/accounts/plat/InstagramLogin',+ threads: '/accounts/plat/ThreadsLogin',+ }++ const authUrl = authUrls[account.type]if (authUrl) {- window.open(authUrl, '_blank');+ window.open(authUrl, '_blank')}}@@ -1146,14 +1252,14 @@ export default function CgMaterialPageCore() {<div className={styles.header}><h2>{t('header.title')}</h2><div className={styles.headerActions}>- <Button+ <ButtonclassName={`${styles.actionButton} ${styles.importButton}`}onClick={openImportModal}icon={<ImportOutlined />}>{t('header.importContent')}</Button>- <Button+ <ButtonclassName={styles.actionButton}onClick={() => setCreateGroupModal(true)}icon={<PlusOutlined />}@@ -1162,77 +1268,84 @@ export default function CgMaterialPageCore() {</Button></div></div>-+<div className={styles.cgMain}>{/* 左侧边栏 */}<div className={styles.sidebar}><div className={styles.groupListContainer}><Spin spinning={groupLoading}>- {groupList.length === 0 ? (- <div className={styles.emptyState}>- <div className={styles.emptyIcon}>- <FolderOpenOutlined />- </div>- <h3>{t('sidebar.noGroups')}</h3>- <p>{t('sidebar.noGroupsDesc')}</p>- </div>- ) : (- <List- dataSource={groupList as any[]}- renderItem={(item: any) => (- <List.Item- className={styles.groupItem + (selectedGroup?._id===item._id ? ' ' + styles.selected : '') + (showActionsId===item._id ? ' ' + styles.showActions : '')}- onClick={()=>setSelectedGroup(item as any)}- {...handleGroupItemEvents(item)}- >- <div className={styles.groupName} style={{ marginTop: 10, paddingLeft: 10 }}>{item.name || item.title}</div>- <div className={styles.descTypeInfo} style={{ marginBottom: 10, paddingLeft: 10, paddingRight: 10 }}>- <span>{item.desc || t('sidebar.noDesc')}</span>- <span className={styles.typeTag}>- {getMaterialTypeLabel(item.type)}- </span>+ {groupList.length === 0+ ? (+ <div className={styles.emptyState}>+ <div className={styles.emptyIcon}>+ <FolderOpenOutlined /></div>- <div className={styles.groupActions}>- <span- className={styles.groupActionBtn}- onClick={e => {- e.stopPropagation();- setEditingGroup(item);- setEditGroupName(item.name || item.title || "");- setEditGroupModal(true);- }}- >- <EditOutlined /> {t('sidebar.edit')}- </span>- <span- className={styles.groupActionBtn}- onClick={e => {- e.stopPropagation();- Modal.confirm({- title: t('sidebar.deleteConfirm'),- content: t('sidebar.deleteConfirmDesc', { name: item.name || item.title }),- okText: t('sidebar.delete'),- okType: 'danger',- cancelText: t('batchGenerate.cancel'),- onOk: async () => {- try {- await apiDeleteMaterialGroup(item._id);- message.success(t('sidebar.deleteSuccess'));- fetchGroupList();- } catch {- message.error(t('sidebar.deleteFailed'));- }- },- });- }}+ <h3>{t('sidebar.noGroups')}</h3>+ <p>{t('sidebar.noGroupsDesc')}</p>+ </div>+ )+ : (+ <List+ dataSource={groupList as any[]}+ renderItem={(item: any) => (+ <List.Item+ className={styles.groupItem + (selectedGroup?._id === item._id ? ` ${styles.selected}` : '') + (showActionsId === item._id ? ` ${styles.showActions}` : '')}+ onClick={() => setSelectedGroup(item as any)}+ {...handleGroupItemEvents(item)}>- <DeleteOutlined /> {t('sidebar.delete')}- </span>- </div>- </List.Item>+ <div className={styles.groupName} style={{ marginTop: 10, paddingLeft: 10 }}>{item.name || item.title}</div>+ <div className={styles.descTypeInfo} style={{ marginBottom: 10, paddingLeft: 10, paddingRight: 10 }}>+ <span>{item.desc || t('sidebar.noDesc')}</span>+ <span className={styles.typeTag}>+ {getMaterialTypeLabel(item.type)}+ </span>+ </div>+ <div className={styles.groupActions}>+ <span+ className={styles.groupActionBtn}+ onClick={(e) => {+ e.stopPropagation()+ setEditingGroup(item)+ setEditGroupName(item.name || item.title || '')+ setEditGroupModal(true)+ }}+ >+ <EditOutlined />+ {' '}+ {t('sidebar.edit')}+ </span>+ <span+ className={styles.groupActionBtn}+ onClick={(e) => {+ e.stopPropagation()+ Modal.confirm({+ title: t('sidebar.deleteConfirm'),+ content: t('sidebar.deleteConfirmDesc', { name: item.name || item.title }),+ okText: t('sidebar.delete'),+ okType: 'danger',+ cancelText: t('batchGenerate.cancel'),+ onOk: async () => {+ try {+ await apiDeleteMaterialGroup(item._id)+ message.success(t('sidebar.deleteSuccess'))+ fetchGroupList()+ }+ catch {+ message.error(t('sidebar.deleteFailed'))+ }+ },+ })+ }}+ >+ <DeleteOutlined />+ {' '}+ {t('sidebar.delete')}+ </span>+ </div>+ </List.Item>+ )}+ />)}- />- )}</Spin></div></div>@@ -1244,17 +1357,17 @@ export default function CgMaterialPageCore() {{selectedGroup?.name || selectedGroup?.title || t('sidebar.selectGroup')}</div><div className={styles.contentActions}>- <Button+ <ButtonclassName={styles.actionButton}- onClick={openCreateMaterialModal}+ onClick={openCreateMaterialModal}disabled={!selectedGroup}icon={<PlusOutlined />}>{t('content.createMaterial')}</Button>- <Button+ <ButtonclassName={styles.actionButton}- onClick={openBatchModal}+ onClick={openBatchModal}disabled={!selectedGroup}icon={<FileTextOutlined />}>@@ -1283,16 +1396,16 @@ export default function CgMaterialPageCore() {</div>) : (<List- grid={{gutter: [16, 16], column: 3}}+ grid={{ gutter: [16, 16], column: 3 }}dataSource={materialList}renderItem={item => (<List.Item><div className={styles.materialCard}><divclassName={styles.cardMain}- onClick={() => { setDetailData(item); setDetailModal(true); }}+ onClick={() => { setDetailData(item); setDetailModal(true) }}>- { (item.coverUrl || item.mediaList.length > 0) && (+ { (item.coverUrl || item.mediaList.length > 0) && (selectedGroup?.type === PubType.VIDEO && item.mediaList?.some((m: any) => m.type === 'video') ? (// <video// src={getOssUrl(item.coverUrl)}@@ -1334,8 +1447,8 @@ export default function CgMaterialPageCore() {size="small"icon={<EditOutlined />}onClick={(e) => {- e.stopPropagation();- openEditMaterialModal(item);+ e.stopPropagation()+ openEditMaterialModal(item)}}className={styles.editButton}>@@ -1358,25 +1471,25 @@ export default function CgMaterialPageCore() {title={t('createGroup.title')}onOk={handleCreateGroup}onCancel={() => {- setCreateGroupModal(false);- createGroupForm.resetFields();+ setCreateGroupModal(false)+ createGroupForm.resetFields()}}confirmLoading={creating}width={500}><Form form={createGroupForm} layout="vertical">- <Form.Item- label={t('createGroup.name')}- name="name"+ <Form.Item+ label={t('createGroup.name')}+ name="name"rules={[{ required: true, message: t('createGroup.namePlaceholder') }]}initialValue="DraftboxGroup"><Input placeholder={t('createGroup.namePlaceholder')} /></Form.Item>-- <Form.Item- label={t('createGroup.type')}- name="type"++ <Form.Item+ label={t('createGroup.type')}+ name="type"rules={[{ required: true, message: t('createGroup.typePlaceholder') }]}initialValue={PubType.ImageText}>@@ -1391,10 +1504,10 @@ export default function CgMaterialPageCore() {</Select.Option></Select></Form.Item>-+<Form.Item label={t('createGroup.desc')} name="desc">- <TextArea- rows={3}+ <TextArea+ rows={3}placeholder={t('createGroup.descPlaceholder')}maxLength={200}showCount@@ -1409,89 +1522,90 @@ export default function CgMaterialPageCore() {title={t('import.title')}onOk={handleImportPublishItems}onCancel={() => {- setImportModal(false);- setSelectedAccount(null);- setPublishList([]);- setSelectedPublishItems([]);+ setImportModal(false)+ setSelectedAccount(null)+ setPublishList([])+ setSelectedPublishItems([])}}confirmLoading={importLoading}width={800}footer={[(- <Button- key="check-progress"- onClick={() => checkImportStatus()}+ <Button+ key="check-progress"+ onClick={() => checkImportStatus()}// disabled={selectedPublishItems.length === 0}>{t('import.checkProgress' as any)}</Button>),(- <Button- key="cancel"+ <Button+ key="cancel"onClick={() => {- setImportModal(false);- setSelectedAccount(null);- setPublishList([]);- setSelectedPublishItems([]);+ setImportModal(false)+ setSelectedAccount(null)+ setPublishList([])+ setSelectedPublishItems([])}}>{t('batchGenerate.cancel')}</Button>),(- <Button- key="submit"- type="primary"- onClick={handleImportPublishItems}+ <Button+ key="submit"+ type="primary"+ onClick={handleImportPublishItems}loading={importLoading}disabled={selectedPublishItems.length === 0}>{t('import.importSelected')}</Button>- )+ ),]}><div style={{ marginBottom: 16 }}><div style={{ fontWeight: 600, marginBottom: 8 }}>{t('import.selectAccount')}</div>- <div style={{- display: 'flex',- flexWrap: 'wrap',+ <div style={{+ display: 'flex',+ flexWrap: 'wrap',gap: 12,- maxHeight: 200,+ maxHeight: 200,overflow: 'auto',- padding: '8px'- }}>- {accountList.map(account => {- const isChoosed = selectedAccount?.id === account.id;-+ padding: '8px',+ }}+ >+ {accountList.map((account) => {+ const isChoosed = selectedAccount?.id === account.id+return (<divkey={account.id}className={[- publishDialogStyles["publishDialog-con-acconts-item"],+ publishDialogStyles['publishDialog-con-acconts-item'],isChoosed- ? publishDialogStyles["publishDialog-con-acconts-item--active"]- : "",- ].join(" ")}+ ? publishDialogStyles['publishDialog-con-acconts-item--active']+ : '',+ ].join(' ')}style={{borderColor: isChoosed? '#1677ff'- : "transparent",+ : 'transparent',}}onClick={(e) => {- e.stopPropagation();- handleSelectAccount(account);+ e.stopPropagation()+ handleSelectAccount(account)}}><AvatarPlat- className={`${publishDialogStyles["publishDialog-con-acconts-item-avatar"]} ${!isChoosed ? publishDialogStyles["disabled"] : ""}`}+ className={`${publishDialogStyles['publishDialog-con-acconts-item-avatar']} ${!isChoosed ? publishDialogStyles.disabled : ''}`}account={account}size="large"disabled={!isChoosed}/></div>- );+ )})}</div></div>@@ -1513,17 +1627,17 @@ export default function CgMaterialPageCore() {dataSource={publishList}renderItem={item => (<List.Item- style={{+ style={{cursor: 'pointer',background: selectedPublishItems.includes(item.postId) ? '#e6f4ff' : '#fff',- padding: '12px 16px'+ padding: '12px 16px',}}onClick={() => {setSelectedPublishItems(prev =>prev.includes(item.postId)? prev.filter(id => id !== item.postId)- : [...prev, item.postId]- );+ : [...prev, item.postId],+ )}}><div style={{ display: 'flex', gap: 12, width: '100%' }}>@@ -1537,14 +1651,33 @@ export default function CgMaterialPageCore() {<div style={{ flex: 1 }}><div style={{ fontWeight: 500, marginBottom: 4 }}>{item.title}</div><div style={{ fontSize: 12, color: '#666', marginBottom: 4 }}>- {item.content?.substring(0, 100)}{item.content?.length > 100 ? '...' : ''}+ {item.content?.substring(0, 100)}+ {item.content?.length > 100 ? '...' : ''}</div><div style={{ fontSize: 12, color: '#999', display: 'flex', gap: 8 }}><span>{new Date(item.publishTime).toLocaleDateString()}</span>- <span>• {item.mediaType === 'image' ? t('import.image' as any) : item.mediaType === 'video' ? t('import.video' as any) : t('import.article' as any)}</span>- <span>• {item.viewCount} {t('import.views' as any)}</span>- <span>• {item.likeCount} {t('import.likes' as any)}</span>- <span>• {item.commentCount} {t('import.comments' as any)}</span>+ <span>+ •+ {item.mediaType === 'image' ? t('import.image' as any) : item.mediaType === 'video' ? t('import.video' as any) : t('import.article' as any)}+ </span>+ <span>+ •+ {item.viewCount}+ {' '}+ {t('import.views' as any)}+ </span>+ <span>+ •+ {item.likeCount}+ {' '}+ {t('import.likes' as any)}+ </span>+ <span>+ •+ {item.commentCount}+ {' '}+ {t('import.comments' as any)}+ </span></div></div></div>@@ -1552,12 +1685,12 @@ export default function CgMaterialPageCore() {)}/></Spin>-+{/* 加载更多按钮 */}{pagination.hasMore && (<div style={{ textAlign: 'center', marginTop: 16 }}>- <Button- type="link"+ <Button+ type="link"loading={publishListLoading}onClick={loadMorePosts}>@@ -1575,20 +1708,20 @@ export default function CgMaterialPageCore() {title={t('createMaterial.title')}onOk={handleCreateMaterial}onCancel={() => {- setCreateModal(false);+ setCreateModal(false)// 重置创建素材相关状态- setSelectedMediaGroup(null);- setMediaList([]);- setSelectedCover(null);- setSelectedMaterials([]);- setSelectedCoverGroup(null);- setSelectedVideoGroup(null);- setCoverList([]);- setVideoList([]);- setMediaGroupModal(false);- setCoverGroupModal(false);- setVideoGroupModal(false);- form.resetFields();+ setSelectedMediaGroup(null)+ setMediaList([])+ setSelectedCover(null)+ setSelectedMaterials([])+ setSelectedCoverGroup(null)+ setSelectedVideoGroup(null)+ setCoverList([])+ setVideoList([])+ setMediaGroupModal(false)+ setCoverGroupModal(false)+ setVideoGroupModal(false)+ form.resetFields()}}confirmLoading={creating}width={700}@@ -1615,11 +1748,12 @@ export default function CgMaterialPageCore() {<divclassName={styles.mediaCard}style={{- background: selectedMediaGroup?._id === item._id ?- 'linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%)' :- '#FAEFFC',- border: selectedMediaGroup?._id === item._id ?- '2px solid #667eea' : '2px solid transparent',+ background: selectedMediaGroup?._id === item._id+ ? 'linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%)'+ : '#FAEFFC',+ border: selectedMediaGroup?._id === item._id+ ? '2px solid #667eea'+ : '2px solid transparent',padding: '20px',borderRadius: '12px',cursor: 'pointer',@@ -1629,35 +1763,37 @@ export default function CgMaterialPageCore() {flexDirection: 'column',justifyContent: 'center',alignItems: 'center',- textAlign: 'center'+ textAlign: 'center',}}onClick={() => handleSelectMediaGroup(item)}onMouseEnter={(e) => {if (selectedMediaGroup?._id !== item._id) {- e.currentTarget.style.transform = 'translateY(-2px)';- e.currentTarget.style.boxShadow = '0 4px 12px rgba(102, 126, 234, 0.2)';+ e.currentTarget.style.transform = 'translateY(-2px)'+ e.currentTarget.style.boxShadow = '0 4px 12px rgba(102, 126, 234, 0.2)'}}}onMouseLeave={(e) => {if (selectedMediaGroup?._id !== item._id) {- e.currentTarget.style.transform = 'translateY(0)';- e.currentTarget.style.boxShadow = 'none';+ e.currentTarget.style.transform = 'translateY(0)'+ e.currentTarget.style.boxShadow = 'none'}}}>- <div style={{- fontSize: 24,+ <div style={{+ fontSize: 24,marginBottom: 8,- color: selectedMediaGroup?._id === item._id ? '#667eea' : '#bdc3c7'- }}>+ color: selectedMediaGroup?._id === item._id ? '#667eea' : '#bdc3c7',+ }}+ ><FolderOpenOutlined /></div>- <div style={{- fontWeight: 600,+ <div style={{+ fontWeight: 600,fontSize: 16,color: '#2c3e50',- marginBottom: 4- }}>+ marginBottom: 4,+ }}+ >{item.title}</div>{/* 类型标签 */}@@ -1670,20 +1806,24 @@ export default function CgMaterialPageCore() {fontSize: '10px',fontWeight: '500',color: '#fff',- background: item.type === 'img' ? '#52c41a' :- item.type === 'video' ? '#1890ff' : '#722ed1',- zIndex: 1- }}>- {item.type === 'img' ? t('mediaGroupType.img') :- item.type === 'video' ? t('mediaGroupType.video') : t('mediaGroupType.mixed')}+ background: item.type === 'img'+ ? '#52c41a'+ : item.type === 'video' ? '#1890ff' : '#722ed1',+ zIndex: 1,+ }}+ >+ {item.type === 'img'+ ? t('mediaGroupType.img')+ : item.type === 'video' ? t('mediaGroupType.video') : t('mediaGroupType.mixed')}</div>{item.desc && (- <div style={{- fontSize: 12,+ <div style={{+ fontSize: 12,color: '#7f8c8d',lineHeight: 1.4,- marginTop: 4- }}>+ marginTop: 4,+ }}+ >{item.desc}</div>)}@@ -1691,9 +1831,12 @@ export default function CgMaterialPageCore() {<div style={{fontSize: 11,color: '#95a5a6',- marginTop: 4- }}>- {item.mediaList.total || 0} {t('mediaCount')}+ marginTop: 4,+ }}+ >+ {item.mediaList.total || 0}+ {' '}+ {t('mediaCount')}</div>{selectedMediaGroup?._id === item._id && (<div style={{@@ -1709,8 +1852,9 @@ export default function CgMaterialPageCore() {justifyContent: 'center',color: 'white',fontSize: 12,- zIndex: 2- }}>+ zIndex: 2,+ }}+ >✓</div>)}@@ -1743,11 +1887,12 @@ export default function CgMaterialPageCore() {<divclassName={styles.mediaCard}style={{- background: selectedCoverGroup?._id === item._id ?- 'linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%)' :- '#FAEFFC',- border: selectedCoverGroup?._id === item._id ?- '2px solid #667eea' : '2px solid transparent',+ background: selectedCoverGroup?._id === item._id+ ? 'linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%)'+ : '#FAEFFC',+ border: selectedCoverGroup?._id === item._id+ ? '2px solid #667eea'+ : '2px solid transparent',padding: '20px',borderRadius: '12px',cursor: 'pointer',@@ -1757,35 +1902,37 @@ export default function CgMaterialPageCore() {flexDirection: 'column',justifyContent: 'center',alignItems: 'center',- textAlign: 'center'+ textAlign: 'center',}}onClick={() => handleSelectCoverGroup(item)}onMouseEnter={(e) => {if (selectedCoverGroup?._id !== item._id) {- e.currentTarget.style.transform = 'translateY(-2px)';- e.currentTarget.style.boxShadow = '0 4px 12px rgba(102, 126, 234, 0.2)';+ e.currentTarget.style.transform = 'translateY(-2px)'+ e.currentTarget.style.boxShadow = '0 4px 12px rgba(102, 126, 234, 0.2)'}}}onMouseLeave={(e) => {if (selectedCoverGroup?._id !== item._id) {- e.currentTarget.style.transform = 'translateY(0)';- e.currentTarget.style.boxShadow = 'none';+ e.currentTarget.style.transform = 'translateY(0)'+ e.currentTarget.style.boxShadow = 'none'}}}>- <div style={{- fontSize: 24,+ <div style={{+ fontSize: 24,marginBottom: 8,- color: selectedCoverGroup?._id === item._id ? '#667eea' : '#bdc3c7'- }}>+ color: selectedCoverGroup?._id === item._id ? '#667eea' : '#bdc3c7',+ }}+ ><FolderOpenOutlined /></div>- <div style={{- fontWeight: 600,+ <div style={{+ fontWeight: 600,fontSize: 16,color: '#2c3e50',- marginBottom: 4- }}>+ marginBottom: 4,+ }}+ >{item.title}</div>{/* 类型标签 */}@@ -1799,17 +1946,19 @@ export default function CgMaterialPageCore() {fontWeight: '500',color: '#fff',background: '#52c41a',- zIndex: 1- }}>+ zIndex: 1,+ }}+ >{t('mediaGroupType.img')}</div>{item.desc && (- <div style={{- fontSize: 12,+ <div style={{+ fontSize: 12,color: '#7f8c8d',lineHeight: 1.4,- marginTop: 4- }}>+ marginTop: 4,+ }}+ >{item.desc}</div>)}@@ -1817,9 +1966,12 @@ export default function CgMaterialPageCore() {<div style={{fontSize: 11,color: '#95a5a6',- marginTop: 4- }}>- {item.mediaCount || 0} {t('mediaCount')}+ marginTop: 4,+ }}+ >+ {item.mediaCount || 0}+ {' '}+ {t('mediaCount')}</div>{selectedCoverGroup?._id === item._id && (<div style={{@@ -1835,8 +1987,9 @@ export default function CgMaterialPageCore() {justifyContent: 'center',color: 'white',fontSize: 12,- zIndex: 2- }}>+ zIndex: 2,+ }}+ >✓</div>)}@@ -1869,11 +2022,12 @@ export default function CgMaterialPageCore() {<divclassName={styles.mediaCard}style={{- background: selectedVideoGroup?._id === item._id ?- 'linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%)' :- '#FAEFFC',- border: selectedVideoGroup?._id === item._id ?- '2px solid #667eea' : '2px solid transparent',+ background: selectedVideoGroup?._id === item._id+ ? 'linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%)'+ : '#FAEFFC',+ border: selectedVideoGroup?._id === item._id+ ? '2px solid #667eea'+ : '2px solid transparent',padding: '20px',borderRadius: '12px',cursor: 'pointer',@@ -1883,35 +2037,37 @@ export default function CgMaterialPageCore() {flexDirection: 'column',justifyContent: 'center',alignItems: 'center',- textAlign: 'center'+ textAlign: 'center',}}onClick={() => handleSelectVideoGroup(item)}onMouseEnter={(e) => {if (selectedVideoGroup?._id !== item._id) {- e.currentTarget.style.transform = 'translateY(-2px)';- e.currentTarget.style.boxShadow = '0 4px 12px rgba(102, 126, 234, 0.2)';+ e.currentTarget.style.transform = 'translateY(-2px)'+ e.currentTarget.style.boxShadow = '0 4px 12px rgba(102, 126, 234, 0.2)'}}}onMouseLeave={(e) => {if (selectedVideoGroup?._id !== item._id) {- e.currentTarget.style.transform = 'translateY(0)';- e.currentTarget.style.boxShadow = 'none';+ e.currentTarget.style.transform = 'translateY(0)'+ e.currentTarget.style.boxShadow = 'none'}}}>- <div style={{- fontSize: 24,+ <div style={{+ fontSize: 24,marginBottom: 8,- color: selectedVideoGroup?._id === item._id ? '#667eea' : '#bdc3c7'- }}>+ color: selectedVideoGroup?._id === item._id ? '#667eea' : '#bdc3c7',+ }}+ ><VideoCameraOutlined /></div>- <div style={{- fontWeight: 600,+ <div style={{+ fontWeight: 600,fontSize: 16,color: '#2c3e50',- marginBottom: 4- }}>+ marginBottom: 4,+ }}+ >{item.title}</div>{/* 类型标签 */}@@ -1925,17 +2081,19 @@ export default function CgMaterialPageCore() {fontWeight: '500',color: '#fff',background: '#1890ff',- zIndex: 1- }}>+ zIndex: 1,+ }}+ >{t('mediaGroupType.video')}</div>{item.desc && (- <div style={{- fontSize: 12,+ <div style={{+ fontSize: 12,color: '#7f8c8d',lineHeight: 1.4,- marginTop: 4- }}>+ marginTop: 4,+ }}+ >{item.desc}</div>)}@@ -1943,9 +2101,12 @@ export default function CgMaterialPageCore() {<div style={{fontSize: 11,color: '#95a5a6',- marginTop: 4- }}>- {item.mediaCount || 0} {t('mediaCount')}+ marginTop: 4,+ }}+ >+ {item.mediaCount || 0}+ {' '}+ {t('mediaCount')}</div>{selectedVideoGroup?._id === item._id && (<div style={{@@ -1961,8 +2122,9 @@ export default function CgMaterialPageCore() {justifyContent: 'center',color: 'white',fontSize: 12,- zIndex: 2- }}>+ zIndex: 2,+ }}+ >✓</div>)}@@ -2019,12 +2181,13 @@ export default function CgMaterialPageCore() {opacity: selectedCover === media.url ? 0.5 : 1,}}onClick={() => {- if (selectedCover === media.url) return;+ if (selectedCover === media.url)+ returnsetSelectedMaterials(prev =>prev.includes(media.url)? prev.filter(url => url !== media.url)- : [...prev, media.url]- );+ : [...prev, media.url],+ )}}/>))}@@ -2039,8 +2202,8 @@ export default function CgMaterialPageCore() {{/* 封面组选择按钮 */}{!selectedCoverGroup && (<div style={{ marginBottom: 16 }}>- <Button- type="dashed"+ <Button+ type="dashed"onClick={() => setCoverGroupModal(true)}style={{ width: '100%', height: 60 }}>@@ -2053,8 +2216,8 @@ export default function CgMaterialPageCore() {{/* 视频组选择按钮 */}{!selectedVideoGroup && (<div style={{ marginBottom: 16 }}>- <Button- type="dashed"+ <Button+ type="dashed"onClick={() => setVideoGroupModal(true)}style={{ width: '100%', height: 60 }}>@@ -2071,13 +2234,13 @@ export default function CgMaterialPageCore() {<div style={{ fontWeight: 500 }}>{t('createMaterial.selectCover')}</div>- <Button- type="link"+ <Button+ type="link"size="small"onClick={() => {- setSelectedCoverGroup(null);- setCoverList([]);- setSelectedCover(null);+ setSelectedCoverGroup(null)+ setCoverList([])+ setSelectedCover(null)}}>{t('createMaterial.reselectCoverGroup')}@@ -2100,10 +2263,10 @@ export default function CgMaterialPageCore() {}}onClick={() => {if (media.type !== 'img') {- message.warning(t('createMaterial.coverMustBeImage'));- return;+ message.warning(t('createMaterial.coverMustBeImage'))+ return}- setSelectedCover(media.url);+ setSelectedCover(media.url)}}/>))}@@ -2118,13 +2281,13 @@ export default function CgMaterialPageCore() {<div style={{ fontWeight: 500 }}>{t('createMaterial.selectVideo')}</div>- <Button- type="link"+ <Button+ type="link"size="small"onClick={() => {- setSelectedVideoGroup(null);- setVideoList([]);- setSelectedMaterials([]);+ setSelectedVideoGroup(null)+ setVideoList([])+ setSelectedMaterials([])}}>{t('createMaterial.reselectVideoGroup')}@@ -2132,43 +2295,45 @@ export default function CgMaterialPageCore() {</div><div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>{videoList.map((media: any) => (- media.type === 'video' ? (- <video- key={media._id}- src={getOssUrl(media.url)}- style={{- width: 60,- height: 60,- border: selectedMaterials.includes(media.url) ? '2px solid #1677ff' : '1px solid #eee',- borderRadius: 4,- cursor: 'pointer',- objectFit: 'cover',- }}- onClick={() => setSelectedMaterials([media.url])}- muted- loop- onMouseEnter={(e) => (e.target as HTMLVideoElement).play()}- onMouseLeave={(e) => (e.target as HTMLVideoElement).pause()}- />- ) : (- <img- key={media._id}- src={getOssUrl(media.url)}- alt=""- style={{- width: 60,- height: 60,- border: selectedMaterials.includes(media.url) ? '2px solid #1677ff' : '1px solid #eee',- borderRadius: 4,- cursor: 'pointer',- objectFit: 'cover',- opacity: 0.3,- }}- onClick={() => {- message.warning(t('createMaterial.videoGroupOnly'));- }}- />- )+ media.type === 'video'+ ? (+ <video+ key={media._id}+ src={getOssUrl(media.url)}+ style={{+ width: 60,+ height: 60,+ border: selectedMaterials.includes(media.url) ? '2px solid #1677ff' : '1px solid #eee',+ borderRadius: 4,+ cursor: 'pointer',+ objectFit: 'cover',+ }}+ onClick={() => setSelectedMaterials([media.url])}+ muted+ loop+ onMouseEnter={e => (e.target as HTMLVideoElement).play()}+ onMouseLeave={e => (e.target as HTMLVideoElement).pause()}+ />+ )+ : (+ <img+ key={media._id}+ src={getOssUrl(media.url)}+ alt=""+ style={{+ width: 60,+ height: 60,+ border: selectedMaterials.includes(media.url) ? '2px solid #1677ff' : '1px solid #eee',+ borderRadius: 4,+ cursor: 'pointer',+ objectFit: 'cover',+ opacity: 0.3,+ }}+ onClick={() => {+ message.warning(t('createMaterial.videoGroupOnly'))+ }}+ />+ )))}</div></div>@@ -2178,7 +2343,7 @@ export default function CgMaterialPageCore() {{/* 表单区 */}<Form form={form} layout="vertical">- <Form.Item label={t('fields.title' as any)} name="title" rules={[{ required: true, message: t('validation.enterTitle' as any) }]}>+ <Form.Item label={t('fields.title' as any)} name="title" rules={[{ required: true, message: t('validation.enterTitle' as any) }]}><Input /></Form.Item><Form.Item label={t('fields.description' as any)} name="desc">@@ -2187,9 +2352,9 @@ export default function CgMaterialPageCore() {<Form.Item label={t('fields.location' as any)} name="location"><Inputvalue={singleLocation.join(',')}- onChange={e => {- const val = e.target.value.split(',').map((v: string) => Number(v.trim()));- setSingleLocation([val[0] || 0, val[1] || 0]);+ onChange={(e) => {+ const val = e.target.value.split(',').map((v: string) => Number(v.trim()))+ setSingleLocation([val[0] || 0, val[1] || 0])}}/></Form.Item>@@ -2200,49 +2365,49 @@ export default function CgMaterialPageCore() {open={batchModal}title={t('batchGenerate.title')}onOk={handleBatchMaterial}- onCancel={()=>setBatchModal(false)}+ onCancel={() => setBatchModal(false)}confirmLoading={batchTaskLoading}footer={[<Button key="preview" onClick={handlePreviewMaterial} loading={previewLoading} type="default">{t('batchGenerate.preview')}</Button>,<Button key="submit" type="primary" onClick={handleBatchMaterial} loading={batchTaskLoading}>{t('batchGenerate.startTask')}</Button>,- <Button key="cancel" onClick={()=>setBatchModal(false)}>{t('batchGenerate.cancel')}</Button>,+ <Button key="cancel" onClick={() => setBatchModal(false)}>{t('batchGenerate.cancel')}</Button>,]}><Form form={batchForm} layout="vertical">- <Form.Item label={t('batchGenerate.model')} name="model" rules={[{required:true,message:t('batchGenerate.modelPlaceholder')}]}>+ <Form.Item label={t('batchGenerate.model')} name="model" rules={[{ required: true, message: t('batchGenerate.modelPlaceholder') }]}><Select- style={{width:200}}+ style={{ width: 200 }}loading={chatModelsLoading}- options={chatModels.map((m:any)=>({ label: m?.description || m?.name, value: m?.name }))}+ options={chatModels.map((m: any) => ({ label: m?.description || m?.name, value: m?.name }))}placeholder={t('batchGenerate.modelPlaceholder')}/></Form.Item><Form.Item label={t('batchGenerate.prompt')} name="prompt">- <Input placeholder={t('batchGenerate.promptPlaceholder')}/>+ <Input placeholder={t('batchGenerate.promptPlaceholder')} /></Form.Item><Form.Item label={t('fields.title' as any)} name="title">- <Input placeholder={t('batchGenerate.titlePlaceholder')}/>+ <Input placeholder={t('batchGenerate.titlePlaceholder')} /></Form.Item><Form.Item label={t('fields.description' as any)} name="desc">- <TextArea rows={3} placeholder={t('batchGenerate.descPlaceholder')}/>+ <TextArea rows={3} placeholder={t('batchGenerate.descPlaceholder')} /></Form.Item>- <Form.Item label={t('batchGenerate.coverGroup')} name="coverGroup" rules={[{required:true,message:t('batchGenerate.coverGroupPlaceholder')}]}>+ <Form.Item label={t('batchGenerate.coverGroup')} name="coverGroup" rules={[{ required: true, message: t('batchGenerate.coverGroupPlaceholder') }]}><Select- options={mediaGroups.map((g:any)=>({label:g.title,value:g._id}))}- style={{width:200}}- onChange={v=>setBatchCoverGroup(v)}+ options={mediaGroups.map((g: any) => ({ label: g.title, value: g._id }))}+ style={{ width: 200 }}+ onChange={v => setBatchCoverGroup(v)}/></Form.Item>- <Form.Item label={t('batchGenerate.mediaGroups')} name="mediaGroups" rules={[{required:true,message:t('batchGenerate.mediaGroupsPlaceholder')}]}>+ <Form.Item label={t('batchGenerate.mediaGroups')} name="mediaGroups" rules={[{ required: true, message: t('batchGenerate.mediaGroupsPlaceholder') }]}><Selectmode="multiple"- options={mediaGroups.map((g:any)=>({label:g.title,value:g._id}))}- style={{width:300}}- onChange={v=>setBatchMediaGroups(v)}+ options={mediaGroups.map((g: any) => ({ label: g.title, value: g._id }))}+ style={{ width: 300 }}+ onChange={v => setBatchMediaGroups(v)}/></Form.Item>- <Form.Item label={t('batchGenerate.num')} name="num" initialValue={4} rules={[{required:true}]}>- <InputNumber min={1} max={20}/>+ <Form.Item label={t('batchGenerate.num')} name="num" initialValue={4} rules={[{ required: true }]}>+ <InputNumber min={1} max={20} /></Form.Item>{/* <Form.Item label="地理位置" name="location"><Input value={batchLocation.join(',')} disabled />@@ -2253,34 +2418,47 @@ export default function CgMaterialPageCore() {<Modalopen={previewModal}title={t('previewModal.title' as any)}- onCancel={()=>setPreviewModal(false)}+ onCancel={() => setPreviewModal(false)}footer={null}width={700}><Spin spinning={previewLoading}>- {!previewData ? (- <div style={{textAlign:'center',color:'#888'}}>{t('batchGenerate.noPreview')}</div>- ) : (- <Card title={previewData.title} bordered>- <div style={{marginBottom:8}}><b>{t('detail.descLabel' as any)}</b>{previewData.desc}</div>- <div style={{marginBottom:8}}><b>{t('detail.typeLabel' as any)}</b>{getMaterialTypeLabel(previewData.type)}</div>- <div style={{marginBottom:8}}><b>{t('detail.coverLabel' as any)}</b>- <div style={{marginTop:4}}>- {previewData.coverUrl && (- <img- src={getOssUrl(previewData.coverUrl)}- alt="cover"- style={{width:'100%',maxWidth:320,height:120,objectFit:'cover',borderRadius:8,display:'block'}}- />- )}- </div>- </div>- <div style={{marginBottom:8}}><b>{t('fields.location' as any)}</b>{Array.isArray(previewData.location) ? previewData.location.join(', ') : ''}</div>- <div><b>{t('detail.materialsLabel' as any)}</b>- {renderMediaContent(previewData.mediaList)}- </div>- </Card>- )}+ {!previewData+ ? (+ <div style={{ textAlign: 'center', color: '#888' }}>{t('batchGenerate.noPreview')}</div>+ )+ : (+ <Card title={previewData.title} bordered>+ <div style={{ marginBottom: 8 }}>+ <b>{t('detail.descLabel' as any)}</b>+ {previewData.desc}+ </div>+ <div style={{ marginBottom: 8 }}>+ <b>{t('detail.typeLabel' as any)}</b>+ {getMaterialTypeLabel(previewData.type)}+ </div>+ <div style={{ marginBottom: 8 }}>+ <b>{t('detail.coverLabel' as any)}</b>+ <div style={{ marginTop: 4 }}>+ {previewData.coverUrl && (+ <img+ src={getOssUrl(previewData.coverUrl)}+ alt="cover"+ style={{ width: '100%', maxWidth: 320, height: 120, objectFit: 'cover', borderRadius: 8, display: 'block' }}+ />+ )}+ </div>+ </div>+ <div style={{ marginBottom: 8 }}>+ <b>{t('fields.location' as any)}</b>+ {Array.isArray(previewData.location) ? previewData.location.join(', ') : ''}+ </div>+ <div>+ <b>{t('detail.materialsLabel' as any)}</b>+ {renderMediaContent(previewData.mediaList)}+ </div>+ </Card>+ )}</Spin></Modal>{/* 详情弹窗 */}@@ -2294,27 +2472,29 @@ export default function CgMaterialPageCore() {{detailData && (<div><div style={{ marginBottom: 16 }}>- <b>{t('detail.titleLabel' as any)}</b>{detailData.title}+ <b>{t('detail.titleLabel' as any)}</b>+ {detailData.title}</div><div style={{ marginBottom: 16 }}>- <b>{t('detail.descLabel' as any)}</b>{detailData.desc}+ <b>{t('detail.descLabel' as any)}</b>+ {detailData.desc}</div><div style={{ marginBottom: 16 }}><b>{t('detail.typeLabel' as any)}</b>{getMaterialTypeLabel(detailData.type)}</div>-+<div style={{ marginBottom: 16 }}><b>{t('detail.coverLabel' as any)}</b>- <div style={{marginTop:4}}>+ <div style={{ marginTop: 4 }}>{detailData.coverUrl && (-- <img- src={getOssUrl(detailData.coverUrl)}- alt="cover"- style={{maxWidth:320, objectFit:'cover',borderRadius:8,display:'block'}}- />-++ <img+ src={getOssUrl(detailData.coverUrl)}+ alt="cover"+ style={{ maxWidth: 320, objectFit: 'cover', borderRadius: 8, display: 'block' }}+ />+)}</div></div>@@ -2324,7 +2504,7 @@ export default function CgMaterialPageCore() {</div><div style={{ marginBottom: 16 }}><b>{t('detail.statusLabel' as any)}</b>- <span style={{ color: detailData.status === 0 ? "#faad14" : "#52c41a" }}>+ <span style={{ color: detailData.status === 0 ? '#faad14' : '#52c41a' }}>{getMaterialStatusLabel(detailData.status)}</span></div>@@ -2336,13 +2516,13 @@ export default function CgMaterialPageCore() {open={editGroupModal}title={t('editGroup.title')}onOk={handleEditGroup}- onCancel={()=>setEditGroupModal(false)}+ onCancel={() => setEditGroupModal(false)}confirmLoading={editLoading}><Inputplaceholder={t('editGroup.namePlaceholder')}value={editGroupName}- onChange={e=>setEditGroupName(e.target.value)}+ onChange={e => setEditGroupName(e.target.value)}/></Modal>@@ -2352,20 +2532,20 @@ export default function CgMaterialPageCore() {title={t('editMaterial.title')}onOk={handleUpdateMaterial}onCancel={() => {- setEditMaterialModal(false);- setEditingMaterial(null);- editMaterialForm.resetFields();+ setEditMaterialModal(false)+ setEditingMaterial(null)+ editMaterialForm.resetFields()// 重置编辑素材相关状态- setEditMaterialSelectedGroup(null);- setEditMaterialMediaList([]);- setEditMaterialSelectedCover(null);- setEditMaterialSelectedMaterials([]);- setEditMaterialSelectedCoverGroup(null);- setEditMaterialSelectedVideoGroup(null);- setEditMaterialCoverList([]);- setEditMaterialVideoList([]);- setEditMaterialCoverGroupModal(false);- setEditMaterialVideoGroupModal(false);+ setEditMaterialSelectedGroup(null)+ setEditMaterialMediaList([])+ setEditMaterialSelectedCover(null)+ setEditMaterialSelectedMaterials([])+ setEditMaterialSelectedCoverGroup(null)+ setEditMaterialSelectedVideoGroup(null)+ setEditMaterialCoverList([])+ setEditMaterialVideoList([])+ setEditMaterialCoverGroupModal(false)+ setEditMaterialVideoGroupModal(false)}}confirmLoading={editMaterialLoading}width={700}@@ -2392,11 +2572,12 @@ export default function CgMaterialPageCore() {<divclassName={styles.mediaCard}style={{- background: editMaterialSelectedCoverGroup?._id === item._id ?- 'linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%)' :- '#FAEFFC',- border: editMaterialSelectedCoverGroup?._id === item._id ?- '2px solid #667eea' : '2px solid transparent',+ background: editMaterialSelectedCoverGroup?._id === item._id+ ? 'linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%)'+ : '#FAEFFC',+ border: editMaterialSelectedCoverGroup?._id === item._id+ ? '2px solid #667eea'+ : '2px solid transparent',padding: '20px',borderRadius: '12px',cursor: 'pointer',@@ -2406,35 +2587,37 @@ export default function CgMaterialPageCore() {flexDirection: 'column',justifyContent: 'center',alignItems: 'center',- textAlign: 'center'+ textAlign: 'center',}}onClick={() => handleEditMaterialSelectCoverGroup(item)}onMouseEnter={(e) => {if (editMaterialSelectedCoverGroup?._id !== item._id) {- e.currentTarget.style.transform = 'translateY(-2px)';- e.currentTarget.style.boxShadow = '0 4px 12px rgba(102, 126, 234, 0.2)';+ e.currentTarget.style.transform = 'translateY(-2px)'+ e.currentTarget.style.boxShadow = '0 4px 12px rgba(102, 126, 234, 0.2)'}}}onMouseLeave={(e) => {if (editMaterialSelectedCoverGroup?._id !== item._id) {- e.currentTarget.style.transform = 'translateY(0)';- e.currentTarget.style.boxShadow = 'none';+ e.currentTarget.style.transform = 'translateY(0)'+ e.currentTarget.style.boxShadow = 'none'}}}>- <div style={{- fontSize: 24,+ <div style={{+ fontSize: 24,marginBottom: 8,- color: editMaterialSelectedCoverGroup?._id === item._id ? '#667eea' : '#bdc3c7'- }}>+ color: editMaterialSelectedCoverGroup?._id === item._id ? '#667eea' : '#bdc3c7',+ }}+ ><FolderOpenOutlined /></div>- <div style={{- fontWeight: 600,+ <div style={{+ fontWeight: 600,fontSize: 16,color: '#2c3e50',- marginBottom: 4- }}>+ marginBottom: 4,+ }}+ >{item.title}</div>{/* 类型标签 */}@@ -2448,17 +2631,19 @@ export default function CgMaterialPageCore() {fontWeight: '500',color: '#fff',background: '#52c41a',- zIndex: 1- }}>+ zIndex: 1,+ }}+ >{t('mediaGroupType.img')}</div>{item.desc && (- <div style={{- fontSize: 12,+ <div style={{+ fontSize: 12,color: '#7f8c8d',lineHeight: 1.4,- marginTop: 4- }}>+ marginTop: 4,+ }}+ >{item.desc}</div>)}@@ -2466,9 +2651,12 @@ export default function CgMaterialPageCore() {<div style={{fontSize: 11,color: '#95a5a6',- marginTop: 4- }}>- {item.mediaCount || 0} {t('mediaCount')}+ marginTop: 4,+ }}+ >+ {item.mediaCount || 0}+ {' '}+ {t('mediaCount')}</div>{editMaterialSelectedCoverGroup?._id === item._id && (<div style={{@@ -2484,8 +2672,9 @@ export default function CgMaterialPageCore() {justifyContent: 'center',color: 'white',fontSize: 12,- zIndex: 2- }}>+ zIndex: 2,+ }}+ >✓</div>)}@@ -2518,11 +2707,12 @@ export default function CgMaterialPageCore() {<divclassName={styles.mediaCard}style={{- background: editMaterialSelectedVideoGroup?._id === item._id ?- 'linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%)' :- '#FAEFFC',- border: editMaterialSelectedVideoGroup?._id === item._id ?- '2px solid #667eea' : '2px solid transparent',+ background: editMaterialSelectedVideoGroup?._id === item._id+ ? 'linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%)'+ : '#FAEFFC',+ border: editMaterialSelectedVideoGroup?._id === item._id+ ? '2px solid #667eea'+ : '2px solid transparent',padding: '20px',borderRadius: '12px',cursor: 'pointer',@@ -2532,35 +2722,37 @@ export default function CgMaterialPageCore() {flexDirection: 'column',justifyContent: 'center',alignItems: 'center',- textAlign: 'center'+ textAlign: 'center',}}onClick={() => handleEditMaterialSelectVideoGroup(item)}onMouseEnter={(e) => {if (editMaterialSelectedVideoGroup?._id !== item._id) {- e.currentTarget.style.transform = 'translateY(-2px)';- e.currentTarget.style.boxShadow = '0 4px 12px rgba(102, 126, 234, 0.2)';+ e.currentTarget.style.transform = 'translateY(-2px)'+ e.currentTarget.style.boxShadow = '0 4px 12px rgba(102, 126, 234, 0.2)'}}}onMouseLeave={(e) => {if (editMaterialSelectedVideoGroup?._id !== item._id) {- e.currentTarget.style.transform = 'translateY(0)';- e.currentTarget.style.boxShadow = 'none';+ e.currentTarget.style.transform = 'translateY(0)'+ e.currentTarget.style.boxShadow = 'none'}}}>- <div style={{- fontSize: 24,+ <div style={{+ fontSize: 24,marginBottom: 8,- color: editMaterialSelectedVideoGroup?._id === item._id ? '#667eea' : '#bdc3c7'- }}>+ color: editMaterialSelectedVideoGroup?._id === item._id ? '#667eea' : '#bdc3c7',+ }}+ ><VideoCameraOutlined /></div>- <div style={{- fontWeight: 600,+ <div style={{+ fontWeight: 600,fontSize: 16,color: '#2c3e50',- marginBottom: 4- }}>+ marginBottom: 4,+ }}+ >{item.title}</div>{/* 类型标签 */}@@ -2574,17 +2766,19 @@ export default function CgMaterialPageCore() {fontWeight: '500',color: '#fff',background: '#1890ff',- zIndex: 1- }}>+ zIndex: 1,+ }}+ >{t('mediaGroupType.video')}</div>{item.desc && (- <div style={{- fontSize: 12,+ <div style={{+ fontSize: 12,color: '#7f8c8d',lineHeight: 1.4,- marginTop: 4- }}>+ marginTop: 4,+ }}+ >{item.desc}</div>)}@@ -2592,9 +2786,12 @@ export default function CgMaterialPageCore() {<div style={{fontSize: 11,color: '#95a5a6',- marginTop: 4- }}>- {item.mediaCount || 0} {t('mediaCount')}+ marginTop: 4,+ }}+ >+ {item.mediaCount || 0}+ {' '}+ {t('mediaCount')}</div>{editMaterialSelectedVideoGroup?._id === item._id && (<div style={{@@ -2610,8 +2807,9 @@ export default function CgMaterialPageCore() {justifyContent: 'center',color: 'white',fontSize: 12,- zIndex: 2- }}>+ zIndex: 2,+ }}+ >✓</div>)}@@ -2633,11 +2831,12 @@ export default function CgMaterialPageCore() {<divclassName={styles.mediaCard}style={{- background: editMaterialSelectedGroup?._id === item._id ?- 'linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%)' :- '#FAEFFC',- border: editMaterialSelectedGroup?._id === item._id ?- '2px solid #667eea' : '2px solid transparent',+ background: editMaterialSelectedGroup?._id === item._id+ ? 'linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%)'+ : '#FAEFFC',+ border: editMaterialSelectedGroup?._id === item._id+ ? '2px solid #667eea'+ : '2px solid transparent',padding: '20px',borderRadius: '12px',cursor: 'pointer',@@ -2647,43 +2846,46 @@ export default function CgMaterialPageCore() {flexDirection: 'column',justifyContent: 'center',alignItems: 'center',- textAlign: 'center'+ textAlign: 'center',}}onClick={() => handleEditMaterialSelectGroup(item)}onMouseEnter={(e) => {if (editMaterialSelectedGroup?._id !== item._id) {- e.currentTarget.style.transform = 'translateY(-2px)';- e.currentTarget.style.boxShadow = '0 4px 12px rgba(102, 126, 234, 0.2)';+ e.currentTarget.style.transform = 'translateY(-2px)'+ e.currentTarget.style.boxShadow = '0 4px 12px rgba(102, 126, 234, 0.2)'}}}onMouseLeave={(e) => {if (editMaterialSelectedGroup?._id !== item._id) {- e.currentTarget.style.transform = 'translateY(0)';- e.currentTarget.style.boxShadow = 'none';+ e.currentTarget.style.transform = 'translateY(0)'+ e.currentTarget.style.boxShadow = 'none'}}}>- <div style={{- fontSize: 24,+ <div style={{+ fontSize: 24,marginBottom: 8,- color: editMaterialSelectedGroup?._id === item._id ? '#667eea' : '#bdc3c7'- }}>+ color: editMaterialSelectedGroup?._id === item._id ? '#667eea' : '#bdc3c7',+ }}+ ><FolderOpenOutlined /></div>- <div style={{- fontWeight: 600,+ <div style={{+ fontWeight: 600,fontSize: 16,color: '#2c3e50',- marginBottom: 4- }}>+ marginBottom: 4,+ }}+ >{item.title}</div>{item.desc && (- <div style={{- fontSize: 12,+ <div style={{+ fontSize: 12,color: '#7f8c8d',- lineHeight: 1.4- }}>+ lineHeight: 1.4,+ }}+ >{item.desc}</div>)}@@ -2700,8 +2902,9 @@ export default function CgMaterialPageCore() {alignItems: 'center',justifyContent: 'center',color: 'white',- fontSize: 12- }}>+ fontSize: 12,+ }}+ >✓</div>)}@@ -2758,12 +2961,13 @@ export default function CgMaterialPageCore() {opacity: editMaterialSelectedCover === media.url ? 0.5 : 1,}}onClick={() => {- if (editMaterialSelectedCover === media.url) return;+ if (editMaterialSelectedCover === media.url)+ returnsetEditMaterialSelectedMaterials(prev =>prev.includes(media.url)? prev.filter(url => url !== media.url)- : [...prev, media.url]- );+ : [...prev, media.url],+ )}}/>))}@@ -2778,8 +2982,8 @@ export default function CgMaterialPageCore() {{/* 封面组选择按钮 */}{!editMaterialSelectedCoverGroup && (<div style={{ marginBottom: 16 }}>- <Button- type="dashed"+ <Button+ type="dashed"onClick={() => setEditMaterialCoverGroupModal(true)}style={{ width: '100%', height: 60 }}>@@ -2792,8 +2996,8 @@ export default function CgMaterialPageCore() {{/* 视频组选择按钮 */}{!editMaterialSelectedVideoGroup && (<div style={{ marginBottom: 16 }}>- <Button- type="dashed"+ <Button+ type="dashed"onClick={() => setEditMaterialVideoGroupModal(true)}style={{ width: '100%', height: 60 }}>@@ -2810,13 +3014,13 @@ export default function CgMaterialPageCore() {<div style={{ fontWeight: 500 }}>{t('createMaterial.selectCover')}</div>- <Button- type="link"+ <Button+ type="link"size="small"onClick={() => {- setEditMaterialSelectedCoverGroup(null);- setEditMaterialCoverList([]);- setEditMaterialSelectedCover(null);+ setEditMaterialSelectedCoverGroup(null)+ setEditMaterialCoverList([])+ setEditMaterialSelectedCover(null)}}>{t('createMaterial.reselectCoverGroup')}@@ -2839,10 +3043,10 @@ export default function CgMaterialPageCore() {}}onClick={() => {if (media.type !== 'img') {- message.warning(t('createMaterial.coverMustBeImage'));- return;+ message.warning(t('createMaterial.coverMustBeImage'))+ return}- setEditMaterialSelectedCover(media.url);+ setEditMaterialSelectedCover(media.url)}}/>))}@@ -2857,13 +3061,13 @@ export default function CgMaterialPageCore() {<div style={{ fontWeight: 500 }}>{t('createMaterial.selectVideo')}</div>- <Button- type="link"+ <Button+ type="link"size="small"onClick={() => {- setEditMaterialSelectedVideoGroup(null);- setEditMaterialVideoList([]);- setEditMaterialSelectedMaterials([]);+ setEditMaterialSelectedVideoGroup(null)+ setEditMaterialVideoList([])+ setEditMaterialSelectedMaterials([])}}>{t('createMaterial.reselectVideoGroup')}@@ -2871,43 +3075,45 @@ export default function CgMaterialPageCore() {</div><div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>{editMaterialVideoList.map((media: any) => (- media.type === 'video' ? (- <video- key={media._id}- src={getOssUrl(media.url)}- style={{- width: 60,- height: 60,- border: editMaterialSelectedMaterials.includes(media.url) ? '2px solid #1677ff' : '1px solid #eee',- borderRadius: 4,- cursor: 'pointer',- objectFit: 'cover',- }}- onClick={() => setEditMaterialSelectedMaterials([media.url])}- muted- loop- onMouseEnter={(e) => (e.target as HTMLVideoElement).play()}- onMouseLeave={(e) => (e.target as HTMLVideoElement).pause()}- />- ) : (- <img- key={media._id}- src={getOssUrl(media.url)}- alt=""- style={{- width: 60,- height: 60,- border: editMaterialSelectedMaterials.includes(media.url) ? '2px solid #1677ff' : '1px solid #eee',- borderRadius: 4,- cursor: 'pointer',- objectFit: 'cover',- opacity: 0.3,- }}- onClick={() => {- message.warning(t('createMaterial.videoGroupOnly'));- }}- />- )+ media.type === 'video'+ ? (+ <video+ key={media._id}+ src={getOssUrl(media.url)}+ style={{+ width: 60,+ height: 60,+ border: editMaterialSelectedMaterials.includes(media.url) ? '2px solid #1677ff' : '1px solid #eee',+ borderRadius: 4,+ cursor: 'pointer',+ objectFit: 'cover',+ }}+ onClick={() => setEditMaterialSelectedMaterials([media.url])}+ muted+ loop+ onMouseEnter={e => (e.target as HTMLVideoElement).play()}+ onMouseLeave={e => (e.target as HTMLVideoElement).pause()}+ />+ )+ : (+ <img+ key={media._id}+ src={getOssUrl(media.url)}+ alt=""+ style={{+ width: 60,+ height: 60,+ border: editMaterialSelectedMaterials.includes(media.url) ? '2px solid #1677ff' : '1px solid #eee',+ borderRadius: 4,+ cursor: 'pointer',+ objectFit: 'cover',+ opacity: 0.3,+ }}+ onClick={() => {+ message.warning(t('createMaterial.videoGroupOnly'))+ }}+ />+ )))}</div></div>@@ -2917,7 +3123,7 @@ export default function CgMaterialPageCore() {{/* 表单区 */}<Form form={editMaterialForm} layout="vertical">- <Form.Item label={t('fields.title' as any)} name="title" rules={[{ required: true, message: t('validation.enterTitle' as any) }]}>+ <Form.Item label={t('fields.title' as any)} name="title" rules={[{ required: true, message: t('validation.enterTitle' as any) }]}><Input /></Form.Item><Form.Item label={t('fields.description' as any)} name="desc">@@ -2926,9 +3132,9 @@ export default function CgMaterialPageCore() {<Form.Item label={t('fields.location' as any)} name="location"><Inputvalue={editMaterialLocation.join(',')}- onChange={e => {- const val = e.target.value.split(',').map((v: string) => Number(v.trim()));- setEditMaterialLocation([val[0] || 0, val[1] || 0]);+ onChange={(e) => {+ const val = e.target.value.split(',').map((v: string) => Number(v.trim()))+ setEditMaterialLocation([val[0] || 0, val[1] || 0])}}/></Form.Item>@@ -2941,5 +3147,5 @@ export default function CgMaterialPageCore() {onClose={() => setVipModalVisible(false)}/></div>- );-}\ No newline at end of file+ )+}diff --git a/project/web/src/app/[lng]/cgmaterial/page.tsx b/project/web/src/app/[lng]/cgmaterial/page.tsxindex 056c3108..9b4e24d6 100644--- a/project/web/src/app/[lng]/cgmaterial/page.tsx+++ b/project/web/src/app/[lng]/cgmaterial/page.tsx@@ -1,23 +1,23 @@-import { useTranslation } from "@/app/i18n";-import { PageParams } from "@/app/globals";-import * as React from "react";-import { getMetadata } from "@/utils/general";-import dynamic from "next/dynamic";+import type { PageParams } from '@/app/globals'+import dynamic from 'next/dynamic'+import * as React from 'react'+import { useTranslation } from '@/app/i18n'+import { getMetadata } from '@/utils/general'const CgMaterialPageCore = dynamic(// @ts-ignore- () => import("./cgmaterialPageCore").then(mod => mod.default || mod.CgMaterialPageCore),- { ssr: false }-);+ () => import('./cgmaterialPageCore').then(mod => mod.default || mod.CgMaterialPageCore),+ { ssr: false },+)export async function generateMetadata({ params }: PageParams) {- const { lng } = await params;+ const { lng } = await paramsreturn await getMetadata({- title: "草稿箱",+ title: '草稿箱',},lng,- );+ )}export default function Page({ params }: PageParams) {@@ -25,5 +25,5 @@ export default function Page({ params }: PageParams) {<><CgMaterialPageCore /></>- );-}\ No newline at end of file+ )+}diff --git a/project/web/src/app/[lng]/cgmaterial/styles/cgmaterial.module.scss b/project/web/src/app/[lng]/cgmaterial/styles/cgmaterial.module.scssindex de1ff380..c8e499a3 100644--- a/project/web/src/app/[lng]/cgmaterial/styles/cgmaterial.module.scss+++ b/project/web/src/app/[lng]/cgmaterial/styles/cgmaterial.module.scss@@ -171,7 +171,7 @@width: 100%;z-index: 2;position: relative;-+span:first-child {font-size: 13px;color: #7f8c8d;@@ -294,10 +294,10 @@font-size: 64px;color: #bdc3c7;margin-bottom: 16px;-+:global(.anticon) {transition: all 0.3s ease;-+&:hover {color: #667eea;transform: scale(1.1);@@ -518,7 +518,7 @@.ant-modal-header {background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);border: none;-+.ant-modal-title {color: white;font-weight: 600;@@ -527,7 +527,7 @@.ant-modal-close {color: white;-+&:hover {color: rgba(255, 255, 255, 0.8);}@@ -576,4 +576,4 @@min-height: 200px;}}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/dataStatistics/DataStatisticsCore.tsx b/project/web/src/app/[lng]/dataStatistics/DataStatisticsCore.tsxindex 6ca0f51f..44633b6d 100644--- a/project/web/src/app/[lng]/dataStatistics/DataStatisticsCore.tsx+++ b/project/web/src/app/[lng]/dataStatistics/DataStatisticsCore.tsx@@ -1,16 +1,16 @@-"use client";+'use client'-import styles from "./dataStatistics.module.scss";-import DataStatisticsHeader from "@/app/[lng]/dataStatistics/components/DataStatisticsHeader";-import { useDataStatisticsStore } from "@/app/[lng]/dataStatistics/useDataStatistics";-import { useShallow } from "zustand/react/shallow";-import { useEffect } from "react";-import { useAccountStore } from "@/store/account";-import DataStatisticsDetails from "@/app/[lng]/dataStatistics/components/DataStatisticsDetails";-import { Spin } from "antd";-import DataStatisticsTable from "@/app/[lng]/dataStatistics/components/DataStatisticsTable";+import { Spin } from 'antd'+import { useEffect } from 'react'+import { useShallow } from 'zustand/react/shallow'+import DataStatisticsDetails from '@/app/[lng]/dataStatistics/components/DataStatisticsDetails'+import DataStatisticsHeader from '@/app/[lng]/dataStatistics/components/DataStatisticsHeader'+import DataStatisticsTable from '@/app/[lng]/dataStatistics/components/DataStatisticsTable'+import { useDataStatisticsStore } from '@/app/[lng]/dataStatistics/useDataStatistics'+import { useAccountStore } from '@/store/account'+import styles from './dataStatistics.module.scss'-export const DataStatisticsCore = () => {+export function DataStatisticsCore() {const {setChoosedGroupIds,setFilteredAccountList,@@ -24,7 +24,7 @@ export const DataStatisticsCore = () => {loading,accountSearchValue,} = useDataStatisticsStore(- useShallow((state) => ({+ useShallow(state => ({setChoosedGroupIds: state.setChoosedGroupIds,setFilteredAccountList: state.setFilteredAccountList,choosedGroupIds: state.choosedGroupIds,@@ -37,46 +37,46 @@ export const DataStatisticsCore = () => {loading: state.loading,accountSearchValue: state.accountSearchValue,})),- );+ )const { accountGroupList, accountList } = useAccountStore(- useShallow((state) => ({+ useShallow(state => ({accountGroupList: state.accountGroupList,accountList: state.accountList,})),- );+ )useEffect(() => {- init();- }, []);+ init()+ }, [])// 数据明细切换,重新分拣数据useEffect(() => {- sortingData();- }, [currentDetailType, sortingData]);+ sortingData()+ }, [currentDetailType, sortingData])// 获取数据统计useEffect(() => {- getStatistics();- }, [timeRangeValue, getStatistics, filteredAccountList]);+ getStatistics()+ }, [timeRangeValue, getStatistics, filteredAccountList])// 初始化选择所有账户组useEffect(() => {if (accountGroupList.length > 0) {- setChoosedGroupIds(accountGroupList.map((group) => group.id));+ setChoosedGroupIds(accountGroupList.map(group => group.id))}- }, [setChoosedGroupIds, accountGroupList]);+ }, [setChoosedGroupIds, accountGroupList])// 过滤账户useEffect(() => {setFilteredAccountList(accountList.filter((v) => {return (- choosedGroupIds.includes(v.groupId) &&- v.nickname.includes(accountSearchValue)- );+ choosedGroupIds.includes(v.groupId)+ && v.nickname.includes(accountSearchValue)+ )}),- );- }, [choosedGroupIds, accountList, accountSearchValue]);+ )+ }, [choosedGroupIds, accountList, accountSearchValue])return (<Spin spinning={loading}>@@ -86,5 +86,5 @@ export const DataStatisticsCore = () => {<DataStatisticsTable /></div></Spin>- );-};+ )+}diff --git a/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsDetails/dataStatisticsDetails.module.scss b/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsDetails/dataStatisticsDetails.module.scssindex 3563493e..0fc67160 100644--- a/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsDetails/dataStatisticsDetails.module.scss+++ b/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsDetails/dataStatisticsDetails.module.scss@@ -9,7 +9,7 @@position: relative;padding-left: 20px;&:after {- content: "";+ content: '';display: block;position: absolute;top: 45%;@@ -54,7 +54,7 @@&-icon {display: inline-block;margin-right: 10px;- svg, {+ svg {font-size: 18px;fill: var(--colorPrimary5);}@@ -78,4 +78,4 @@height: 400px;}}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsDetails/index.tsx b/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsDetails/index.tsxindex 2155a4a3..b0b5b24d 100644--- a/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsDetails/index.tsx+++ b/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsDetails/index.tsx@@ -1,11 +1,12 @@-import { ForwardedRef, forwardRef, memo } from "react";-import styles from "./dataStatisticsDetails.module.scss";-import { useDataStatisticsStore } from "@/app/[lng]/dataStatistics/useDataStatistics";-import { useShallow } from "zustand/react/shallow";-import Icon from "@ant-design/icons";-import { DatePicker } from "antd";-import { Dayjs } from "dayjs";-import { useTransClient } from "@/app/i18n/client";+import type { Dayjs } from 'dayjs'+import type { ForwardedRef } from 'react'+import Icon from '@ant-design/icons'+import { DatePicker } from 'antd'+import { forwardRef, memo } from 'react'+import { useShallow } from 'zustand/react/shallow'+import { useDataStatisticsStore } from '@/app/[lng]/dataStatistics/useDataStatistics'+import { useTransClient } from '@/app/i18n/client'+import styles from './dataStatisticsDetails.module.scss'export interface IDataStatisticsDetailsRef {}@@ -24,44 +25,44 @@ const DataStatisticsDetails = memo(setCurrentDetailType,timeRangeValue,} = useDataStatisticsStore(- useShallow((state) => ({+ useShallow(state => ({dataDetails: state.dataDetails,currentDetailType: state.currentDetailType,setCurrentDetailType: state.setCurrentDetailType,setTimeRangeValue: state.setTimeRangeValue,timeRangeValue: state.timeRangeValue,})),- );- const { t } = useTransClient("dataStatistics");+ )+ const { t } = useTransClient('dataStatistics')return (<div className={styles.dataStatisticsDetails}><div className="dataStatisticsDetails-head">- <h3>{t("dataDetails")}</h3>+ <h3>{t('dataDetails')}</h3><div className="dataStatisticsDetails-head-rangePicker">- <label>{t("timeRange")}</label>+ <label>{t('timeRange')}</label><DatePicker.RangePickervalue={timeRangeValue}allowClear={false}onChange={(e) => {- const dates = e as [Dayjs, Dayjs];- setTimeRangeValue(dates);+ const dates = e as [Dayjs, Dayjs]+ setTimeRangeValue(dates)}}/></div></div><div className="dataStatisticsDetails-content">- {dataDetails.map((detail) => (+ {dataDetails.map(detail => (<divkey={detail.value}className={`dataStatisticsDetails-content-item ${currentDetailType === detail.value- ? "dataStatisticsDetails-content-item--active"- : ""+ ? 'dataStatisticsDetails-content-item--active'+ : ''}`}onClick={() => {- setCurrentDetailType(detail.value);+ setCurrentDetailType(detail.value)}}><p className="dataStatisticsDetails-content-item-title">@@ -74,7 +75,7 @@ const DataStatisticsDetails = memo({detail.total}</p><p className="dataStatisticsDetails-content-item-yesterday">- {t("yesterdayIncrease")}+ {t('yesterdayIncrease')}<b>{detail.yesterday}</b></p></div>@@ -83,9 +84,9 @@ const DataStatisticsDetails = memo(<div id="dataStatisticsEchartLine" /></div>- );+ )},),-);+)-export default DataStatisticsDetails;+export default DataStatisticsDetailsdiff --git a/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsHeader/dataStatisticsHeader.module.scss b/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsHeader/dataStatisticsHeader.module.scssindex 2c56f2a2..50e42ad9 100644--- a/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsHeader/dataStatisticsHeader.module.scss+++ b/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsHeader/dataStatisticsHeader.module.scss@@ -127,8 +127,7 @@}.swiper-slide:nth-of-type(4n) .accounts-swiper-item::after,- .swiper-slide:last-of-type .accounts-swiper-item::after- {+ .swiper-slide:last-of-type .accounts-swiper-item::after {display: none;}@@ -146,4 +145,4 @@}}}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsHeader/index.tsx b/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsHeader/index.tsxindex 286ca06f..fa4a202b 100644--- a/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsHeader/index.tsx+++ b/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsHeader/index.tsx@@ -1,24 +1,25 @@-import { ForwardedRef, forwardRef, memo, useState } from "react";-import styles from "./dataStatisticsHeader.module.scss";-import AccountCount from "../../svgs/accountCount.svg";-import { Swiper, SwiperSlide } from "swiper/react";-import { useAccountStore } from "@/store/account";-import { useShallow } from "zustand/react/shallow";-import { Button, Empty, Input, Select, Skeleton, Tag, Tooltip } from "antd";-import { useDataStatisticsStore } from "@/app/[lng]/dataStatistics/useDataStatistics";+import type { ForwardedRef } from 'react'import {CheckCircleOutlined,ExclamationCircleOutlined,LeftOutlined,RightOutlined,WarningOutlined,-} from "@ant-design/icons";-import { Navigation } from "swiper/modules";-import "swiper/css";-import "swiper/css/navigation";-import AvatarPlat from "@/components/AvatarPlat";-import AddAccountModal from "@/app/[lng]/accounts/components/AddAccountModal";-import { useTransClient } from "@/app/i18n/client";+} from '@ant-design/icons'+import { Button, Empty, Input, Select, Skeleton, Tag, Tooltip } from 'antd'+import { forwardRef, memo, useState } from 'react'+import { Navigation } from 'swiper/modules'+import { Swiper, SwiperSlide } from 'swiper/react'+import { useShallow } from 'zustand/react/shallow'+import AddAccountModal from '@/app/[lng]/accounts/components/AddAccountModal'+import { useDataStatisticsStore } from '@/app/[lng]/dataStatistics/useDataStatistics'+import { useTransClient } from '@/app/i18n/client'+import AvatarPlat from '@/components/AvatarPlat'+import { useAccountStore } from '@/store/account'+import AccountCount from '../../svgs/accountCount.svg'+import styles from './dataStatisticsHeader.module.scss'+import 'swiper/css'+import 'swiper/css/navigation'export interface IDataStatisticsHeaderRef {}@@ -31,25 +32,25 @@ const DataStatisticsHeader = memo(ref: ForwardedRef<IDataStatisticsHeaderRef>,) => {const { accountGroupList } = useAccountStore(- useShallow((state) => ({+ useShallow(state => ({accountGroupList: state.accountGroupList,})),- );+ )const {choosedGroupIds,setChoosedGroupIds,filteredAccountList,setAccountSearchValue,} = useDataStatisticsStore(- useShallow((state) => ({+ useShallow(state => ({setChoosedGroupIds: state.setChoosedGroupIds,choosedGroupIds: state.choosedGroupIds,filteredAccountList: state.filteredAccountList,setAccountSearchValue: state.setAccountSearchValue,})),- );- const [addAccountModalOpen, setAddAccountModalOpen] = useState(false);- const { t } = useTransClient("dataStatistics");+ )+ const [addAccountModalOpen, setAddAccountModalOpen] = useState(false)+ const { t } = useTransClient('dataStatistics')return (<div className={styles.dataStatisticsHeader}>@@ -64,129 +65,138 @@ const DataStatisticsHeader = memo(/><div className="dataStatisticsHeader-top">- <h2>{t("accountData")}</h2>+ <h2>{t('accountData')}</h2><div className="dataStatisticsHeader-top-options"><Selectmode="multiple"value={choosedGroupIds}- style={{ width: "220px" }}+ style={{ width: '220px' }}options={accountGroupList}- fieldNames={{ value: "id", label: "name" }}- placeholder={t("selectSpace")}+ fieldNames={{ value: 'id', label: 'name' }}+ placeholder={t('selectSpace')}maxTagCount={1}onChange={(value) => {- setChoosedGroupIds(value);+ setChoosedGroupIds(value)}}/><Input.Search- style={{ width: "300px" }}- placeholder={t("inputAccountName")}+ style={{ width: '300px' }}+ placeholder={t('inputAccountName')}allowClearonSearch={(value) => {- setAccountSearchValue(value);+ setAccountSearchValue(value)}}/></div></div><div className="dataStatisticsHeader-accounts">- {filteredAccountList.length === 0 ? (- <>- <Empty- style={{ width: "100%", height: "100%" }}- description={t("noAccount")}- />- </>- ) : (- <>- <div className="dataStatisticsHeader-accountCount">- <div className="dataStatisticsHeader-accountCount-title">- <AccountCount />- {t("totalAccount")}- </div>- <div className="dataStatisticsHeader-accountCount-number">- {filteredAccountList.length}- </div>- <Tag bordered={false} icon={<CheckCircleOutlined />}>- {t("online")}{" "}- <b>- {filteredAccountList.filter((v) => v.status === 1).length}- </b>- </Tag>- <br />- <Tag bordered={false} icon={<WarningOutlined />}>- {t("offline")}{" "}- <b>- {filteredAccountList.filter((v) => v.status === 0).length}- </b>- </Tag>- </div>+ {filteredAccountList.length === 0+ ? (+ <>+ <Empty+ style={{ width: '100%', height: '100%' }}+ description={t('noAccount')}+ />+ </>+ )+ : (+ <>+ <div className="dataStatisticsHeader-accountCount">+ <div className="dataStatisticsHeader-accountCount-title">+ <AccountCount />+ {t('totalAccount')}+ </div>+ <div className="dataStatisticsHeader-accountCount-number">+ {filteredAccountList.length}+ </div>+ <Tag bordered={false} icon={<CheckCircleOutlined />}>+ {t('online')}+ {' '}+ <b>+ {filteredAccountList.filter(v => v.status === 1).length}+ </b>+ </Tag>+ <br />+ <Tag bordered={false} icon={<WarningOutlined />}>+ {t('offline')}+ {' '}+ <b>+ {filteredAccountList.filter(v => v.status === 0).length}+ </b>+ </Tag>+ </div>- <div className="dataStatisticsHeader-accounts-swiper">- <Button className="swiper-prev" icon={<LeftOutlined />} />+ <div className="dataStatisticsHeader-accounts-swiper">+ <Button className="swiper-prev" icon={<LeftOutlined />} />- {accountGroupList.length === 0 ? (- <Skeleton active />- ) : (- <Swiper- modules={[Navigation]}- slidesPerView={4}- slidesPerGroup={4}- navigation={{- prevEl: ".swiper-prev",- nextEl: ".swiper-next",- }}- >- {filteredAccountList.map((account) => {- return (- <SwiperSlide key={account.id}>- <div className="accounts-swiper-item">- <div className="accounts-swiper-item-info">- <AvatarPlat account={account} size="large" />- <Tooltip title={account.nickname}>- <div className="accounts-swiper-item-info-name">- {account.nickname}- </div>- </Tooltip>- </div>+ {accountGroupList.length === 0+ ? (+ <Skeleton active />+ )+ : (+ <Swiper+ modules={[Navigation]}+ slidesPerView={4}+ slidesPerGroup={4}+ navigation={{+ prevEl: '.swiper-prev',+ nextEl: '.swiper-next',+ }}+ >+ {filteredAccountList.map((account) => {+ return (+ <SwiperSlide key={account.id}>+ <div className="accounts-swiper-item">+ <div className="accounts-swiper-item-info">+ <AvatarPlat account={account} size="large" />+ <Tooltip title={account.nickname}>+ <div className="accounts-swiper-item-info-name">+ {account.nickname}+ </div>+ </Tooltip>+ </div>- {account.status === 1 ? (- <div className="accounts-swiper-item-fans">- {t("fansCount")}{" "}- <span>{account.fansCount}</span>- </div>- ) : (- <div className="accounts-swiper-item-offline">- <span>- <ExclamationCircleOutlined />- {t("loginFailed")}- </span>- <a- onClick={(e) => {- e.preventDefault();- setAddAccountModalOpen(true);- }}- >- {t("relogin")}- </a>- </div>- )}- </div>- </SwiperSlide>- );- })}- </Swiper>- )}+ {account.status === 1+ ? (+ <div className="accounts-swiper-item-fans">+ {t('fansCount')}+ {' '}+ <span>{account.fansCount}</span>+ </div>+ )+ : (+ <div className="accounts-swiper-item-offline">+ <span>+ <ExclamationCircleOutlined />+ {t('loginFailed')}+ </span>+ <a+ onClick={(e) => {+ e.preventDefault()+ setAddAccountModalOpen(true)+ }}+ >+ {t('relogin')}+ </a>+ </div>+ )}+ </div>+ </SwiperSlide>+ )+ })}+ </Swiper>+ )}- <Button className="swiper-next" icon={<RightOutlined />} />- </div>- </>- )}+ <Button className="swiper-next" icon={<RightOutlined />} />+ </div>+ </>+ )}</div></div>- );+ )},),-);+)-export default DataStatisticsHeader;+export default DataStatisticsHeaderdiff --git a/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsTable/dataStatisticsTable.module.scss b/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsTable/dataStatisticsTable.module.scssindex 35126f16..f64c9243 100644--- a/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsTable/dataStatisticsTable.module.scss+++ b/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsTable/dataStatisticsTable.module.scss@@ -7,4 +7,4 @@}}}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsTable/index.tsx b/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsTable/index.tsxindex 55dfa404..2238cc79 100644--- a/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsTable/index.tsx+++ b/project/web/src/app/[lng]/dataStatistics/components/DataStatisticsTable/index.tsx@@ -1,15 +1,16 @@-import React, { ForwardedRef, forwardRef, memo, useMemo } from "react";-import styles from "./dataStatisticsTable.module.scss";-import { Table } from "antd";-import type { TableProps } from "antd";-import {+import type { TableProps } from 'antd'+import type { ForwardedRef } from 'react'+import type {StatisticsPeriodItems,StatisticsPeriodItems2,-} from "@/api/types/dataStatistics";-import { useDataStatisticsStore } from "@/app/[lng]/dataStatistics/useDataStatistics";-import { useShallow } from "zustand/react/shallow";-import { useAccountStore } from "@/store/account";-import AvatarPlat from "@/components/AvatarPlat";+} from '@/api/types/dataStatistics'+import { Table } from 'antd'+import React, { forwardRef, memo, useMemo } from 'react'+import { useShallow } from 'zustand/react/shallow'+import { useDataStatisticsStore } from '@/app/[lng]/dataStatistics/useDataStatistics'+import AvatarPlat from '@/components/AvatarPlat'+import { useAccountStore } from '@/store/account'+import styles from './dataStatisticsTable.module.scss'export interface IDataStatisticsTableRef {}@@ -22,20 +23,20 @@ const DataStatisticsTable = memo(ref: ForwardedRef<IDataStatisticsTableRef>,) => {const { originData, dataDetails } = useDataStatisticsStore(- useShallow((state) => ({+ useShallow(state => ({originData: state.originData,dataDetails: state.dataDetails,})),- );+ )const { accountList } = useAccountStore(- useShallow((state) => ({+ useShallow(state => ({accountList: state.accountList,})),- );+ )// key=uid, value=该账号对应的数据,此数据是累加的值const data = useMemo(() => {- const d: { [key: string]: Partial<StatisticsPeriodItems2> } = {};+ const d: { [key: string]: Partial<StatisticsPeriodItems2> } = {}originData?.items?.map((v) => {if (!d[v.uid]) {@@ -48,43 +49,43 @@ const DataStatisticsTable = memo(collectCount: 0,forwardCount: 0,workCount: 0,- };+ }}// 累加该账号的各项数据v.items?.map((item) => {- d[v.uid]!.commentCount! += item.commentCount || 0;- d[v.uid]!.followingCount! += item.followingCount || 0;- d[v.uid]!.likeCount! += item.likeCount || 0;- d[v.uid]!.fansCount! += item.fansCount || 0;- d[v.uid]!.readCount! += item.readCount || 0;- d[v.uid]!.collectCount! += item.collectCount || 0;- d[v.uid]!.forwardCount! += item.forwardCount || 0;- d[v.uid]!.workCount! += item.workCount || 0;- });- });+ d[v.uid]!.commentCount! += item.commentCount || 0+ d[v.uid]!.followingCount! += item.followingCount || 0+ d[v.uid]!.likeCount! += item.likeCount || 0+ d[v.uid]!.fansCount! += item.fansCount || 0+ d[v.uid]!.readCount! += item.readCount || 0+ d[v.uid]!.collectCount! += item.collectCount || 0+ d[v.uid]!.forwardCount! += item.forwardCount || 0+ d[v.uid]!.workCount! += item.workCount || 0+ })+ })- return d;- }, [originData]);+ return d+ }, [originData])const columns = useMemo(() => {- const columns: TableProps<StatisticsPeriodItems>["columns"] = [+ const columns: TableProps<StatisticsPeriodItems>['columns'] = [{- title: "账号",- key: "uid",+ title: '账号',+ key: 'uid',render: (text, item) => {- const account = accountList.find((v) => v.uid === item.uid)!;+ const account = accountList.find(v => v.uid === item.uid)!return (<div><AvatarPlat account={account} />- <span style={{ display: "inline-block", marginLeft: "10px" }}>+ <span style={{ display: 'inline-block', marginLeft: '10px' }}>{account?.nickname}</span></div>- );+ )},},- ];+ ]dataDetails.map((v) => {columns.push({@@ -92,36 +93,36 @@ const DataStatisticsTable = memo(key: v.value,sorter: (a, b) => {// @ts-ignore- const aValue = data[a.uid]?.[v.value] || 0;+ const aValue = data[a.uid]?.[v.value] || 0// @ts-ignore- const bValue = data[b.uid]?.[v.value] || 0;- return aValue - bValue;+ const bValue = data[b.uid]?.[v.value] || 0+ return aValue - bValue},render: (text, item) => {// @ts-ignore- return <span>{data[item.uid]?.[v.value] || 0}</span>;+ return <span>{data[item.uid]?.[v.value] || 0}</span>},- });- });+ })+ })- return columns;- }, [accountList, data, dataDetails]);+ return columns+ }, [accountList, data, dataDetails])return (<div className={styles.dataStatisticsTable}><Table<StatisticsPeriodItems>columns={columns}key="uid"- dataSource={originData?.items?.map((item) => ({+ dataSource={originData?.items?.map(item => ({...item,key: item.uid,}))}- scroll={{ y: "400px" }}+ scroll={{ y: '400px' }}/></div>- );+ )},),-);+)-export default DataStatisticsTable;+export default DataStatisticsTablediff --git a/project/web/src/app/[lng]/dataStatistics/dataStatistics.module.scss b/project/web/src/app/[lng]/dataStatistics/dataStatistics.module.scssindex efc7582a..3b042473 100644--- a/project/web/src/app/[lng]/dataStatistics/dataStatistics.module.scss+++ b/project/web/src/app/[lng]/dataStatistics/dataStatistics.module.scss@@ -1,3 +1,3 @@.dataStatistics {padding: 20px;-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/dataStatistics/echart/drawDataStatisticsEchartLine.ts b/project/web/src/app/[lng]/dataStatistics/echart/drawDataStatisticsEchartLine.tsindex 06ba514b..85e904c4 100644--- a/project/web/src/app/[lng]/dataStatistics/echart/drawDataStatisticsEchartLine.ts+++ b/project/web/src/app/[lng]/dataStatistics/echart/drawDataStatisticsEchartLine.ts@@ -1,64 +1,64 @@-import * as echarts from "echarts";-import { useDataStatisticsStore } from "../useDataStatistics";-import { describeNumber } from "@/utils"; // 引入store+import * as echarts from 'echarts'+import { describeNumber } from '@/utils' // 引入store+import { useDataStatisticsStore } from '../useDataStatistics'-type EChartsOption = echarts.EChartsOption;+type EChartsOption = echarts.EChartsOptionexport default function drawDataStatisticsEchartLine(elId: string) {- const chartDom = document.getElementById(elId)!;- const chartDomAny = chartDom as any;+ const chartDom = document.getElementById(elId)!+ const chartDomAny = chartDom as any// 先销毁已有实例,防止重复初始化报错if (echarts.getInstanceByDom(chartDom)) {- echarts.dispose(chartDom);+ echarts.dispose(chartDom)}- const myChart = echarts.init(chartDom);+ const myChart = echarts.init(chartDom)// 获取store中的echartData- const { legend, xAxis, series } =- useDataStatisticsStore.getState().echartData;+ const { legend, xAxis, series }+ = useDataStatisticsStore.getState().echartDataconst option: EChartsOption = {tooltip: {- trigger: "axis",+ trigger: 'axis',},legend: {top: 25,data: legend,},grid: {- left: "3%",- right: "4%",- bottom: "3%",+ left: '3%',+ right: '4%',+ bottom: '3%',containLabel: true,},xAxis: {- type: "category",+ type: 'category',boundaryGap: false,data: xAxis,},yAxis: {- type: "value",+ type: 'value',axisLabel: {- formatter: function (value: number) {- return describeNumber(value);+ formatter(value: number) {+ return describeNumber(value)},},},// @ts-ignore- series: series,- };+ series,+ }if (option) {- myChart.setOption(option);+ myChart.setOption(option)}// 先移除旧的resize事件监听,防止重复绑定if (chartDomAny._resizeHandler) {- window.removeEventListener("resize", chartDomAny._resizeHandler);+ window.removeEventListener('resize', chartDomAny._resizeHandler)}function handleResize() {- myChart.resize();+ myChart.resize()}- window.addEventListener("resize", handleResize);- chartDomAny._resizeHandler = handleResize;+ window.addEventListener('resize', handleResize)+ chartDomAny._resizeHandler = handleResize}diff --git a/project/web/src/app/[lng]/dataStatistics/page.tsx b/project/web/src/app/[lng]/dataStatistics/page.tsxindex 09d95e42..4ba02c32 100644--- a/project/web/src/app/[lng]/dataStatistics/page.tsx+++ b/project/web/src/app/[lng]/dataStatistics/page.tsx@@ -1,20 +1,20 @@-import { PageParams } from "@/app/globals";-import { useTranslation } from "@/app/i18n";-import { getMetadata } from "@/utils/general";-import { DataStatisticsCore } from "@/app/[lng]/dataStatistics/DataStatisticsCore";+import type { PageParams } from '@/app/globals'+import { DataStatisticsCore } from '@/app/[lng]/dataStatistics/DataStatisticsCore'+import { useTranslation } from '@/app/i18n'+import { getMetadata } from '@/utils/general'export async function generateMetadata({ params }: PageParams) {- const { lng } = await params;- const { t } = await useTranslation(lng, "dataStatistics");+ const { lng } = await params+ const { t } = await useTranslation(lng, 'dataStatistics')return await getMetadata({- title: t("title"),- description: t("description"),+ title: t('title'),+ description: t('description'),},lng,- );+ )}export default function Page() {- return <DataStatisticsCore />;+ return <DataStatisticsCore />}diff --git a/project/web/src/app/[lng]/dataStatistics/useDataStatistics.tsx b/project/web/src/app/[lng]/dataStatistics/useDataStatistics.tsxindex 8358ec0f..1a4356ab 100644--- a/project/web/src/app/[lng]/dataStatistics/useDataStatistics.tsx+++ b/project/web/src/app/[lng]/dataStatistics/useDataStatistics.tsx@@ -1,66 +1,68 @@-import { create } from "zustand/index";-import { combine } from "zustand/middleware";-import { SocialAccount } from "@/api/types/account.type";-import FansCount from "./svgs/fansCount.svg";-import CollectCount from "./svgs/collectCount.svg";-import ForwardCount from "./svgs/forwardCount.svg";+import type { Dayjs } from 'dayjs'+import type { SocialAccount } from '@/api/types/account.type'+import type { StatisticsPeriodModel } from '@/api/types/dataStatistics'+import type { PlatType } from '@/app/config/platConfig'import {HeartFilled,- VideoCameraFilled,MessageFilled,-} from "@ant-design/icons";-import dayjs, { Dayjs } from "dayjs";-import { getStatisticsPeriodApi } from "@/api/dataStatistics";-import { StatisticsPeriodModel } from "@/api/types/dataStatistics";-import { message } from "antd";-import drawDataStatisticsEchartLine from "@/app/[lng]/dataStatistics/echart/drawDataStatisticsEchartLine";-import { directTrans } from "@/app/i18n/client";-import { AccountPlatInfoMap, PlatType } from "@/app/config/platConfig";+ VideoCameraFilled,+} from '@ant-design/icons'+import { message } from 'antd'+import dayjs from 'dayjs'+import { create } from 'zustand/index'+import { combine } from 'zustand/middleware'+import { getStatisticsPeriodApi } from '@/api/dataStatistics'+import drawDataStatisticsEchartLine from '@/app/[lng]/dataStatistics/echart/drawDataStatisticsEchartLine'+import { AccountPlatInfoMap } from '@/app/config/platConfig'+import { directTrans } from '@/app/i18n/client'+import CollectCount from './svgs/collectCount.svg'+import FansCount from './svgs/fansCount.svg'+import ForwardCount from './svgs/forwardCount.svg'export interface IDataStatisticsStore {// 当前选择的账户组IDs- choosedGroupIds: string[];+ choosedGroupIds: string[]// 过滤之后的账户- filteredAccountList: SocialAccount[];+ filteredAccountList: SocialAccount[]// 数据明细dataDetails: {- title: string;- value: string;- icon: any;+ title: string+ value: string+ icon: any// 总数- total: number;+ total: number// 昨日数- yesterday: number;- }[];+ yesterday: number+ }[]// 当前选择的明细类型- currentDetailType: string;+ currentDetailType: string// 账号搜索value- accountSearchValue: string;+ accountSearchValue: string// 日期范围- timeRangeValue: [Dayjs, Dayjs];+ timeRangeValue: [Dayjs, Dayjs]// 源数据- originData?: StatisticsPeriodModel;+ originData?: StatisticsPeriodModel// loading- loading: boolean;+ loading: boolean// echart 数据,直接适配 ECharts 格式echartData: {- legend: string[];- xAxis: string[];+ legend: string[]+ xAxis: string[]series: {- name: string;- type: string;- data: number[];- }[];- };+ name: string+ type: string+ data: number[]+ }[]+ }}const state: IDataStatisticsStore = {- accountSearchValue: "",+ accountSearchValue: '',choosedGroupIds: [],filteredAccountList: [],dataDetails: [],- currentDetailType: "",- timeRangeValue: [dayjs().subtract(7, "day"), dayjs()],+ currentDetailType: '',+ timeRangeValue: [dayjs().subtract(7, 'day'), dayjs()],loading: false,originData: undefined,echartData: {@@ -68,7 +70,7 @@ const state: IDataStatisticsStore = {xAxis: [],series: [],},-};+}export const useDataStatisticsStore = create(combine(@@ -80,194 +82,196 @@ export const useDataStatisticsStore = create(async init() {const dataDetails = [{- title: directTrans("dataStatistics", "growthFansCount"),- value: "fansCount",+ title: directTrans('dataStatistics', 'growthFansCount'),+ value: 'fansCount',icon: FansCount,total: 0,yesterday: 0,},{- title: directTrans("dataStatistics", "readCount"),- value: "readCount",+ title: directTrans('dataStatistics', 'readCount'),+ value: 'readCount',icon: VideoCameraFilled,total: 0,yesterday: 0,},{- title: directTrans("dataStatistics", "commentCount"),- value: "commentCount",+ title: directTrans('dataStatistics', 'commentCount'),+ value: 'commentCount',icon: MessageFilled,total: 0,yesterday: 0,},{- title: directTrans("dataStatistics", "likeCount"),- value: "likeCount",+ title: directTrans('dataStatistics', 'likeCount'),+ value: 'likeCount',icon: HeartFilled,total: 0,yesterday: 0,},{- title: directTrans("dataStatistics", "collectCount"),- value: "collectCount",+ title: directTrans('dataStatistics', 'collectCount'),+ value: 'collectCount',icon: CollectCount,total: 0,yesterday: 0,},{- title: directTrans("dataStatistics", "forwardCount"),- value: "forwardCount",+ title: directTrans('dataStatistics', 'forwardCount'),+ value: 'forwardCount',icon: ForwardCount,total: 0,yesterday: 0,},- ];+ ]set({dataDetails,currentDetailType: dataDetails[0].value,- });+ })},// 获取数据统计async getStatistics() {if (get().filteredAccountList.length === 0) {- return;+ return}set({loading: true,- });+ })// 过滤掉无效的account和account.typeconst validAccounts = get().filteredAccountList.filter(- (account) => account && account.type && account.uid,- );+ account => account && account.type && account.uid,+ )const res = await getStatisticsPeriodApi({- startDate: get().timeRangeValue[0].format("YYYY-MM-DD"),- endDate: get().timeRangeValue[1].format("YYYY-MM-DD"),- queries: validAccounts.map((account) => ({+ startDate: get().timeRangeValue[0].format('YYYY-MM-DD'),+ endDate: get().timeRangeValue[1].format('YYYY-MM-DD'),+ queries: validAccounts.map(account => ({platform: account.type,uid: account.uid,})),- });+ })set({loading: false,- });+ })if (!res || !res.data) {- message.error("获取数据统计失败,请稍后重试");- return;+ message.error('获取数据统计失败,请稍后重试')+ return}set({originData: res.data,- });+ })- methods.sortingData();+ methods.sortingData()},// 分拣数据sortingData() {- const data = get().originData;+ const data = get().originData- if (!data) return;+ if (!data)+ return// 1. 汇总各指标总数- const metrics = get().dataDetails.map((e) => e.value);- const totals: Record<string, number> = {};- metrics.forEach((m) => (totals[m] = 0));+ const metrics = get().dataDetails.map(e => e.value)+ const totals: Record<string, number> = {}+ metrics.forEach(m => (totals[m] = 0))data.groupedByDate.forEach((day) => {day.records.forEach((rec) => {metrics.forEach((m) => {// @ts-ignore- totals[m] += rec[m] ?? 0;- });- });- });+ totals[m] += rec[m] ?? 0+ })+ })+ })set({- dataDetails: get().dataDetails.map((item) => ({+ dataDetails: get().dataDetails.map(item => ({...item,total: totals[item.value] ?? 0,})),- });+ })// 2. 统计前一天数据- const endDate = get().timeRangeValue[1].format("YYYY-MM-DD");+ const endDate = get().timeRangeValue[1].format('YYYY-MM-DD')const prevDay = dayjs(endDate)- .subtract(1, "day")- .format("YYYY-MM-DD");+ .subtract(1, 'day')+ .format('YYYY-MM-DD')const prevDayData = data.groupedByDate.find(- (d) => d.date === prevDay,- );- const yesterdayTotals: Record<string, number> = {};+ d => d.date === prevDay,+ )+ const yesterdayTotals: Record<string, number> = {}if (prevDayData) {- const metrics = get().dataDetails.map((e) => e.value);- metrics.forEach((m) => (yesterdayTotals[m] = 0));+ const metrics = get().dataDetails.map(e => e.value)+ metrics.forEach(m => (yesterdayTotals[m] = 0))prevDayData.records.forEach((rec) => {metrics.forEach((m) => {// @ts-ignore- yesterdayTotals[m] += rec[m] ?? 0;- });- });+ yesterdayTotals[m] += rec[m] ?? 0+ })+ })}// 3. 更新 dataDetailsset({- dataDetails: get().dataDetails.map((item) => ({+ dataDetails: get().dataDetails.map(item => ({...item,yesterday:- prevDayData && typeof yesterdayTotals[item.value] === "number"+ prevDayData && typeof yesterdayTotals[item.value] === 'number'? yesterdayTotals[item.value]: item.yesterday,})),- });+ })// 4. 生成 ECharts 适配数据- const currentField = get().currentDetailType;+ const currentField = get().currentDetailType// 日期const dates = Array.from(- new Set(data.groupedByDate.map((e) => e.date)),- ).sort();- const dateIndex: Record<string, number> = {};- dates.forEach((d, i) => (dateIndex[d] = i));+ new Set(data.groupedByDate.map(e => e.date)),+ ).sort()+ const dateIndex: Record<string, number> = {}+ dates.forEach((d, i) => (dateIndex[d] = i))// 平台- const platformSet = new Set<string>();- data.groupedByDate.forEach((g) =>- g.records.forEach((r) => platformSet.add(r.platform)),- );- const platforms = Array.from(platformSet).sort() as PlatType[];+ const platformSet = new Set<string>()+ data.groupedByDate.forEach(g =>+ g.records.forEach(r => platformSet.add(r.platform)),+ )+ const platforms = Array.from(platformSet).sort() as PlatType[]// 初始化矩阵- const chartData: Record<string, number[]> = {};+ const chartData: Record<string, number[]> = {}platforms.forEach(- (p) => (chartData[p] = Array(dates.length).fill(0)),- );+ // @ts-ignore+ p => (chartData[p] = Array.from({ length: dates.length }).fill(0)),+ )// 填充数据data.groupedByDate.forEach((g) => {- const dIdx = dateIndex[g.date];+ const dIdx = dateIndex[g.date]g.records.forEach((r) => {- const p = r.platform;+ const p = r.platformif (chartData[p]) {// @ts-ignore- chartData[p][dIdx] = r[currentField] ?? 0;+ chartData[p][dIdx] = r[currentField] ?? 0}- });- });+ })+ })// 组装 ECharts 格式const legend = platforms.map(- (v) => AccountPlatInfoMap.get(v)?.name || v,- );- const xAxis = dates;- const series = platforms.map((p) => ({+ v => AccountPlatInfoMap.get(v)?.name || v,+ )+ const xAxis = dates+ const series = platforms.map(p => ({name: AccountPlatInfoMap.get(p)?.name || p,- type: "line",+ type: 'line',data: chartData[p],- }));+ }))set({echartData: {@@ -275,44 +279,44 @@ export const useDataStatisticsStore = create(xAxis,series,},- });+ })- drawDataStatisticsEchartLine("dataStatisticsEchartLine");+ drawDataStatisticsEchartLine('dataStatisticsEchartLine')},// 设置 timeRangeValuesetTimeRangeValue(timeRangeValue: [Dayjs, Dayjs]) {set({timeRangeValue,- });+ })},// 设置 currentDetailTypesetCurrentDetailType(currentDetailType: string) {set({currentDetailType,- });+ })},// 设置选择账户组IDssetChoosedGroupIds(choosedGroupIds: string[]) {set({choosedGroupIds,- });+ })},// 设置过滤之后的账户setFilteredAccountList(filteredAccountList: SocialAccount[]) {set({filteredAccountList,- });+ })},// 设置 accountSearchValuesetAccountSearchValue(accountSearchValue: string) {set({accountSearchValue,- });+ })},- };+ }- return methods;+ return methods},),-);+)diff --git a/project/web/src/app/[lng]/forgot-password/forgot-password.module.css b/project/web/src/app/[lng]/forgot-password/forgot-password.module.cssindex 7f8090ce..5db37f42 100644--- a/project/web/src/app/[lng]/forgot-password/forgot-password.module.css+++ b/project/web/src/app/[lng]/forgot-password/forgot-password.module.css@@ -96,7 +96,7 @@.box {padding: 24px;}-+.title {font-size: 24px;margin-bottom: 24px;@@ -109,4 +109,4 @@.submitButton {height: 40px !important;}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/forgot-password/page.tsx b/project/web/src/app/[lng]/forgot-password/page.tsxindex 9a563c58..503a4989 100644--- a/project/web/src/app/[lng]/forgot-password/page.tsx+++ b/project/web/src/app/[lng]/forgot-password/page.tsx@@ -1,65 +1,69 @@-"use client";+'use client'-import { useState, useEffect } from "react";-import { Form, Input, Button, message, Modal } from "antd";-import { useRouter } from "next/navigation";-import Link from "next/link";-import { sendResetPasswordMailApi, resetPasswordApi } from "@/api/apiReq";-import { useTransClient } from "@/app/i18n/client";-import styles from "./forgot-password.module.css";+import { Button, Form, Input, message, Modal } from 'antd'+import Link from 'next/link'+import { useRouter } from 'next/navigation'+import { useEffect, useState } from 'react'+import { resetPasswordApi, sendResetPasswordMailApi } from '@/api/apiReq'+import { useTransClient } from '@/app/i18n/client'+import styles from './forgot-password.module.css'export default function ForgotPasswordPage() {- const router = useRouter();- const { t } = useTransClient("login");- const [form] = Form.useForm();- const [loading, setLoading] = useState(false);- const [isModalOpen, setIsModalOpen] = useState(false);- const [resetForm] = Form.useForm();+ const router = useRouter()+ const { t } = useTransClient('login')+ const [form] = Form.useForm()+ const [loading, setLoading] = useState(false)+ const [isModalOpen, setIsModalOpen] = useState(false)+ const [resetForm] = Form.useForm()// 处理Modal关闭const handleModalClose = () => {- setIsModalOpen(false);- resetForm.resetFields();- };+ setIsModalOpen(false)+ resetForm.resetFields()+ }// 处理发送重置密码邮件const handleSubmit = async (values: { mail: string }) => {try {- setLoading(true);- const response: any = await sendResetPasswordMailApi(values);+ setLoading(true)+ const response: any = await sendResetPasswordMailApi(values)if (response.code === 0) {- message.success(t('resetEmailSent' as any));- setIsModalOpen(true);+ message.success(t('resetEmailSent' as any))+ setIsModalOpen(true)}- } catch (error) {- message.error(t('sendEmailFailed' as any));- } finally {- setLoading(false);}- };+ catch (error) {+ message.error(t('sendEmailFailed' as any))+ }+ finally {+ setLoading(false)+ }+ }// 处理重置密码- const handleResetPassword = async (values: { code: string; password: string }) => {+ const handleResetPassword = async (values: { code: string, password: string }) => {try {- setLoading(true);+ setLoading(true)const response: any = await resetPasswordApi({code: values.code,mail: form.getFieldValue('mail'),- password: values.password- });+ password: values.password,+ })if (response.code === 0) {- message.success(t('resetSuccess' as any));- setIsModalOpen(false);- router.push('/login');+ message.success(t('resetSuccess' as any))+ setIsModalOpen(false)+ router.push('/login')}- } catch (error) {- message.error(t('resetFailed' as any));- } finally {- setLoading(false);}- };+ catch (error) {+ message.error(t('resetFailed' as any))+ }+ finally {+ setLoading(false)+ }+ }return (<div className={styles.container}>@@ -75,17 +79,17 @@ export default function ForgotPasswordPage() {label={t('emailLabel' as any)}rules={[{ required: true, message: t('emailRequired' as any) },- { type: 'email', message: t('emailInvalid' as any) }+ { type: 'email', message: t('emailInvalid' as any) },]}><Input placeholder={t('emailPlaceholder' as any)} /></Form.Item><Form.Item>- <Button- type="primary"- htmlType="submit"- block+ <Button+ type="primary"+ htmlType="submit"+ blockloading={loading}className={styles.submitButton}>@@ -117,7 +121,7 @@ export default function ForgotPasswordPage() {name="code"label={t('verificationCode' as any)}rules={[- { required: true, message: t('verificationCodeRequired' as any) }+ { required: true, message: t('verificationCodeRequired' as any) },]}><Input placeholder={t('verificationCodePlaceholder' as any)} />@@ -128,7 +132,7 @@ export default function ForgotPasswordPage() {label={t('newPassword' as any)}rules={[{ required: true, message: t('newPasswordRequired' as any) },- { min: 6, message: t('newPasswordMinLength' as any) }+ { min: 6, message: t('newPasswordMinLength' as any) },]}><Input.Password placeholder={t('newPasswordPlaceholder' as any)} />@@ -143,9 +147,9 @@ export default function ForgotPasswordPage() {({ getFieldValue }) => ({validator(_, value) {if (!value || getFieldValue('password') === value) {- return Promise.resolve();+ return Promise.resolve()}- return Promise.reject(new Error(t('confirmPasswordMismatch' as any)));+ return Promise.reject(new Error(t('confirmPasswordMismatch' as any)))},}),]}@@ -154,10 +158,10 @@ export default function ForgotPasswordPage() {</Form.Item><Form.Item>- <Button- type="primary"- htmlType="submit"- block+ <Button+ type="primary"+ htmlType="submit"+ blockloading={loading}className={styles.submitButton}>@@ -167,5 +171,5 @@ export default function ForgotPasswordPage() {</Form></Modal></div>- );-}\ No newline at end of file+ )+}diff --git a/project/web/src/app/[lng]/healthz/page.tsx b/project/web/src/app/[lng]/healthz/page.tsxindex db02fc88..4f23abcb 100644--- a/project/web/src/app/[lng]/healthz/page.tsx+++ b/project/web/src/app/[lng]/healthz/page.tsx@@ -6,14 +6,15 @@ export default function HealthzPage() {<meta name="viewport" content="width=device-width, initial-scale=1" /></head><body style={{ margin: 0, padding: 0 }}>- <div style={{- display: 'flex',- justifyContent: 'center',- alignItems: 'center',+ <div style={{+ display: 'flex',+ justifyContent: 'center',+ alignItems: 'center',height: '100vh',fontFamily: 'Arial, sans-serif',- backgroundColor: '#fff'- }}>+ backgroundColor: '#fff',+ }}+ ><div style={{ textAlign: 'center' }}><h1 style={{ color: '#4CAF50', marginBottom: '20px' }}>OK</h1><p style={{ color: '#666', fontSize: '16px' }}>Service is healthy</p>@@ -21,5 +22,5 @@ export default function HealthzPage() {</div></body></html>- );+ )}diff --git a/project/web/src/app/[lng]/hotContent/HotContentCore.tsx b/project/web/src/app/[lng]/hotContent/HotContentCore.tsxindex fc2e8780..ff8806f0 100644--- a/project/web/src/app/[lng]/hotContent/HotContentCore.tsx+++ b/project/web/src/app/[lng]/hotContent/HotContentCore.tsx@@ -1,27 +1,27 @@-"use client";-import styles from "./hotContent.module.scss";-import HotContentSidebar from "@/app/[lng]/hotContent/components/HotContentSidebar";-import HotContent from "@/app/[lng]/hotContent/components/HotContent";-import { useHotContent } from "@/app/[lng]/hotContent/useHotContent";-import { useShallow } from "zustand/react/shallow";-import { HotType } from "@/app/[lng]/hotContent/hotContent.enum";-import HotEvent from "@/app/[lng]/hotContent/components/HotEvent";-import HotFeatures from "@/app/[lng]/hotContent/components/HotFeatures";-import HotTitle from "@/app/[lng]/hotContent/components/HotTitle";-import { Spin } from "antd";-import { RankingContentsResponse } from "@/api/hot";+'use client'+import type { RankingContentsResponse } from '@/api/hot'+import { Spin } from 'antd'+import { useShallow } from 'zustand/react/shallow'+import HotContent from '@/app/[lng]/hotContent/components/HotContent'+import HotContentSidebar from '@/app/[lng]/hotContent/components/HotContentSidebar'+import HotEvent from '@/app/[lng]/hotContent/components/HotEvent'+import HotFeatures from '@/app/[lng]/hotContent/components/HotFeatures'+import HotTitle from '@/app/[lng]/hotContent/components/HotTitle'+import { HotType } from '@/app/[lng]/hotContent/hotContent.enum'+import { useHotContent } from '@/app/[lng]/hotContent/useHotContent'+import styles from './hotContent.module.scss'-export const HotContentCore = ({+export function HotContentCore({defaultHotContentData,}: {- defaultHotContentData?: RankingContentsResponse;-}) => {+ defaultHotContentData?: RankingContentsResponse+}) {const { hotType, pageLoading } = useHotContent(- useShallow((state) => ({+ useShallow(state => ({hotType: state.hotType,pageLoading: state.pageLoading,})),- );+ )return (<Spin@@ -33,17 +33,23 @@ export const HotContentCore = ({<HotContentSidebar /><div className="hotContent-content">- {hotType === HotType.hotContent ? (- <HotContent defaultHotContentData={defaultHotContentData} />- ) : hotType === HotType.hotEvent ? (- <HotEvent />- ) : hotType === HotType.hotFeatures ? (- <HotFeatures />- ) : (- <HotTitle />- )}+ {hotType === HotType.hotContent+ ? (+ <HotContent defaultHotContentData={defaultHotContentData} />+ )+ : hotType === HotType.hotEvent+ ? (+ <HotEvent />+ )+ : hotType === HotType.hotFeatures+ ? (+ <HotFeatures />+ )+ : (+ <HotTitle />+ )}</div></div></Spin>- );-};+ )+}diff --git a/project/web/src/app/[lng]/hotContent/components/HotContent/hotContent.module.scss b/project/web/src/app/[lng]/hotContent/components/HotContent/hotContent.module.scssindex 483b4e93..837b1224 100644--- a/project/web/src/app/[lng]/hotContent/components/HotContent/hotContent.module.scss+++ b/project/web/src/app/[lng]/hotContent/components/HotContent/hotContent.module.scss@@ -57,14 +57,16 @@}}- .ant-spin-container, .ant-spin-nested-loading {+ .ant-spin-container,+ .ant-spin-nested-loading {height: 100%;min-height: 0;display: flex;flex-direction: column;}- .hotContent--wechat, .hotContent--bilibili {+ .hotContent--wechat,+ .hotContent--bilibili {.baseInfo-cover {width: 110px !important;height: 75px !important;@@ -79,7 +81,7 @@line-height: 30px;text-align: center;color: #fff;- background: url("../../../../../images/bg-rank-index.png") no-repeat center / cover;+ background: url('../../../../../images/bg-rank-index.png') no-repeat center / cover;}.baseInfo {@@ -131,7 +133,6 @@}.baseInfo-cover {-}}}@@ -226,14 +227,12 @@height: 400px;:global {.baseInfoPopver-head {-}.baseInfoPopver-content {height: 100%;overflow: auto;}.baseInfoPopver-footer {-}}}diff --git a/project/web/src/app/[lng]/hotContent/components/HotContent/hotContentCommonWidget.tsx b/project/web/src/app/[lng]/hotContent/components/HotContent/hotContentCommonWidget.tsxindex 9c827ee9..f287ff27 100644--- a/project/web/src/app/[lng]/hotContent/components/HotContent/hotContentCommonWidget.tsx+++ b/project/web/src/app/[lng]/hotContent/components/HotContent/hotContentCommonWidget.tsx@@ -1,65 +1,67 @@-import styles from "@/app/[lng]/hotContent/components/HotContent/hotContent.module.scss";-import Icon from "@ant-design/icons";-import Uparrow from "@/app/[lng]/hotContent/svgs/uparrow.svg";-import { describeNumber } from "@/utils";-import { Avatar, Popover } from "antd";-import { useTransClient } from "@/app/i18n/client";+import Icon from '@ant-design/icons'+import { Avatar, Popover } from 'antd'+import styles from '@/app/[lng]/hotContent/components/HotContent/hotContent.module.scss'+import Uparrow from '@/app/[lng]/hotContent/svgs/uparrow.svg'+import { useTransClient } from '@/app/i18n/client'+import { describeNumber } from '@/utils'-export const AnaAddCall = ({+export function AnaAddCall({add,total,highlight = false,}: {- add: number;- total: number;- highlight?: boolean;-}) => {- const { t } = useTransClient("hot-content");+ add: number+ total: number+ highlight?: boolean+}) {+ const { t } = useTransClient('hot-content')return (<div- className={`${styles.anaAddCall} ${highlight ? styles["anaAddCall-highlight"] : ""}`}+ className={`${styles.anaAddCall} ${highlight ? styles['anaAddCall-highlight'] : ''}`}><div className="anaAddCall-add">- {add ? (- <>- <Icon component={Uparrow} />- {describeNumber(add)}- </>- ) : (- "-"- )}+ {add+ ? (+ <>+ <Icon component={Uparrow} />+ {describeNumber(add)}+ </>+ )+ : (+ '-'+ )}</div><div className="anaAddCall-total">- {t("total")}+ {t('total')}{describeNumber(total)}</div></div>- );-};+ )+}-export const SingleNumberCall = ({+export function SingleNumberCall({total,highlight = false,}: {- total: number;- highlight?: boolean;-}) => {+ total: number+ highlight?: boolean+}) {return (<pstyle={{- textAlign: "center",- fontSize: "var(--fs-md)",- color: highlight ? "var(--colorPrimary5)" : "#3d4242",- fontFamily: "DIN",+ textAlign: 'center',+ fontSize: 'var(--fs-md)',+ color: highlight ? 'var(--colorPrimary5)' : '#3d4242',+ fontFamily: 'DIN',fontWeight: 100,}}>{describeNumber(total)}</p>- );-};+ )+}-export const HotContentBaseInfo = ({+export function HotContentBaseInfo({cover,title,avatar,@@ -69,35 +71,38 @@ export const HotContentBaseInfo = ({onClick,coverPopoverContent,}: {- cover: string;- title: string;- avatar: string;- nickname: string;- fansCount?: number;- publishTime: string;- coverPopoverContent?: React.ReactNode;- onClick?: () => void;-}) => {- const { t } = useTransClient("hot-content");+ cover: string+ title: string+ avatar: string+ nickname: string+ fansCount?: number+ publishTime: string+ coverPopoverContent?: React.ReactNode+ onClick?: () => void+}) {+ const { t } = useTransClient('hot-content')return (<div className={styles.baseInfo}><Popover placement="right" content={coverPopoverContent}><img className="baseInfo-cover" src={cover} /></Popover><div className="baseInfo-right">- {title ? (- <div className="baseInfo-right-title" title={title}>- {title}- </div>- ) : (- <div className="baseInfo-right-noTitle">{t("noTitle")}</div>- )}+ {title+ ? (+ <div className="baseInfo-right-title" title={title}>+ {title}+ </div>+ )+ : (+ <div className="baseInfo-right-noTitle">{t('noTitle')}</div>+ )}<divclassName="baseInfo-right-author"onClick={(e) => {- e.stopPropagation();- if (onClick) onClick();+ e.stopPropagation()+ if (onClick)+ onClick()}}><Avatar@@ -108,15 +113,17 @@ export const HotContentBaseInfo = ({<p className="baseInfo-right-author-name">{nickname}</p>{fansCount && (<p className="baseInfo-right-author-fans">- {t("fans")} {describeNumber(fansCount)}+ {t('fans')}+ {' '}+ {describeNumber(fansCount)}</p>)}<p className="baseInfo-right-author-pubTime">- {t("publishTime")}+ {t('publishTime')}{publishTime}</p></div></div></div>- );-};+ )+}diff --git a/project/web/src/app/[lng]/hotContent/components/HotContent/index.tsx b/project/web/src/app/[lng]/hotContent/components/HotContent/index.tsxindex 64e596fd..792c1166 100644--- a/project/web/src/app/[lng]/hotContent/components/HotContent/index.tsx+++ b/project/web/src/app/[lng]/hotContent/components/HotContent/index.tsx@@ -1,5 +1,16 @@-import {+import type { TableProps } from 'antd'+import type {ForwardedRef,+} from 'react'+import type {+ PlatformRanking,+ RankingContent,+ RankingContentsResponse,+} from '@/api/hot'+import Icon, { QuestionCircleOutlined } from '@ant-design/icons'+import { Popover, Select, Skeleton, Spin, Table } from 'antd'+import CryptoJS from 'crypto-js'+import {forwardRef,memo,useCallback,@@ -7,41 +18,34 @@ import {useMemo,useRef,useState,-} from "react";-import { useHotContent } from "@/app/[lng]/hotContent/useHotContent";-import { useShallow } from "zustand/react/shallow";-import HotContentLabel from "@/app/[lng]/hotContent/components/HotContentLabel";-import styles from "./hotContent.module.scss";-import { Popover, Select, Skeleton, Spin, Table } from "antd";-import Icon, { QuestionCircleOutlined } from "@ant-design/icons";-import type { TableProps } from "antd";+} from 'react'+import InfiniteScroll from 'react-infinite-scroll-component'+import { useShallow } from 'zustand/react/shallow'import {platformApi,- PlatformRanking,- RankingContent,- RankingContentsResponse,-} from "@/api/hot";-import InfiniteScroll from "react-infinite-scroll-component";-import HotSvg from "../../svgs/hotContent.svg";-import ReadSvg from "./svgs/read.svg";+} from '@/api/hot'import {AnaAddCall,HotContentBaseInfo,SingleNumberCall,-} from "@/app/[lng]/hotContent/components/HotContent/hotContentCommonWidget";-import { useTransClient } from "@/app/i18n/client";-import CryptoJS from "crypto-js";-import { AccountPlatInfoMap, PlatType } from "@/app/config/platConfig";+} from '@/app/[lng]/hotContent/components/HotContent/hotContentCommonWidget'+import HotContentLabel from '@/app/[lng]/hotContent/components/HotContentLabel'+import { useHotContent } from '@/app/[lng]/hotContent/useHotContent'+import { AccountPlatInfoMap, PlatType } from '@/app/config/platConfig'+import { useTransClient } from '@/app/i18n/client'+import HotSvg from '../../svgs/hotContent.svg'+import styles from './hotContent.module.scss'+import ReadSvg from './svgs/read.svg'export interface IHotContentRef {}export interface IHotContentProps {- defaultHotContentData?: RankingContentsResponse;+ defaultHotContentData?: RankingContentsResponse}const icons = {wechat: [ReadSvg, HotSvg],-};+}const HotContent = memo(forwardRef(@@ -57,7 +61,7 @@ const HotContent = memo(twoMenuKey,setCurrentRankCategory,} = useHotContent(- useShallow((state) => ({+ useShallow(state => ({labelData: state.labelData,rankingData: state.rankingData,datesData: state.datesData,@@ -65,108 +69,109 @@ const HotContent = memo(currentRankCategory: state.currentRankCategory,setCurrentRankCategory: state.setCurrentRankCategory,})),- );- const { t } = useTransClient("hot-content");- const all = useRef<string>(t("all"));+ )+ const { t } = useTransClient('hot-content')+ const all = useRef<string>(t('all'))// 当前选中的标签- const [labelValue, setLabelValue] = useState(all.current);+ const [labelValue, setLabelValue] = useState(all.current)// 当前选中的日期- const [dateValue, setDateValue] = useState("");+ const [dateValue, setDateValue] = useState('')// 数据loading- const [loading, setLoading] = useState(false);+ const [loading, setLoading] = useState(false)// 表格数据- const [dataSource, setDataSource] = useState<RankingContent[]>([]);+ const [dataSource, setDataSource] = useState<RankingContent[]>([])// 总数- const [total, setTotal] = useState(0);- const page = useRef(0);- const [isReset, setIsReset] = useState(false);+ const [total, setTotal] = useState(0)+ const page = useRef(0)+ const [isReset, setIsReset] = useState(false)// 获取当前选中的标签、日期、榜单const selectedLabelInfo = useMemo(() => {- const platId = twoMenuKey.split("_")[1];+ const platId = twoMenuKey.split('_')[1]return {// 所有榜单allRanking: rankingData[platId] || [],// 当前选择榜单ranking: (rankingData[platId]?.find(- (v) => v.id === currentRankCategory,+ v => v.id === currentRankCategory,) ?? {}) as PlatformRanking,labelData: labelData[platId] || [],datesData: datesData[platId] || [],- };- }, [labelData, rankingData, datesData, twoMenuKey, currentRankCategory]);+ }+ }, [labelData, rankingData, datesData, twoMenuKey, currentRankCategory])// 跳转到作者主页const goAuthorPage = useCallback((data: RankingContent) => {- let authorUrl = "";+ let authorUrl = ''switch (selectedLabelInfo.ranking.platform.type) {- case "douyin":- authorUrl = `https://www.douyin.com/user/${data.secUid}`;- break;- case "xiaohongshu":- authorUrl = `https://www.xiaohongshu.com/user/profile/${data.author.id}`;- break;- case "kuaishou":- authorUrl = `https://kuaishou.cn/profile/${data.secUid}`;- break;- case "bilibili":- authorUrl = `https://space.bilibili.com/${data.mid}`;- break;- case "shipinhao":- break;+ case 'douyin':+ authorUrl = `https://www.douyin.com/user/${data.secUid}`+ break+ case 'xiaohongshu':+ authorUrl = `https://www.xiaohongshu.com/user/profile/${data.author.id}`+ break+ case 'kuaishou':+ authorUrl = `https://kuaishou.cn/profile/${data.secUid}`+ break+ case 'bilibili':+ authorUrl = `https://space.bilibili.com/${data.mid}`+ break+ case 'shipinhao':+ break}- if (authorUrl) window.open(authorUrl, "_blank");+ if (authorUrl)+ window.open(authorUrl, '_blank')},[selectedLabelInfo],- );+ )// 热门内容的平台类型转换到本地枚举const getPlatEnum = (type: string) => {switch (type) {- case "douyin":+ case 'douyin':return {plat: PlatType.Douyin,- };- case "xiaohongshu":+ }+ case 'xiaohongshu':return {plat: PlatType.Xhs,- };- case "kuaishou":+ }+ case 'kuaishou':return {plat: PlatType.KWAI,- };- case "bilibili":+ }+ case 'bilibili':return {plat: PlatType.BILIBILI,- };- case "shipinhao":+ }+ case 'shipinhao':return {plat: PlatType.WxSph,- };- case "wechat":+ }+ case 'wechat':return {plat: PlatType.WxGzh,- };+ }}- };+ }const columns = useMemo(() => {const callParamsColumnsCommon = (title: string) => {return {width: 90,title: () => {- return <p style={{ textAlign: "center" }}>{title}</p>;+ return <p style={{ textAlign: 'center' }}>{title}</p>},- };- };- const plat = selectedLabelInfo?.ranking?.platform?.type;+ }+ }+ const plat = selectedLabelInfo?.ranking?.platform?.type- const anaAddColumns: TableProps<RankingContent>["columns"] = [+ const anaAddColumns: TableProps<RankingContent>['columns'] = [...(dataSource[1]?.anaAdd?.addCollectCount? [{- ...callParamsColumnsCommon(t("collections")),+ ...callParamsColumnsCommon(t('collections')),render: (text: string, data: RankingContent) => (<AnaAddCalladd={data.anaAdd.addCollectCount!}@@ -177,7 +182,7 @@ const HotContent = memo(]: []),{- ...callParamsColumnsCommon(t("shares")),+ ...callParamsColumnsCommon(t('shares')),render: (text, data) => (<AnaAddCalladd={data.anaAdd.addShareCount}@@ -186,7 +191,7 @@ const HotContent = memo(),},{- ...callParamsColumnsCommon(t("comments")),+ ...callParamsColumnsCommon(t('comments')),render: (text, data) => (<AnaAddCalladd={data.anaAdd.addCommentCount}@@ -197,7 +202,7 @@ const HotContent = memo(...(dataSource[0]?.anaAdd?.addViewCount? [{- ...callParamsColumnsCommon(t("views")),+ ...callParamsColumnsCommon(t('views')),render: (text: string, data: RankingContent) => (<AnaAddCalladd={data.anaAdd.addViewCount!}@@ -208,19 +213,19 @@ const HotContent = memo(]: []),{- ...callParamsColumnsCommon(t("likes")),+ ...callParamsColumnsCommon(t('likes')),render: (text, data) => (<AnaAddCall- highlight={plat !== "xiaohongshu"}+ highlight={plat !== 'xiaohongshu'}add={data.anaAdd.addLikeCount}total={data.anaAdd.useLikeCount}/>),},- ...(plat === "xiaohongshu"+ ...(plat === 'xiaohongshu'? [{- ...callParamsColumnsCommon(t("engagement")),+ ...callParamsColumnsCommon(t('engagement')),render: (text: string, data: RankingContent) => (<AnaAddCallhighlight={true}@@ -231,40 +236,40 @@ const HotContent = memo(},]: []),- ];+ ]// 视频号- const wxSphColumns: TableProps<RankingContent>["columns"] = [+ const wxSphColumns: TableProps<RankingContent>['columns'] = [{- ...callParamsColumnsCommon(t("comments")),+ ...callParamsColumnsCommon(t('comments')),render: (text, data) => (<SingleNumberCall total={data.stats.commentCount} />),},{- ...callParamsColumnsCommon(t("shares")),+ ...callParamsColumnsCommon(t('shares')),render: (text, data) => (<SingleNumberCall total={data.shareCount!} />),},{- ...callParamsColumnsCommon(t("likes")),+ ...callParamsColumnsCommon(t('likes')),render: (text, data) => (<SingleNumberCall total={data.stats.likeCount} />),},{- ...callParamsColumnsCommon(t("recommend")),+ ...callParamsColumnsCommon(t('recommend')),render: (text, data) => (<SingleNumberCall total={data.stats.likeCount} />),},- ];+ ]// 微信公众号- const wxGzhColumns: TableProps<RankingContent>["columns"] = [+ const wxGzhColumns: TableProps<RankingContent>['columns'] = [...(dataSource[1]?.stats.watchCount? [{- ...callParamsColumnsCommon(t("watch")),+ ...callParamsColumnsCommon(t('watch')),render: (text: string, data: RankingContent) => (<SingleNumberCall total={data.stats.watchCount} />),@@ -274,7 +279,7 @@ const HotContent = memo(...(dataSource[1]?.stats.likeCount? [{- ...callParamsColumnsCommon(t("likes")),+ ...callParamsColumnsCommon(t('likes')),render: (text: string, data: RankingContent) => (<SingleNumberCall total={data.stats.likeCount} />),@@ -284,7 +289,7 @@ const HotContent = memo(...(dataSource[1]?.shareCount? [{- ...callParamsColumnsCommon(t("shares")),+ ...callParamsColumnsCommon(t('shares')),render: (text: string, data: RankingContent) => (<SingleNumberCall total={data.shareCount!} />),@@ -294,7 +299,7 @@ const HotContent = memo(...(dataSource[1]?.stats.viewCount? [{- ...callParamsColumnsCommon(t("views")),+ ...callParamsColumnsCommon(t('views')),render: (text: string, data: RankingContent) => (<SingleNumberCalltotal={data.stats.viewCount}@@ -304,36 +309,38 @@ const HotContent = memo(},]: []),- ];+ ]- const columns: TableProps<RankingContent>["columns"] = [+ const columns: TableProps<RankingContent>['columns'] = [{- title: t("rank"),- dataIndex: "rankingPosition",- key: "rankingPosition",+ title: t('rank'),+ dataIndex: 'rankingPosition',+ key: 'rankingPosition',width: 60,render: (text, data, ind) => (<>- {ind <= 2 ? (- <div className={styles.rankingTopthree}>{ind + 1}</div>- ) : (- <p style={{ width: "30px", textAlign: "center" }}>- {ind + 1}- </p>- )}+ {ind <= 2+ ? (+ <div className={styles.rankingTopthree}>{ind + 1}</div>+ )+ : (+ <p style={{ width: '30px', textAlign: 'center' }}>+ {ind + 1}+ </p>+ )}</>),},{- title: t("baseInfo"),- dataIndex: "baseInfo",+ title: t('baseInfo'),+ dataIndex: 'baseInfo',render: (text, data) => {const platInfo = getPlatEnum(selectedLabelInfo.ranking?.platform?.type,- );+ )const platConfig = AccountPlatInfoMap.get(platInfo?.plat ?? PlatType.Xhs,- )!;+ )!return (<HotContentBaseInfo@@ -351,19 +358,19 @@ const HotContent = memo(nickname={data.author.name}cover={data.cover}onClick={() => {- goAuthorPage(data);+ goAuthorPage(data)}}/>- );+ )},},{- title: () => <p style={{ textAlign: "center" }}>{t("category")}</p>,- dataIndex: "category",- key: "category",+ title: () => <p style={{ textAlign: 'center' }}>{t('category')}</p>,+ dataIndex: 'category',+ key: 'category',width: 120,render: (text, data) => (- <div style={{ textAlign: "center" }}>+ <div style={{ textAlign: 'center' }}><p><b>{text}</b></p>@@ -372,49 +379,50 @@ const HotContent = memo(),},- ...(plat === "shipinhao"+ ...(plat === 'shipinhao'? wxSphColumns- : plat === "wechat"+ : plat === 'wechat'? wxGzhColumns: anaAddColumns),- ];- return columns;- }, [selectedLabelInfo, dataSource, t]);+ ]+ return columns+ }, [selectedLabelInfo, dataSource, t])const getTableData = useCallback(async () => {- if (loading) return;+ if (loading)+ returnconst res = await platformApi.getRankingContents(selectedLabelInfo.ranking.id,page.current,20,- labelValue === all.current ? "全部" : labelValue,+ labelValue === all.current ? '全部' : labelValue,dateValue,- );- page.current += 1;+ )+ page.current += 1setDataSource((prevState) => {- return [...prevState, ...(res?.data.items || [])];- });- setTotal(res?.data.meta.totalItems || 0);- }, [selectedLabelInfo.ranking, labelValue, dateValue]);+ return [...prevState, ...(res?.data.items || [])]+ })+ setTotal(res?.data.meta.totalItems || 0)+ }, [selectedLabelInfo.ranking, labelValue, dateValue])// 当平台切换时,重置数据useEffect(() => {if (selectedLabelInfo.datesData.length > 0) {- setDateValue(selectedLabelInfo.datesData[0].value);- setLabelValue(all.current);- setIsReset(true);+ setDateValue(selectedLabelInfo.datesData[0].value)+ setLabelValue(all.current)+ setIsReset(true)}- }, [selectedLabelInfo.datesData, twoMenuKey]);+ }, [selectedLabelInfo.datesData, twoMenuKey])// 请求列表数据useEffect(() => {if (isReset && selectedLabelInfo.ranking?.id) {- page.current = 1;- setDataSource([]);- setLoading(true);- getTableData().then(() => setLoading(false));- setIsReset(false);+ page.current = 1+ setDataSource([])+ setLoading(true)+ getTableData().then(() => setLoading(false))+ setIsReset(false)}}, [labelValue,@@ -423,28 +431,28 @@ const HotContent = memo(selectedLabelInfo.ranking?.id,isReset,currentRankCategory,- ]);+ ])return (<div className={`${styles.hotContent}`}>{selectedLabelInfo.allRanking.length > 1 && (<div className="hotContent-rankLabel">{selectedLabelInfo.allRanking.map((v, i) => {- const icon = (icons[v.platform.type as "wechat"] ?? [])[i];+ const icon = (icons[v.platform.type as 'wechat'] ?? [])[i]return (<div- className={`hotContent-rankLabel-item ${v.id === currentRankCategory ? "hotContent-rankLabel-item--active" : ""}`}+ className={`hotContent-rankLabel-item ${v.id === currentRankCategory ? 'hotContent-rankLabel-item--active' : ''}`}key={v.id}onClick={() => {- setCurrentRankCategory(v.id);- setIsReset(true);+ setCurrentRankCategory(v.id)+ setIsReset(true)}}><Icon component={icon} />{v.name}</div>- );+ )})}</div>)}@@ -453,51 +461,59 @@ const HotContent = memo(labels={[all.current, ...(selectedLabelInfo.labelData ?? [])]}value={labelValue}onChange={(value) => {- setLabelValue(value);- setIsReset(true);+ setLabelValue(value)+ setIsReset(true)}}/><div className="hotContent-options"><div className="hotContent-options-select"><div className="hotContent-options-select-label">- {t("dailyRank")}+ {t('dailyRank')}</div><Select- options={selectedLabelInfo.datesData.map((v) => ({+ options={selectedLabelInfo.datesData.map(v => ({label: v.showDate,value: v.value,}))}value={dateValue}onChange={(e) => {- setDateValue(e);- setIsReset(true);+ setDateValue(e)+ setIsReset(true)}}- ></Select>+ >+ </Select></div><Popover- content={+ content={(<><p>- {t("updateFrequency")}:+ {t('updateFrequency')}+ :{selectedLabelInfo.ranking.updateFrequency}</p><p>- {t("statEndTime")}:{selectedLabelInfo.ranking.updateTime}+ {t('statEndTime')}+ :+ {selectedLabelInfo.ranking.updateTime}</p><p>- {t("updateFrequency")}:{t("daily")}+ {t('updateFrequency')}+ :+ {t('daily')}</p><p>- {t("sortRule")}:{t("sortRuleDesc")}+ {t('sortRule')}+ :+ {t('sortRuleDesc')}</p></>- }+ )}placement="bottomLeft"><div className="hotContent-options-explain">- {t("dataDescription")}+ {t('dataDescription')}<QuestionCircleOutlined /></div></Popover>@@ -505,7 +521,7 @@ const HotContent = memo(<Spin spinning={loading}><div- className={`${styles["hotContent-table"]} hotContent--${selectedLabelInfo?.ranking?.platform?.type}`}+ className={`${styles['hotContent-table']} hotContent--${selectedLabelInfo?.ranking?.platform?.type}`}id="hotContent-table"><InfiniteScroll@@ -520,24 +536,24 @@ const HotContent = memo(><TabledataSource={defaultHotContentData?.items ?? dataSource}- rowKey={(record) => record.id}+ rowKey={record => record.id}columns={columns}pagination={false}onRow={(record) => {return {onClick: async () => {if (- selectedLabelInfo.ranking.platform.type === "wechat"+ selectedLabelInfo.ranking.platform.type === 'wechat') {- setLoading(true);+ setLoading(true)const res = await platformApi.getDetailUrl(record.photoId,- );- setLoading(false);+ )+ setLoading(false)- const key =- CryptoJS.enc.Utf8.parse("cdxbxhs147258369");- const encrypted = res?.data ?? "";+ const key+ = CryptoJS.enc.Utf8.parse('cdxbxhs147258369')+ const encrypted = res?.data ?? ''const decrypted = CryptoJS.AES.decrypt(encrypted,@@ -546,25 +562,26 @@ const HotContent = memo(mode: CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7,},- );- const result = CryptoJS.enc.Utf8.stringify(decrypted);- window.open(result, "_blank");- return;+ )+ const result = CryptoJS.enc.Utf8.stringify(decrypted)+ window.open(result, '_blank')+ return}- if (!record.url) return;- window.open(record.url, "_blank");+ if (!record.url)+ return+ window.open(record.url, '_blank')},- };+ }}}/></InfiniteScroll></div></Spin></div>- );+ )},),-);+)-export default HotContent;+export default HotContentdiff --git a/project/web/src/app/[lng]/hotContent/components/HotContentLabel/index.tsx b/project/web/src/app/[lng]/hotContent/components/HotContentLabel/index.tsxindex fae79270..1827bfb3 100644--- a/project/web/src/app/[lng]/hotContent/components/HotContentLabel/index.tsx+++ b/project/web/src/app/[lng]/hotContent/components/HotContentLabel/index.tsx@@ -1,23 +1,25 @@-import {+import type {+ CSSProperties,ForwardedRef,+} from 'react'+import {forwardRef,memo,+ useLayoutEffect,useRef,useState,- useLayoutEffect,- CSSProperties,-} from "react";-import styles from "./hotContentLabel.module.scss";-import { useTransClient } from "@/app/i18n/client";+} from 'react'+import { useTransClient } from '@/app/i18n/client'+import styles from './hotContentLabel.module.scss'export interface IHotContentLabelRef {}export interface IHotContentLabelProps {- labels: string[];- icons?: string[];- value: string;- onChange: (label: string) => void;- style?: CSSProperties;+ labels: string[]+ icons?: string[]+ value: string+ onChange: (label: string) => void+ style?: CSSProperties}const HotContentLabel = memo(@@ -26,25 +28,25 @@ const HotContentLabel = memo({ labels, value, onChange, style, icons }: IHotContentLabelProps,ref: ForwardedRef<IHotContentLabelRef>,) => {- const listRef = useRef<HTMLUListElement>(null);- const [expanded, setExpanded] = useState(false);- const [showToggle, setShowToggle] = useState(false);- const [collapsedHeight, setCollapsedHeight] = useState(0);- const [fullHeight, setFullHeight] = useState(0);- const { t } = useTransClient("hot-content");+ const listRef = useRef<HTMLUListElement>(null)+ const [expanded, setExpanded] = useState(false)+ const [showToggle, setShowToggle] = useState(false)+ const [collapsedHeight, setCollapsedHeight] = useState(0)+ const [fullHeight, setFullHeight] = useState(0)+ const { t } = useTransClient('hot-content')useLayoutEffect(() => {- const ul = listRef.current;+ const ul = listRef.currentif (ul) {- const firstLi = ul.querySelector("li");+ const firstLi = ul.querySelector('li')if (firstLi) {- const lineHeight = firstLi.getBoundingClientRect().height;- setCollapsedHeight(lineHeight);- setFullHeight(ul.scrollHeight);- setShowToggle(ul.scrollHeight > lineHeight + 2);+ const lineHeight = firstLi.getBoundingClientRect().height+ setCollapsedHeight(lineHeight)+ setFullHeight(ul.scrollHeight)+ setShowToggle(ul.scrollHeight > lineHeight + 2)}}- }, [labels]);+ }, [labels])return (<div className={styles.hotContentLabelWrapper} style={style}>@@ -53,15 +55,15 @@ const HotContentLabel = memo(ref={listRef}style={{maxHeight: expanded ? fullHeight : collapsedHeight,- overflow: "hidden",- transition: "max-height 0.3s cubic-bezier(0.4,0,0.2,1)",+ overflow: 'hidden',+ transition: 'max-height 0.3s cubic-bezier(0.4,0,0.2,1)',}}>{labels.map((label, i) => (<likey={label}className={`hotContentLabel-item ${- label === value ? "hotContentLabel-item--active" : ""+ label === value ? 'hotContentLabel-item--active' : ''}`}title={label}onClick={() => onChange(label)}@@ -81,17 +83,17 @@ const HotContentLabel = memo(<aclassName="hotContentLabel-toggle"onClick={(e) => {- e.preventDefault();- setExpanded((v) => !v);+ e.preventDefault()+ setExpanded(v => !v)}}>- {expanded ? t("collapse") : t("expand")}+ {expanded ? t('collapse') : t('expand')}</a>)}</div>- );+ )},),-);+)-export default HotContentLabel;+export default HotContentLabeldiff --git a/project/web/src/app/[lng]/hotContent/components/HotContentSidebar/hotContentSidebar.module.scss b/project/web/src/app/[lng]/hotContent/components/HotContentSidebar/hotContentSidebar.module.scssindex 7b9eaa5a..1684da91 100644--- a/project/web/src/app/[lng]/hotContent/components/HotContentSidebar/hotContentSidebar.module.scss+++ b/project/web/src/app/[lng]/hotContent/components/HotContentSidebar/hotContentSidebar.module.scss@@ -5,4 +5,4 @@height: 100%;}}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/hotContent/components/HotContentSidebar/index.tsx b/project/web/src/app/[lng]/hotContent/components/HotContentSidebar/index.tsxindex 5f4f70e3..8c62e11a 100644--- a/project/web/src/app/[lng]/hotContent/components/HotContentSidebar/index.tsx+++ b/project/web/src/app/[lng]/hotContent/components/HotContentSidebar/index.tsx@@ -1,25 +1,26 @@-import { ForwardedRef, forwardRef, memo, useEffect, useMemo } from "react";-import styles from "./hotContentSidebar.module.scss";-import React from "react";-import Icon from "@ant-design/icons";-import { Menu } from "antd";-import type { GetProp, MenuProps } from "antd";-import HotContentSvg from "../../svgs/hotContent.svg";-import HotEventSvg from "../../svgs/hotEvent.svg";-import HotFeaturesSvg from "../../svgs/hotFeatures.svg";-import HotTitleSvg from "../../svgs/hotTitle.svg";-import { HotType } from "@/app/[lng]/hotContent/hotContent.enum";-import { useShallow } from "zustand/react/shallow";-import { useHotContent } from "@/app/[lng]/hotContent/useHotContent";-import { useTransClient } from "@/app/i18n/client";+import type { GetProp, MenuProps } from 'antd'+import type { ForwardedRef } from 'react'+import Icon from '@ant-design/icons'+import { Menu } from 'antd'+import React, { forwardRef, memo, useEffect, useMemo } from 'react'-type MenuItem = GetProp<MenuProps, "items">[number];+import { useShallow } from 'zustand/react/shallow'+import { HotType } from '@/app/[lng]/hotContent/hotContent.enum'+import { useHotContent } from '@/app/[lng]/hotContent/useHotContent'+import { useTransClient } from '@/app/i18n/client'+import HotContentSvg from '../../svgs/hotContent.svg'+import HotEventSvg from '../../svgs/hotEvent.svg'+import HotFeaturesSvg from '../../svgs/hotFeatures.svg'+import HotTitleSvg from '../../svgs/hotTitle.svg'+import styles from './hotContentSidebar.module.scss'++type MenuItem = GetProp<MenuProps, 'items'>[number]export interface IHotContentSidebarRef {}export interface IHotContentSidebarProps {}-const yikaOss = process.env.NEXT_PUBLIC_YIKA_OSS_HOST;+const yikaOss = process.env.NEXT_PUBLIC_YIKA_OSS_HOSTconst HotContentSidebar = memo(forwardRef(@@ -34,7 +35,7 @@ const HotContentSidebar = memo(hotTitlePlatformList,changeHotContentPlatform,} = useHotContent(- useShallow((state) => ({+ useShallow(state => ({setHotType: state.setHotType,hotType: state.hotType,hotContentPlatformList: state.hotContentPlatformList,@@ -44,22 +45,22 @@ const HotContentSidebar = memo(hotTitlePlatformList: state.hotTitlePlatformList,changeHotContentPlatform: state.changeHotContentPlatform,})),- );- const { t } = useTransClient("hot-content");+ )+ const { t } = useTransClient('hot-content')const items = useMemo(() => {const items: MenuItem[] = [{key: HotType.hotContent,icon: <Icon component={HotContentSvg} />,- label: <b>{t("hotContent")}</b>,- children: hotContentPlatformList.map((platform) => ({+ label: <b>{t('hotContent')}</b>,+ children: hotContentPlatformList.map(platform => ({key: `${HotType.hotContent}_${platform.id}`,label: platform.name,icon: (<imgsrc={`${yikaOss}/${platform.icon}`}- style={{ width: "18px" }}+ style={{ width: '18px' }}/>),})),@@ -67,53 +68,53 @@ const HotContentSidebar = memo({key: HotType.hotEvent,icon: <Icon component={HotEventSvg} />,- label: <b>{t("hotEvents")}</b>,+ label: <b>{t('hotEvents')}</b>,},{key: HotType.hotFeatures,icon: <Icon component={HotFeaturesSvg} />,- label: <b>{t("hotTopics")}</b>,+ label: <b>{t('hotTopics')}</b>,children: [{- key: "AIGC",- label: "AIGC",+ key: 'AIGC',+ label: 'AIGC',},{- key: "短剧",- label: t("shortDrama"),+ key: '短剧',+ label: t('shortDrama'),},{- key: "文旅",- label: t("cultureTourism"),+ key: '文旅',+ label: t('cultureTourism'),},{- key: "内容出海",- label: t("contentOverseas"),+ key: '内容出海',+ label: t('contentOverseas'),},],},{key: HotType.hotTitle,icon: <Icon component={HotTitleSvg} />,- label: <b>{t("viralTitles")}</b>,- children: hotTitlePlatformList.map((platform) => ({+ label: <b>{t('viralTitles')}</b>,+ children: hotTitlePlatformList.map(platform => ({key: `${HotType.hotTitle}_${platform.id}`,label: platform.name,icon: (<imgsrc={`${yikaOss}/${platform.icon}`}- style={{ width: "18px" }}+ style={{ width: '18px' }}/>),})),},- ];- return items;- }, [hotContentPlatformList, hotTitlePlatformList, t]);+ ]+ return items+ }, [hotContentPlatformList, hotTitlePlatformList, t])useEffect(() => {- init();- }, [init]);+ init()+ }, [init])return (<div className={styles.hotContentSidebar}>@@ -128,24 +129,25 @@ const HotContentSidebar = memo(]}selectedKeys={twoMenuKey ? [twoMenuKey, hotType] : [hotType]}onClick={(e) => {- const hotType = e["keyPath"][e["keyPath"].length - 1] as HotType;+ const hotType = e.keyPath[e.keyPath.length - 1] as HotType// 热门内容分类设置- setHotType(hotType);+ setHotType(hotType)switch (hotType) {case HotType.hotContent:- changeHotContentPlatform(e.key);- break;+ changeHotContentPlatform(e.key)+ breakcase HotType.hotTitle:- changeHotContentPlatform(e.key);- break;+ changeHotContentPlatform(e.key)+ break}if (e.keyPath.length === 2) {// 侧边栏二级菜单选择- setTwoMenuKey(e.key);- } else {- setTwoMenuKey("");+ setTwoMenuKey(e.key)+ }+ else {+ setTwoMenuKey('')}}}items={items}@@ -153,9 +155,9 @@ const HotContentSidebar = memo(inlineIndent={10}/></div>- );+ )},),-);+)-export default HotContentSidebar;+export default HotContentSidebardiff --git a/project/web/src/app/[lng]/hotContent/components/HotEvent/echart/drawHotEventEchartLine.ts b/project/web/src/app/[lng]/hotContent/components/HotEvent/echart/drawHotEventEchartLine.tsindex 62942344..fcefd7c2 100644--- a/project/web/src/app/[lng]/hotContent/components/HotEvent/echart/drawHotEventEchartLine.ts+++ b/project/web/src/app/[lng]/hotContent/components/HotEvent/echart/drawHotEventEchartLine.ts@@ -1,29 +1,31 @@-import * as echarts from "echarts";-import { HotValueHistory } from "@/api/types/hotTopic";-import { describeNumber } from "@/utils";-import { directTrans } from "@/app/i18n/client";+import type { HotValueHistory } from '@/api/types/hotTopic'+import * as echarts from 'echarts'+import { directTrans } from '@/app/i18n/client'+import { describeNumber } from '@/utils'-type EChartsOption = echarts.EChartsOption;+type EChartsOption = echarts.EChartsOptionexport default function drawHotEventEchartLine(elId: string,data: HotValueHistory[],) {- if (!data || data.length === 0) return;+ if (!data || data.length === 0)+ return- const chartDom = document.getElementById(elId)!;- if (!chartDom) return;+ const chartDom = document.getElementById(elId)!+ if (!chartDom)+ returnif (echarts.getInstanceByDom(chartDom)) {- echarts.dispose(chartDom);+ echarts.dispose(chartDom)}- const myChart = echarts.init(chartDom);+ const myChart = echarts.init(chartDom)// 只有一个点时,设置上下各留 50% 空间- let yMin, yMax;+ let yMin, yMaxif (data.length === 1) {- const v = data[0].hotValue;- yMin = v * 0.5;- yMax = v * 1.5;+ const v = data[0].hotValue+ yMin = v * 0.5+ yMax = v * 1.5}// 处理每个点的颜色@@ -31,46 +33,46 @@ export default function drawHotEventEchartLine(if (item.hotValue === null || item.hotValue === undefined) {return {value: null,- itemStyle: { color: "#a66ae4" },- };+ itemStyle: { color: '#a66ae4' },+ }}- return item.hotValue;- });+ return item.hotValue+ })const option: EChartsOption = {grid: { left: 0, right: 0, top: 0, bottom: 0, containLabel: false },tooltip: {- appendTo: "body",- trigger: "axis",+ appendTo: 'body',+ trigger: 'axis',show: true,formatter: (params: any) => {- const item = params[0];- return `${item.axisValue}<br/>${directTrans("hot-content", "hotValue")}: ${describeNumber(item.data)}`;+ const item = params[0]+ return `${item.axisValue}<br/>${directTrans('hot-content', 'hotValue')}: ${describeNumber(item.data)}`},},xAxis: {- type: "category",- data: data.map((item) => item.updateTime),+ type: 'category',+ data: data.map(item => item.updateTime),show: false,boundaryGap: false,},yAxis: {- type: "value",+ type: 'value',show: false,min: yMin,max: yMax,},series: [{- type: "line",+ type: 'line',data: seriesData,smooth: true,- symbol: data.length === 1 ? "circle" : "none",+ symbol: data.length === 1 ? 'circle' : 'none',symbolSize: 6,- lineStyle: { width: 2, color: "#a66ae4" },+ lineStyle: { width: 2, color: '#a66ae4' },},],- };+ }- myChart.setOption(option);+ myChart.setOption(option)}diff --git a/project/web/src/app/[lng]/hotContent/components/HotEvent/hotEvent.module.scss b/project/web/src/app/[lng]/hotContent/components/HotEvent/hotEvent.module.scssindex 1cdfedf7..f8cb7436 100644--- a/project/web/src/app/[lng]/hotContent/components/HotEvent/hotEvent.module.scss+++ b/project/web/src/app/[lng]/hotContent/components/HotEvent/hotEvent.module.scss@@ -66,7 +66,8 @@display: flex;align-items: center;:global {- .rankingTopthree-rise, .rankingTopthree-fall {+ .rankingTopthree-rise,+ .rankingTopthree-fall {position: absolute;display: flex;align-items: center;@@ -92,4 +93,4 @@}}}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/hotContent/components/HotEvent/index.tsx b/project/web/src/app/[lng]/hotContent/components/HotEvent/index.tsxindex b482585d..9324f8b1 100644--- a/project/web/src/app/[lng]/hotContent/components/HotEvent/index.tsx+++ b/project/web/src/app/[lng]/hotContent/components/HotEvent/index.tsx@@ -1,173 +1,184 @@-import {+import type { TableProps } from 'antd'+import type {ForwardedRef,+} from 'react'+import type { Platform } from '@/api/hot'+import type { HotTopic, HotValueHistory } from '@/api/types/hotTopic'+import Icon from '@ant-design/icons'+import { Spin, Table } from 'antd'+import {forwardRef,memo,useCallback,useEffect,useState,-} from "react";-import styles from "./hotEvent.module.scss";-import { Platform, platformApi } from "@/api/hot";-import { HotTopic, HotValueHistory } from "@/api/types/hotTopic";-import KwaiSvg from "./svgs/kwai.svg";-import XhsSvg from "./svgs/xhs.svg";-import BaiduSvg from "./svgs/baidu.svg";-import DouyinSvg from "./svgs/douyin.svg";-import TaotiaoSvg from "./svgs/totiao.svg";-import WeiboSvg from "./svgs/weibo.svg";-import ZhihuSvg from "./svgs/zhihu.svg";-import BiblSvg from "./svgs/bibl.svg";-import Icon from "@ant-design/icons";-import { Spin, Table, type TableProps } from "antd";-import { describeNumber } from "@/utils";-import hotContentStyles from "../HotContent/hotContent.module.scss";-import drawHotEventEchartLine from "@/app/[lng]/hotContent/components/HotEvent/echart/drawHotEventEchartLine";-import Uparrow from "../../svgs/uparrow.svg";-import { useTransClient } from "@/app/i18n/client"; // 新增+} from 'react'+import { platformApi } from '@/api/hot'+import drawHotEventEchartLine from '@/app/[lng]/hotContent/components/HotEvent/echart/drawHotEventEchartLine'+import { useTransClient } from '@/app/i18n/client' // 新增+import { describeNumber } from '@/utils'+import Uparrow from '../../svgs/uparrow.svg'+import hotContentStyles from '../HotContent/hotContent.module.scss'+import styles from './hotEvent.module.scss'+import BaiduSvg from './svgs/baidu.svg'+import BiblSvg from './svgs/bibl.svg'+import DouyinSvg from './svgs/douyin.svg'+import KwaiSvg from './svgs/kwai.svg'+import TaotiaoSvg from './svgs/totiao.svg'+import WeiboSvg from './svgs/weibo.svg'+import XhsSvg from './svgs/xhs.svg'+import ZhihuSvg from './svgs/zhihu.svg'const material = [{icon: XhsSvg,- back: "linear-gradient(127deg, rgba(255, 38, 82, 0.1) 0%, rgba(255, 126, 140, 0.1) 100%)",+ back: 'linear-gradient(127deg, rgba(255, 38, 82, 0.1) 0%, rgba(255, 126, 140, 0.1) 100%)',},{icon: DouyinSvg,- back: "linear-gradient(127deg, rgba(90, 246, 242, 0.1) 0%, rgba(254, 44, 85, 0.1) 100%)",+ back: 'linear-gradient(127deg, rgba(90, 246, 242, 0.1) 0%, rgba(254, 44, 85, 0.1) 100%)',},{icon: KwaiSvg,- back: "linear-gradient(127deg, rgba(255, 121, 2, 0.1) 0%, rgba(255, 216, 181, 0.1) 100%)",+ back: 'linear-gradient(127deg, rgba(255, 121, 2, 0.1) 0%, rgba(255, 216, 181, 0.1) 100%)',},{icon: BiblSvg,- back: "linear-gradient(127deg, rgba(90, 246, 242, 0.1) 0%, rgba(254, 44, 85, 0.1) 100%)",+ back: 'linear-gradient(127deg, rgba(90, 246, 242, 0.1) 0%, rgba(254, 44, 85, 0.1) 100%)',},{icon: WeiboSvg,- back: "linear-gradient(127deg, rgba(90, 246, 242, 0.1) 0%, rgba(254, 44, 85, 0.1) 100%)",+ back: 'linear-gradient(127deg, rgba(90, 246, 242, 0.1) 0%, rgba(254, 44, 85, 0.1) 100%)',},{icon: BaiduSvg,- back: "linear-gradient(127deg, rgba(255, 121, 35, 0.1) 0%, rgba(255, 72, 20, 0.1) 100%)",+ back: 'linear-gradient(127deg, rgba(255, 121, 35, 0.1) 0%, rgba(255, 72, 20, 0.1) 100%)',},{icon: TaotiaoSvg,- back: "linear-gradient(127deg, rgba(90, 246, 242, 0.1) 0%, rgba(254, 44, 85, 0.1) 100%)",+ back: 'linear-gradient(127deg, rgba(90, 246, 242, 0.1) 0%, rgba(254, 44, 85, 0.1) 100%)',},{icon: ZhihuSvg,- back: "linear-gradient(127deg, rgba(90, 246, 242, 0.1) 0%, rgba(254, 44, 85, 0.1) 100%)",+ back: 'linear-gradient(127deg, rgba(90, 246, 242, 0.1) 0%, rgba(254, 44, 85, 0.1) 100%)',},-];+]export interface IHotEventRef {}export interface IHotEventProps {}-const HotTrendLine: React.FC<{ id: string; data: HotValueHistory[] }> = ({+const HotTrendLine: React.FC<{ id: string, data: HotValueHistory[] }> = ({id,data,}) => {useEffect(() => {- drawHotEventEchartLine(id, data);- }, [id, data]);+ drawHotEventEchartLine(id, data)+ }, [id, data])- return <div id={id} style={{ width: "180px", height: "25px" }}></div>;-};+ return <div id={id} style={{ width: '180px', height: '25px' }}></div>+}const HotEvent = memo(forwardRef(({}: IHotEventProps, ref: ForwardedRef<IHotEventRef>) => {const [data, setData] = useState<{- platform: Platform;- topics: HotTopic[];+ platform: Platform+ topics: HotTopic[]}[]- >([]);- const [loading, setLoading] = useState(false);- const { t } = useTransClient("hot-content"); // 新增+ >([])+ const [loading, setLoading] = useState(false)+ const { t } = useTransClient('hot-content') // 新增const getData = useCallback(async () => {- setLoading(true);- const res = await platformApi.getAllHotTopics();- setLoading(false);- setData(res?.data ?? []);- }, []);+ setLoading(true)+ const res = await platformApi.getAllHotTopics()+ setLoading(false)+ setData(res?.data ?? [])+ }, [])useEffect(() => {- getData();- }, []);+ getData()+ }, [])const getColumns = useCallback((hotTopic: HotTopic[]) => {- const columns: TableProps<HotTopic>["columns"] = [+ const columns: TableProps<HotTopic>['columns'] = [{- title: t("rank"),+ title: t('rank'),width: 60,render: (text, data, ind) => (<div className={styles.ranking}>- {ind <= 2 ? (- <div- className={hotContentStyles.rankingTopthree}- style={{- width: "20px",- height: "20px",- lineHeight: "20px",- }}- >- {ind + 1}- </div>- ) : (- <p style={{ width: "20px", textAlign: "center" }}>- {ind + 1}- </p>- )}+ {ind <= 2+ ? (+ <div+ className={hotContentStyles.rankingTopthree}+ style={{+ width: '20px',+ height: '20px',+ lineHeight: '20px',+ }}+ >+ {ind + 1}+ </div>+ )+ : (+ <p style={{ width: '20px', textAlign: 'center' }}>+ {ind + 1}+ </p>+ )}- {!data.rankChange ? null : data.rankChange > 0 ? (- <p className="rankingTopthree-rise">- <Icon component={Uparrow} />- <span className="rankingTopthree-name">- {data.rankChange}- </span>- </p>- ) : (- <p className="rankingTopthree-fall">- <Icon component={Uparrow} />- <span className="rankingTopthree-name">- {Math.abs(data.rankChange)}- </span>- </p>- )}+ {!data.rankChange+ ? null+ : data.rankChange > 0+ ? (+ <p className="rankingTopthree-rise">+ <Icon component={Uparrow} />+ <span className="rankingTopthree-name">+ {data.rankChange}+ </span>+ </p>+ )+ : (+ <p className="rankingTopthree-fall">+ <Icon component={Uparrow} />+ <span className="rankingTopthree-name">+ {Math.abs(data.rankChange)}+ </span>+ </p>+ )}</div>),},{- title: t("hotEvents"),+ title: t('hotEvents'),render: (text, record) => {return (<spanclassName={styles.hotEventTitle}title={record.title}onClick={() => {- if (!record.url) return;- window.open(record.url, "_blank");+ if (!record.url)+ return+ window.open(record.url, '_blank')}}>{record.title}</span>- );+ )},},{width: 120,- title: t("hotValue"),- align: "center",+ title: t('hotValue'),+ align: 'center',render: (text, record) => {return (- <span style={{ fontFamily: "DIN" }}>+ <span style={{ fontFamily: 'DIN' }}>{describeNumber(record.hotValue)}</span>- );+ )},},@@ -175,7 +186,7 @@ const HotEvent = memo(? [{width: 200,- title: t("hotTrend"),+ title: t('hotTrend'),render: (text: string, record: HotTopic) => (<HotTrendLineid={record._id}@@ -185,14 +196,14 @@ const HotEvent = memo(},]: []),- ];- return columns;+ ]+ return columns},[t],- );+ )return (- <Spin spinning={loading} style={{ minHeight: "60vh" }}>+ <Spin spinning={loading} style={{ minHeight: '60vh' }}><div className={styles.hotEvent}>{data.map(({ platform, topics }, i) => {return (@@ -201,25 +212,30 @@ const HotEvent = memo(className="hotEvent-item-head"style={{ background: material[i].back }}>- <Icon component={material[i].icon} /> {platform.name} ·{" "}- {t("hot")}+ <Icon component={material[i].icon} />+ {' '}+ {platform.name}+ {' '}+ ·+ {' '}+ {t('hot')}</div>- <div className={styles["hotEvent-item-content"]}>+ <div className={styles['hotEvent-item-content']}><TabledataSource={topics}columns={getColumns(topics)}- rowKey={(record) => record._id}+ rowKey={record => record._id}pagination={false}scroll={{ y: 400 }}/></div></div>- );+ )})}</div></Spin>- );+ )}),-);+)-export default HotEvent;+export default HotEventdiff --git a/project/web/src/app/[lng]/hotContent/components/HotFeatures/hotFeatures.module.scss b/project/web/src/app/[lng]/hotContent/components/HotFeatures/hotFeatures.module.scssindex 8c19a2aa..c404f474 100644--- a/project/web/src/app/[lng]/hotContent/components/HotFeatures/hotFeatures.module.scss+++ b/project/web/src/app/[lng]/hotContent/components/HotFeatures/hotFeatures.module.scss@@ -3,11 +3,13 @@display: flex;flex-direction: column;:global {- .ant-spin-nested-loading, .hotFeatures-content, .ant-spin-container {+ .ant-spin-nested-loading,+ .hotFeatures-content,+ .ant-spin-container {height: 100%;display: flex;flex-direction: column;min-height: 0;}}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/hotContent/components/HotFeatures/index.tsx b/project/web/src/app/[lng]/hotContent/components/HotFeatures/index.tsxindex 105ba9f8..3f7d72f9 100644--- a/project/web/src/app/[lng]/hotContent/components/HotFeatures/index.tsx+++ b/project/web/src/app/[lng]/hotContent/components/HotFeatures/index.tsx@@ -1,5 +1,10 @@-import {+import type { TableProps } from 'antd'+import type {ForwardedRef,+} from 'react'+import type { Topic } from '@/api/types/topic'+import { Skeleton, Spin, Table } from 'antd'+import {forwardRef,memo,useCallback,@@ -7,86 +12,86 @@ import {useMemo,useRef,useState,-} from "react";-import styles from "./hotFeatures.module.scss";-import HotContentLabel from "@/app/[lng]/hotContent/components/HotContentLabel";-import { useHotContent } from "@/app/[lng]/hotContent/useHotContent";-import { useShallow } from "zustand/react/shallow";-import { Skeleton, Spin, Table, type TableProps } from "antd";-import InfiniteScroll from "react-infinite-scroll-component";-import { Topic } from "@/api/types/topic";-import { platformApi } from "@/api/hot";-import hotContentStyles from "../HotContent/hotContent.module.scss";+} from 'react'+import InfiniteScroll from 'react-infinite-scroll-component'+import { useShallow } from 'zustand/react/shallow'+import { platformApi } from '@/api/hot'import {HotContentBaseInfo,SingleNumberCall,-} from "@/app/[lng]/hotContent/components/HotContent/hotContentCommonWidget";-import { useTransClient } from "@/app/i18n/client"; // 新增+} from '@/app/[lng]/hotContent/components/HotContent/hotContentCommonWidget'+import HotContentLabel from '@/app/[lng]/hotContent/components/HotContentLabel'+import { useHotContent } from '@/app/[lng]/hotContent/useHotContent'+import { useTransClient } from '@/app/i18n/client' // 新增+import hotContentStyles from '../HotContent/hotContent.module.scss'+import styles from './hotFeatures.module.scss'export interface IHotFeaturesRef {}export interface IHotFeaturesProps {}-const NEXT_PUBLIC_YIKA_OSS_HOST = process.env.NEXT_PUBLIC_YIKA_OSS_HOST;+const NEXT_PUBLIC_YIKA_OSS_HOST = process.env.NEXT_PUBLIC_YIKA_OSS_HOSTconst HotFeatures = memo(forwardRef(({}: IHotFeaturesProps, ref: ForwardedRef<IHotFeaturesRef>) => {const { hotContentPlatformList, twoMenuKey } = useHotContent(- useShallow((state) => ({+ useShallow(state => ({hotContentPlatformList: state.hotContentPlatformList,twoMenuKey: state.twoMenuKey,})),- );- const { t } = useTransClient("hot-content"); // 新增+ )+ const { t } = useTransClient('hot-content') // 新增const allDates = useRef<string[]>([- t("last3days"),- t("last7days"),- t("last15days"),- t("last30days"),- ]);+ t('last3days'),+ t('last7days'),+ t('last15days'),+ t('last30days'),+ ])// 当前选择的日期范围- const [currDate, setCurrDate] = useState(allDates.current[1]);+ const [currDate, setCurrDate] = useState(allDates.current[1])// 当前选择的平台- const [currPlat, setCurrPlat] = useState("");- const [loading, setLoading] = useState(false);- const [total, setTotal] = useState(0);- const page = useRef(1);- const [isReset, setIsReset] = useState(true);- const [dataSource, setDataSource] = useState<Topic[]>([]);+ const [currPlat, setCurrPlat] = useState('')+ const [loading, setLoading] = useState(false)+ const [total, setTotal] = useState(0)+ const page = useRef(1)+ const [isReset, setIsReset] = useState(true)+ const [dataSource, setDataSource] = useState<Topic[]>([])useEffect(() => {- setCurrPlat(hotContentPlatformList[0]?.name || "");- }, [hotContentPlatformList]);+ setCurrPlat(hotContentPlatformList[0]?.name || '')+ }, [hotContentPlatformList])const columns = useMemo(() => {const callParamsColumnsCommon = (title: string) => {return {width: 90,title: () => {- return <p style={{ textAlign: "center" }}>{title}</p>;+ return <p style={{ textAlign: 'center' }}>{title}</p>},- };- };+ }+ }- const columns: TableProps<Topic>["columns"] = [+ const columns: TableProps<Topic>['columns'] = [{- title: t("rank"),+ title: t('rank'),width: 60,render: (text, data, ind) => (<>- {ind <= 2 ? (- <div className={hotContentStyles.rankingTopthree}>- {ind + 1}- </div>- ) : (- <p style={{ width: "30px", textAlign: "center" }}>{ind + 1}</p>- )}+ {ind <= 2+ ? (+ <div className={hotContentStyles.rankingTopthree}>+ {ind + 1}+ </div>+ )+ : (+ <p style={{ width: '30px', textAlign: 'center' }}>{ind + 1}</p>+ )}</>),},{- title: t("baseInfo"),- dataIndex: "baseInfo",+ title: t('baseInfo'),+ dataIndex: 'baseInfo',render: (text, data) => {return (<HotContentBaseInfo@@ -97,19 +102,19 @@ const HotFeatures = memo(nickname={data.author!}cover={data.cover}onClick={() => {- window.open(data.authorUrl, "_blank");+ window.open(data.authorUrl, '_blank')}}/>- );+ )},},{- title: () => <p style={{ textAlign: "center" }}>{t("category")}</p>,- dataIndex: "category",- key: "category",+ title: () => <p style={{ textAlign: 'center' }}>{t('category')}</p>,+ dataIndex: 'category',+ key: 'category',width: 120,render: (text, data) => (- <div style={{ textAlign: "center" }}>+ <div style={{ textAlign: 'center' }}><p><b>{text}</b></p>@@ -121,7 +126,7 @@ const HotFeatures = memo(...(dataSource[1]?.shareCount? [{- ...callParamsColumnsCommon(t("shares")),+ ...callParamsColumnsCommon(t('shares')),render: (text: any, data: Topic) => (<SingleNumberCall total={data.shareCount} />),@@ -131,7 +136,7 @@ const HotFeatures = memo(...(dataSource[1]?.likeCount? [{- ...callParamsColumnsCommon(t("likes")),+ ...callParamsColumnsCommon(t('likes')),render: (text: any, data: Topic) => (<SingleNumberCall total={data.likeCount} />),@@ -141,7 +146,7 @@ const HotFeatures = memo(...(dataSource[1]?.commentCount? [{- ...callParamsColumnsCommon(t("comments")),+ ...callParamsColumnsCommon(t('comments')),render: (text: any, data: Topic) => (<SingleNumberCall total={data.commentCount} />),@@ -151,7 +156,7 @@ const HotFeatures = memo(...(dataSource[1]?.collectCount? [{- ...callParamsColumnsCommon(t("collections")),+ ...callParamsColumnsCommon(t('collections')),render: (text: any, data: Topic) => (<SingleNumberCalltotal={data.collectCount}@@ -164,86 +169,87 @@ const HotFeatures = memo(...(dataSource[1]?.readCount? [{- ...callParamsColumnsCommon(t("views")),+ ...callParamsColumnsCommon(t('views')),render: (text: any, data: Topic) => (<SingleNumberCall total={data.readCount} highlight={true} />),},]: []),- ];+ ]- return columns;- }, [dataSource, t]);+ return columns+ }, [dataSource, t])// 获取数据const getTableData = useCallback(async () => {- if (loading) return;+ if (loading)+ returnconst res = await platformApi.getAllTopics({page: page.current,pageSize: 20,- platformId: hotContentPlatformList.find((v) => v.name === currPlat)?.id,+ platformId: hotContentPlatformList.find(v => v.name === currPlat)?.id,timeType:- currDate === t("last3days")- ? "近3天"- : currDate === t("last7days")- ? "近7天"- : currDate === t("last15days")- ? "近15天"- : currDate === t("last30days")- ? "近30天"- : "",+ currDate === t('last3days')+ ? '近3天'+ : currDate === t('last7days')+ ? '近7天'+ : currDate === t('last15days')+ ? '近15天'+ : currDate === t('last30days')+ ? '近30天'+ : '',msgType: twoMenuKey,- });- page.current = page.current + 1;- setTotal(res?.data.meta.totalItems || 0);+ })+ page.current = page.current + 1+ setTotal(res?.data.meta.totalItems || 0)setDataSource((prevState) => {- return [...prevState, ...(res?.data.items || [])];- });- }, [currDate, currPlat, hotContentPlatformList, loading, twoMenuKey]);+ return [...prevState, ...(res?.data.items || [])]+ })+ }, [currDate, currPlat, hotContentPlatformList, loading, twoMenuKey])useEffect(() => {- setIsReset(true);- }, [twoMenuKey]);+ setIsReset(true)+ }, [twoMenuKey])// 重置数据useEffect(() => {if (currPlat && isReset) {- page.current = 1;- setDataSource([]);- setLoading(true);- getTableData().then(() => setLoading(false));- setIsReset(false);+ page.current = 1+ setDataSource([])+ setLoading(true)+ getTableData().then(() => setLoading(false))+ setIsReset(false)}- }, [isReset, currPlat, currDate, twoMenuKey]);+ }, [isReset, currPlat, currDate, twoMenuKey])return (<div className={styles.hotFeatures}><HotContentLabel- style={{ marginBottom: "15px" }}- labels={hotContentPlatformList.map((v) => v.name)}+ style={{ marginBottom: '15px' }}+ labels={hotContentPlatformList.map(v => v.name)}icons={hotContentPlatformList.map(- (v) => `${NEXT_PUBLIC_YIKA_OSS_HOST}/${v.icon}`,+ v => `${NEXT_PUBLIC_YIKA_OSS_HOST}/${v.icon}`,)}value={currPlat}onChange={(value) => {- setIsReset(true);- setCurrPlat(value);+ setIsReset(true)+ setCurrPlat(value)}}/><HotContentLabellabels={allDates.current}value={currDate}onChange={(value) => {- setIsReset(true);- setCurrDate(value);+ setIsReset(true)+ setCurrDate(value)}}/><Spin spinning={loading}><div- className={`${hotContentStyles["hotContent-table"]}`}+ className={`${hotContentStyles['hotContent-table']}`}id="hotContent-table"><InfiniteScroll@@ -258,24 +264,25 @@ const HotFeatures = memo(><TabledataSource={dataSource}- rowKey={(record) => record._id}+ rowKey={record => record._id}columns={columns}pagination={false}onRow={(record) => {return {onClick: () => {- if (!record.url) return;- window.open(record.url, "_blank");+ if (!record.url)+ return+ window.open(record.url, '_blank')},- };+ }}}/></InfiniteScroll></div></Spin></div>- );+ )}),-);+)-export default HotFeatures;+export default HotFeaturesdiff --git a/project/web/src/app/[lng]/hotContent/components/HotTitle/components/HotTitleCommons.tsx b/project/web/src/app/[lng]/hotContent/components/HotTitle/components/HotTitleCommons.tsxindex ae749aa1..42424bc4 100644--- a/project/web/src/app/[lng]/hotContent/components/HotTitle/components/HotTitleCommons.tsx+++ b/project/web/src/app/[lng]/hotContent/components/HotTitle/components/HotTitleCommons.tsx@@ -1,15 +1,16 @@-import { ViralTitle } from "@/api/types/viralTitles";-import styles from "../hotTitle.module.scss";-import HotTitleBackSvg from "../svgs/hotTitleBack.svg";-import Icon from "@ant-design/icons";-import { CSSProperties } from "react";-import { Table, type TableProps, Typography } from "antd";-import hotEventStyles from "../../HotEvent/hotEvent.module.scss";-import hotContentStyles from "../../HotContent/hotContent.module.scss";-import { describeNumber } from "@/utils";-import { useTransClient } from "@/app/i18n/client";+import type { TableProps } from 'antd'+import type { CSSProperties } from 'react'+import type { ViralTitle } from '@/api/types/viralTitles'+import Icon from '@ant-design/icons'+import { Table, Typography } from 'antd'+import { useTransClient } from '@/app/i18n/client'+import { describeNumber } from '@/utils'+import hotContentStyles from '../../HotContent/hotContent.module.scss'+import hotEventStyles from '../../HotEvent/hotEvent.module.scss'+import styles from '../hotTitle.module.scss'+import HotTitleBackSvg from '../svgs/hotTitleBack.svg'-export const HotTitleItem = ({+export function HotTitleItem({data,style,bottomLinkText,@@ -17,36 +18,38 @@ export const HotTitleItem = ({headRightElement,}: {data: {- category: string;- titles: ViralTitle[];- };- bottomLinkText: string;- onBottomLinkClick: () => void;- style?: CSSProperties;- headRightElement?: React.ReactNode;-}) => {- const { t } = useTransClient("hot-content");- const columns: TableProps<ViralTitle>["columns"] = [+ category: string+ titles: ViralTitle[]+ }+ bottomLinkText: string+ onBottomLinkClick: () => void+ style?: CSSProperties+ headRightElement?: React.ReactNode+}) {+ const { t } = useTransClient('hot-content')+ const columns: TableProps<ViralTitle>['columns'] = [{- title: t("rank"),+ title: t('rank'),width: 50,render: (text, data, ind) => (<>- {ind <= 2 ? (- <div- className={hotContentStyles.rankingTopthree}- style={{ width: "20px", height: "20px", lineHeight: "20px" }}- >- {ind + 1}- </div>- ) : (- <p style={{ width: "20px", textAlign: "center" }}>{ind + 1}</p>- )}+ {ind <= 2+ ? (+ <div+ className={hotContentStyles.rankingTopthree}+ style={{ width: '20px', height: '20px', lineHeight: '20px' }}+ >+ {ind + 1}+ </div>+ )+ : (+ <p style={{ width: '20px', textAlign: 'center' }}>{ind + 1}</p>+ )}</>),},{- title: t("viralTitles"),+ title: t('viralTitles'),render: (text, data, ind) => (<div className="hotTitleItem-title"><Typography.Paragraph copyable={{ text: data.title }}>@@ -56,15 +59,15 @@ export const HotTitleItem = ({),},{- title: t("engagement"),+ title: t('engagement'),width: 100,- align: "center",+ align: 'center',render: (text, data, ind) => <>{describeNumber(data.engagement)}</>,},- ];+ ]return (- <div className={styles.hotTitleItem + " hotTitleItem"} style={style}>+ <div className={`${styles.hotTitleItem} hotTitleItem`} style={style}><div className="hotTitleItem-head"><div className="hotTitleItem-head-left"><div className="hotTitleItem-head-name">{data.category}</div>@@ -73,32 +76,33 @@ export const HotTitleItem = ({{headRightElement}</div><div- className={`hotTitleItem-content ${hotEventStyles["hotEvent-item-content"]}`}+ className={`hotTitleItem-content ${hotEventStyles['hotEvent-item-content']}`}><TabledataSource={data.titles}columns={columns}- rowKey={(record) => record._id}+ rowKey={record => record._id}pagination={false}scroll={{ y: 400 }}onRow={(record) => {return {onClick: () => {- if (!record.url) return;- window.open(record.url, "_blank");+ if (!record.url)+ return+ window.open(record.url, '_blank')},- };+ }}}/><aonClick={(e) => {- e.preventDefault();- onBottomLinkClick();+ e.preventDefault()+ onBottomLinkClick()}}>{bottomLinkText}</a></div></div>- );-};+ )+}diff --git a/project/web/src/app/[lng]/hotContent/components/HotTitle/hotTitle.module.scss b/project/web/src/app/[lng]/hotContent/components/HotTitle/hotTitle.module.scssindex 2a439554..3e016531 100644--- a/project/web/src/app/[lng]/hotContent/components/HotTitle/hotTitle.module.scss+++ b/project/web/src/app/[lng]/hotContent/components/HotTitle/hotTitle.module.scss@@ -25,7 +25,8 @@height: 100%;min-height: 0;overflow: auto;- .hotTitleItem, .hotTitleItem-content {+ .hotTitleItem,+ .hotTitleItem-content {display: flex;flex-direction: column;height: 100% !important;@@ -44,7 +45,7 @@display: flex;justify-content: space-between;align-items: center;- background-image: linear-gradient(to left, rgba(90,246,242,.1), rgba(254,44,85,.1));+ background-image: linear-gradient(to left, rgba(90, 246, 242, 0.1), rgba(254, 44, 85, 0.1));padding: 10px 20px;border-radius: 10px 10px 0 0;.hotTitleItem-head-left {@@ -89,4 +90,4 @@}}}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/hotContent/components/HotTitle/index.tsx b/project/web/src/app/[lng]/hotContent/components/HotTitle/index.tsxindex 1a6b0715..d633276b 100644--- a/project/web/src/app/[lng]/hotContent/components/HotTitle/index.tsx+++ b/project/web/src/app/[lng]/hotContent/components/HotTitle/index.tsx@@ -1,5 +1,10 @@-import {+import type {ForwardedRef,+} from 'react'+import type { PlatformRanking } from '@/api/hot'+import type { ViralTitle } from '@/api/types/viralTitles'+import { Spin } from 'antd'+import {forwardRef,memo,useCallback,@@ -7,16 +12,14 @@ import {useMemo,useRef,useState,-} from "react";-import styles from "./hotTitle.module.scss";-import { useHotContent } from "@/app/[lng]/hotContent/useHotContent";-import { useShallow } from "zustand/react/shallow";-import { platformApi, PlatformRanking } from "@/api/hot";-import HotContentLabel from "@/app/[lng]/hotContent/components/HotContentLabel";-import { Spin } from "antd";-import { ViralTitle } from "@/api/types/viralTitles";-import { HotTitleItem } from "@/app/[lng]/hotContent/components/HotTitle/components/HotTitleCommons";-import { useTransClient } from "@/app/i18n/client";+} from 'react'+import { useShallow } from 'zustand/react/shallow'+import { platformApi } from '@/api/hot'+import HotContentLabel from '@/app/[lng]/hotContent/components/HotContentLabel'+import { HotTitleItem } from '@/app/[lng]/hotContent/components/HotTitle/components/HotTitleCommons'+import { useHotContent } from '@/app/[lng]/hotContent/useHotContent'+import { useTransClient } from '@/app/i18n/client'+import styles from './hotTitle.module.scss'export interface IHotTitleRef {}@@ -31,7 +34,7 @@ const HotTitle = memo(twoMenuKey,setCurrentRankCategory,} = useHotContent(- useShallow((state) => ({+ useShallow(state => ({labelData: state.labelData,rankingData: state.rankingData,datesData: state.datesData,@@ -39,115 +42,117 @@ const HotTitle = memo(currentRankCategory: state.currentRankCategory,setCurrentRankCategory: state.setCurrentRankCategory,})),- );- const { t } = useTransClient("hot-content");- const labelAll = useRef<string>(t("all"));+ )+ const { t } = useTransClient('hot-content')+ const labelAll = useRef<string>(t('all'))// 当前选中的标签- const [labelValue, setLabelValue] = useState(labelAll.current);+ const [labelValue, setLabelValue] = useState(labelAll.current)const allDates = useRef<string[]>([- t("last7days"),- t("last30days"),- t("last90days"),- ]);+ t('last7days'),+ t('last30days'),+ t('last90days'),+ ])// 当前选择的日期范围- const [currDate, setCurrDate] = useState(allDates.current[0]);- const [loading, setLoading] = useState(false);+ const [currDate, setCurrDate] = useState(allDates.current[0])+ const [loading, setLoading] = useState(false)// 所有爆款标题前五条数据const [allHotTitleData, setAllHotTitleData] = useState<{- category: string;- titles: ViralTitle[];+ category: string+ titles: ViralTitle[]}[]- >();+ >()// 爆款标题数据详情- const [hotTitleData, setHotTitleData] = useState<ViralTitle[]>([]);+ const [hotTitleData, setHotTitleData] = useState<ViralTitle[]>([])// 获取当前选中的标签、日期、榜单const selectedLabelInfo = useMemo(() => {- const platId = twoMenuKey.split("_")[1];+ const platId = twoMenuKey.split('_')[1]return {// 所有榜单allRanking: rankingData[platId] || [],// 当前选择榜单ranking: (rankingData[platId]?.find(- (v) => v.id === currentRankCategory,+ v => v.id === currentRankCategory,) ?? {}) as PlatformRanking,labelData: labelData[platId] || [],platId,- };- }, [labelData, rankingData, twoMenuKey, currentRankCategory]);+ }+ }, [labelData, rankingData, twoMenuKey, currentRankCategory])const dateValue = useMemo(() => {- return currDate === t("last7days")- ? "近7天"- : currDate === t("last30days")- ? "近30天"- : currDate === t("last90days")- ? "近90天"- : "";- }, [currDate]);+ return currDate === t('last7days')+ ? '近7天'+ : currDate === t('last30days')+ ? '近30天'+ : currDate === t('last90days')+ ? '近90天'+ : ''+ }, [currDate])// 获取所有爆款数据const getAllData = useCallback(async () => {- if (labelValue !== labelAll.current) return;+ if (labelValue !== labelAll.current)+ return- setLoading(true);+ setLoading(true)const res = await platformApi.findTopByPlatformAndCategories(selectedLabelInfo.platId,dateValue,- );- setLoading(false);- setAllHotTitleData(res?.data);- }, [dateValue, selectedLabelInfo.platId]);+ )+ setLoading(false)+ setAllHotTitleData(res?.data)+ }, [dateValue, selectedLabelInfo.platId])// 获取爆款数据详情const getDetailData = useCallback(async () => {- if (labelValue === labelAll.current) return;+ if (labelValue === labelAll.current)+ return- setLoading(true);+ setLoading(true)const res = await platformApi.findByPlatformAndCategory(selectedLabelInfo.platId,{- category: labelValue === labelAll.current ? t("all") : labelValue,+ category: labelValue === labelAll.current ? t('all') : labelValue,page: 1,timeType: dateValue,pageSize: 50,},- );- setHotTitleData(res?.data.items || []);- setLoading(false);+ )+ setHotTitleData(res?.data.items || [])+ setLoading(false)}, [labelValue,dateValue,selectedLabelInfo.ranking.id,selectedLabelInfo.platId,- ]);+ ])useEffect(() => {- getAllData();- }, [twoMenuKey, dateValue]);+ getAllData()+ }, [twoMenuKey, dateValue])useEffect(() => {- getDetailData();- }, [labelValue, dateValue]);+ getDetailData()+ }, [labelValue, dateValue])return (<div className={styles.hotTitle}><HotContentLabel- style={{ marginBottom: "15px" }}+ style={{ marginBottom: '15px' }}labels={[labelAll.current, ...(selectedLabelInfo.labelData ?? [])]}value={labelValue}onChange={(value) => {- setLabelValue(value);+ setLabelValue(value)}}/><HotContentLabel- style={{ marginBottom: "15px" }}+ style={{ marginBottom: '15px' }}labels={allDates.current}value={currDate}onChange={(value) => {- setCurrDate(value);+ setCurrDate(value)}}/>@@ -155,7 +160,7 @@ const HotTitle = memo(<divclassName="hotTitle-content-wrapper"style={{- display: labelValue === labelAll.current ? "flex" : "none",+ display: labelValue === labelAll.current ? 'flex' : 'none',}}>{allHotTitleData?.map((v) => {@@ -163,51 +168,51 @@ const HotTitle = memo(<HotTitleItemdata={v}key={v.category}- style={{ width: "calc(50% - 15px)", marginBottom: "30px" }}+ style={{ width: 'calc(50% - 15px)', marginBottom: '30px' }}onBottomLinkClick={() => {- setLabelValue(v.category);+ setLabelValue(v.category)}}- bottomLinkText={t("viewMore")}+ bottomLinkText={t('viewMore')}/>- );+ )})}</div><divclassName="hotTitle-content-wrapper-details"style={{- display: labelValue !== labelAll.current ? "flex" : "none",+ display: labelValue !== labelAll.current ? 'flex' : 'none',}}><HotTitleItem- headRightElement={+ headRightElement={(<><aonClick={(e) => {- e.preventDefault();- setLabelValue(labelAll.current);+ e.preventDefault()+ setLabelValue(labelAll.current)}}>- {t("backToAll")}+ {t('backToAll')}</a></>- }+ )}data={{category: labelValue,titles: hotTitleData,}}key={labelValue}- style={{ width: "100%", marginBottom: "30px" }}+ style={{ width: '100%', marginBottom: '30px' }}onBottomLinkClick={() => {- setLabelValue(labelAll.current);+ setLabelValue(labelAll.current)}}- bottomLinkText={t("collapse")}+ bottomLinkText={t('collapse')}/></div></Spin></div>- );+ )}),-);+)-export default HotTitle;+export default HotTitlediff --git a/project/web/src/app/[lng]/hotContent/hotContent.enum.ts b/project/web/src/app/[lng]/hotContent/hotContent.enum.tsindex 65a306d4..31e644c1 100644--- a/project/web/src/app/[lng]/hotContent/hotContent.enum.ts+++ b/project/web/src/app/[lng]/hotContent/hotContent.enum.ts@@ -1,6 +1,6 @@export enum HotType {- hotContent = "hotContent",- hotEvent = "hotEvent",- hotFeatures = "HotFeatures",- hotTitle = "hotTitle",+ hotContent = 'hotContent',+ hotEvent = 'hotEvent',+ hotFeatures = 'HotFeatures',+ hotTitle = 'hotTitle',}diff --git a/project/web/src/app/[lng]/hotContent/hotContent.module.scss b/project/web/src/app/[lng]/hotContent/hotContent.module.scssindex 766cbe17..ff87c8d4 100644--- a/project/web/src/app/[lng]/hotContent/hotContent.module.scss+++ b/project/web/src/app/[lng]/hotContent/hotContent.module.scss@@ -26,4 +26,4 @@min-height: 0;}}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/hotContent/page.tsx b/project/web/src/app/[lng]/hotContent/page.tsxindex 6b08a365..620073cf 100644--- a/project/web/src/app/[lng]/hotContent/page.tsx+++ b/project/web/src/app/[lng]/hotContent/page.tsx@@ -1,14 +1,14 @@-import { PageParams } from "@/app/globals";-import { getMetadata } from "@/utils/general";-import { HotContentCore } from "@/app/[lng]/hotContent/HotContentCore";+import type { PageParams } from '@/app/globals'+import { HotContentCore } from '@/app/[lng]/hotContent/HotContentCore'+import { getMetadata } from '@/utils/general'export async function generateMetadata({ params }: PageParams) {return await getMetadata({- title: "热门内容",+ title: '热门内容',},- "en",- );+ 'en',+ )}export default async function Page() {@@ -24,5 +24,5 @@ export default async function Page() {<><HotContentCore defaultHotContentData={undefined} /></>- );+ )}diff --git a/project/web/src/app/[lng]/hotContent/useHotContent.ts b/project/web/src/app/[lng]/hotContent/useHotContent.tsindex d4d54eee..f1aa1cf2 100644--- a/project/web/src/app/[lng]/hotContent/useHotContent.ts+++ b/project/web/src/app/[lng]/hotContent/useHotContent.ts@@ -1,54 +1,55 @@-import { create } from "zustand";-import { combine } from "zustand/middleware";-import lodash from "lodash";-import { Platform, platformApi, PlatformRanking, RankingDate } from "@/api/hot";-import { HotType } from "@/app/[lng]/hotContent/hotContent.enum";+import type { Platform, PlatformRanking, RankingDate } from '@/api/hot'+import lodash from 'lodash'+import { create } from 'zustand'+import { combine } from 'zustand/middleware'+import { platformApi } from '@/api/hot'+import { HotType } from '@/app/[lng]/hotContent/hotContent.enum'export interface IHotContentStore {// 当前选择的 热点分类- hotType: HotType;+ hotType: HotType// 热门内容平台list- hotContentPlatformList: Platform[];+ hotContentPlatformList: Platform[]// 爆款标题平台list- hotTitlePlatformList: Platform[];+ hotTitlePlatformList: Platform[]// 数据loading- dataLoading: boolean;+ dataLoading: boolean// 当前侧边栏二级菜单选择的ID- twoMenuKey: string;+ twoMenuKey: string// 热门内容页面loading- pageLoading: boolean;+ pageLoading: boolean// 热门内容的标签数据 key=平台,value=标签数组labelData: {- [key: string]: string[];- };+ [key: string]: string[]+ }// 热门内容的榜单数据 key=平台ID,value=榜单数据rankingData: {- [key: string]: PlatformRanking[];- };+ [key: string]: PlatformRanking[]+ }// 日期数据 key=平台ID,value=日期数据datesData: {- [key: string]: RankingDate[];- };+ [key: string]: RankingDate[]+ }// 当前选择的榜单分类- currentRankCategory: string;+ currentRankCategory: string}const store: IHotContentStore = {hotType: HotType.hotContent,hotContentPlatformList: [],dataLoading: false,- twoMenuKey: "",+ twoMenuKey: '',hotTitlePlatformList: [],pageLoading: false,labelData: {},rankingData: {},datesData: {},- currentRankCategory: "",-};+ currentRankCategory: '',+}-const getStore = () => {- return lodash.cloneDeep(store);-};+function getStore() {+ return lodash.cloneDeep(store)+}/*** 热门内容数据存储@@ -62,76 +63,76 @@ export const useHotContent = create(const methods = {// 设置 currentRankCategorysetCurrentRankCategory(currentRankCategory: string) {- set({ currentRankCategory });+ set({ currentRankCategory })},// 设置 当前侧边栏二级菜单选择的IDsetTwoMenuKey(twoMenuKey: string) {- set({ twoMenuKey });+ set({ twoMenuKey })},// 设置当前选择的 热点分类setHotType(hotType: HotType) {- set({ hotType });+ set({ hotType })},// 初始化async init() {- set({ pageLoading: true });+ set({ pageLoading: true })await Promise.all([methods.getHotContentPlatform(),methods.getHotTitlePlatform(),- ]);- set({ pageLoading: false });+ ])+ set({ pageLoading: false })},// 获取热门内容平台async getHotContentPlatform() {- const res = await platformApi.getPlatformList();- const twoMenuKey = `${HotType.hotContent}_${res?.data?.[0]?.id}`;+ const res = await platformApi.getPlatformList()+ const twoMenuKey = `${HotType.hotContent}_${res?.data?.[0]?.id}`set({hotContentPlatformList: res?.data,twoMenuKey,- });+ })- methods.changeHotContentPlatform(twoMenuKey);+ methods.changeHotContentPlatform(twoMenuKey)},// 获取爆款标题平台async getHotTitlePlatform() {- const res = await platformApi.findPlatformsWithData();+ const res = await platformApi.findPlatformsWithData()set({hotTitlePlatformList: res?.data,- });+ })},// 热门内容平台切换async changeHotContentPlatform(platformId: string) {- const { rankingData } = get();- platformId = platformId.split("_")[1];+ const { rankingData } = get()+ platformId = platformId.split('_')[1]set({pageLoading: true,- });+ })if (!rankingData[platformId]) {- const res = await platformApi.getPlatformRanking(platformId);+ const res = await platformApi.getPlatformRanking(platformId)if (res?.data?.length) {const newRankingData = {...rankingData,[platformId]: res.data,- };- set({ rankingData: newRankingData });+ }+ set({ rankingData: newRankingData })}}set({- currentRankCategory: get().rankingData[platformId]?.[0]?.id || "",- });+ currentRankCategory: get().rankingData[platformId]?.[0]?.id || '',+ })const rankingItem = get().rankingData[platformId].find(- (v) => v.id === get().currentRankCategory,- )!;+ v => v.id === get().currentRankCategory,+ )!// 获取标签和日期数据if (!get().labelData[platformId]) {await Promise.all([@@ -141,25 +142,25 @@ export const useHotContent = create(const newLabelData = {...get().labelData,[platformId]: labelRes!.data,- };+ }const newDatesData = {...get().datesData,[platformId]: dateRes!.data,- };+ }set({labelData: newLabelData,datesData: newDatesData,- });- });+ })+ })}set({pageLoading: false,- });+ })},- };+ }- return methods;+ return methods},),-);+)diff --git a/project/web/src/app/[lng]/income/income.module.css b/project/web/src/app/[lng]/income/income.module.cssindex 601c9cde..70aa424e 100644--- a/project/web/src/app/[lng]/income/income.module.css+++ b/project/web/src/app/[lng]/income/income.module.css@@ -34,8 +34,13 @@}@keyframes shimmer {- 0%, 100% { transform: translateX(-100%); }- 50% { transform: translateX(100%); }+ 0%,+ 100% {+ transform: translateX(-100%);+ }+ 50% {+ transform: translateX(100%);+ }}.headerLeft {@@ -101,7 +106,6 @@min-width: 200px;}-.walletLink {display: inline-flex;align-items: center;@@ -379,69 +383,69 @@.container {padding: 12px;}-+.headerContent {flex-direction: column;gap: 20px;padding: 20px;text-align: center;}-+.headerLeft {flex-direction: column;gap: 12px;}-+.headerIcon {width: 48px;height: 48px;font-size: 20px;}-+.headerTitle {font-size: 24px;}-+.headerSubtitle {font-size: 14px;}-+.balanceCard {min-width: auto;width: 100%;justify-content: center;}-+.balanceAmount {font-size: 20px;}-+.content {padding: 16px;}-+.content .ant-tabs > .ant-tabs-nav .ant-tabs-tab {padding: 8px 16px;font-size: 14px;}-+.content .ant-table-thead > tr > th,.content .ant-table-tbody > tr > td {padding: 8px 6px;font-size: 12px;}-+.content .ant-btn {font-size: 12px;padding: 4px 8px;}-+.withdrawItem {flex-direction: column;align-items: flex-start;gap: 4px;}-+.withdrawValue {max-width: none;text-align: left;@@ -452,19 +456,19 @@.headerContent {padding: 16px;}-+.headerTitle {font-size: 20px;}-+.balanceCard {padding: 16px;}-+.content {padding: 12px;}-+.content .ant-tabs > .ant-tabs-nav .ant-tabs-tab {padding: 6px 12px;font-size: 12px;diff --git a/project/web/src/app/[lng]/income/page.tsx b/project/web/src/app/[lng]/income/page.tsxindex 778ec295..8644e54e 100644--- a/project/web/src/app/[lng]/income/page.tsx+++ b/project/web/src/app/[lng]/income/page.tsx@@ -1,139 +1,150 @@-"use client";+'use client'-import { useEffect, useState } from "react";-import { Card, Table, Button, message, Modal, Tabs, Tag, Space, Popconfirm, Descriptions, Input, Select, Form } from "antd";-import { DollarOutlined, HistoryOutlined, WalletOutlined, CheckCircleOutlined, ClockCircleOutlined, CloseCircleOutlined } from "@ant-design/icons";-import { useParams, useRouter } from "next/navigation";-import { useUserStore } from "@/store/user";-import { apiGetIncomeList, apiSubmitWithdraw } from "@/api/income";-import { apiGetWithdrawRecordList } from "@/api/withdraw";-import { IncomeRecord } from "@/api/types/income";-import { WithdrawRecord, WithdrawRecordStatus } from "@/api/types/withdraw";-import { useTransClient } from "@/app/i18n/client";-import styles from "./income.module.css";-import WalletAccountSelect from "@/components/WalletAccountSelect";+import type { IncomeRecord } from '@/api/types/income'+import type { WithdrawRecord } from '@/api/types/withdraw'+import { CheckCircleOutlined, ClockCircleOutlined, CloseCircleOutlined, DollarOutlined, HistoryOutlined, WalletOutlined } from '@ant-design/icons'+import { Button, Card, Descriptions, Form, Input, message, Modal, Popconfirm, Select, Space, Table, Tabs, Tag } from 'antd'+import { useParams, useRouter } from 'next/navigation'+import { useEffect, useState } from 'react'+import { apiGetIncomeList, apiSubmitWithdraw } from '@/api/income'+import { WithdrawRecordStatus } from '@/api/types/withdraw'+import { apiGetWithdrawRecordList } from '@/api/withdraw'+import { useTransClient } from '@/app/i18n/client'+import WalletAccountSelect from '@/components/WalletAccountSelect'+import { useUserStore } from '@/store/user'+import styles from './income.module.css'-const { TabPane } = Tabs;-const { Option } = Select;+const { TabPane } = Tabs+const { Option } = Selectexport default function IncomePage() {- const router = useRouter();- const params = useParams();- const { userInfo, token, lang } = useUserStore();- const { t } = useTransClient('income');-+ const router = useRouter()+ const params = useParams()+ const { userInfo, token, lang } = useUserStore()+ const { t } = useTransClient('income')+// 收入记录相关状态- const [incomeRecords, setIncomeRecords] = useState<IncomeRecord[]>([]);- const [incomeLoading, setIncomeLoading] = useState(false);+ const [incomeRecords, setIncomeRecords] = useState<IncomeRecord[]>([])+ const [incomeLoading, setIncomeLoading] = useState(false)const [incomePagination, setIncomePagination] = useState({current: 1,pageSize: 10,- total: 0- });-+ total: 0,+ })+// 提现记录相关状态- const [withdrawRecords, setWithdrawRecords] = useState<WithdrawRecord[]>([]);- const [withdrawLoading, setWithdrawLoading] = useState(false);+ const [withdrawRecords, setWithdrawRecords] = useState<WithdrawRecord[]>([])+ const [withdrawLoading, setWithdrawLoading] = useState(false)const [withdrawPagination, setWithdrawPagination] = useState({current: 1,pageSize: 10,- total: 0- });-+ total: 0,+ })+// 提现申请状态- const [withdrawModalVisible, setWithdrawModalVisible] = useState(false);- const [selectedIncomeRecord, setSelectedIncomeRecord] = useState<IncomeRecord | null>(null);- const [withdrawSubmitting, setWithdrawSubmitting] = useState(false);+ const [withdrawModalVisible, setWithdrawModalVisible] = useState(false)+ const [selectedIncomeRecord, setSelectedIncomeRecord] = useState<IncomeRecord | null>(null)+ const [withdrawSubmitting, setWithdrawSubmitting] = useState(false)// 获取收入记录const fetchIncomeRecords = async (page: number = 1, pageSize: number = 10) => {- setIncomeLoading(true);+ setIncomeLoading(true)try {- const response = await apiGetIncomeList({ pageNo: page, pageSize }, {});+ const response = await apiGetIncomeList({ pageNo: page, pageSize }, {})if (response?.data) {- setIncomeRecords(response.data.list || []);+ setIncomeRecords(response.data.list || [])setIncomePagination({current: page,pageSize,- total: response?.data?.total || 0- });- } else {- message.error(t('messages.getIncomeRecordsFailed'));+ total: response?.data?.total || 0,+ })}- } catch (error) {- message.error(t('messages.getIncomeRecordsFailed'));- } finally {- setIncomeLoading(false);+ else {+ message.error(t('messages.getIncomeRecordsFailed'))+ }+ }+ catch (error) {+ message.error(t('messages.getIncomeRecordsFailed'))+ }+ finally {+ setIncomeLoading(false)}- };+ }// 获取提现记录const fetchWithdrawRecords = async (page: number = 1, pageSize: number = 10) => {- setWithdrawLoading(true);+ setWithdrawLoading(true)try {- const response = await apiGetWithdrawRecordList({ pageNo: page, pageSize }, {});+ const response = await apiGetWithdrawRecordList({ pageNo: page, pageSize }, {})if (response?.data) {- setWithdrawRecords(response.data.list || []);+ setWithdrawRecords(response.data.list || [])setWithdrawPagination({current: page,pageSize,- total: response.data.total || 0- });- } else {- message.error(t('messages.getWithdrawRecordsFailed'));+ total: response.data.total || 0,+ })}- } catch (error) {- message.error(t('messages.getWithdrawRecordsFailed'));- } finally {- setWithdrawLoading(false);+ else {+ message.error(t('messages.getWithdrawRecordsFailed'))+ }+ }+ catch (error) {+ message.error(t('messages.getWithdrawRecordsFailed'))+ }+ finally {+ setWithdrawLoading(false)}- };+ }// 提交提现申请const handleWithdraw = async (incomeRecord: IncomeRecord) => {- setSelectedIncomeRecord(incomeRecord);- setWithdrawModalVisible(true);- };+ setSelectedIncomeRecord(incomeRecord)+ setWithdrawModalVisible(true)+ }// 确认提现申请- const [form] = Form.useForm<{ userWalletAccountId: string }>();+ const [form] = Form.useForm<{ userWalletAccountId: string }>()const handleConfirmWithdraw = async () => {- if (!selectedIncomeRecord) return;+ if (!selectedIncomeRecord)+ return// 仅 status = 1 的收入记录可提现(按需求说明:1=可提现,0=已申请)// 如果后端收入列表中没有 status 字段,这里按前端约定:仅当类型为 task 时允许(已有逻辑),并在提现接口前再行校验-- setWithdrawSubmitting(true);++ setWithdrawSubmitting(true)try {- const values = await form.validateFields();- const response = await apiSubmitWithdraw(selectedIncomeRecord._id, values.userWalletAccountId);+ const values = await form.validateFields()+ const response = await apiSubmitWithdraw(selectedIncomeRecord._id, values.userWalletAccountId)if (response) {- message.success(t('messages.withdrawSubmitted'));- setWithdrawModalVisible(false);- setSelectedIncomeRecord(null);+ message.success(t('messages.withdrawSubmitted'))+ setWithdrawModalVisible(false)+ setSelectedIncomeRecord(null)// 刷新提现记录- fetchWithdrawRecords(withdrawPagination.current, withdrawPagination.pageSize);- } else {- message.error(t('messages.withdrawFailed'));+ fetchWithdrawRecords(withdrawPagination.current, withdrawPagination.pageSize)+ }+ else {+ message.error(t('messages.withdrawFailed'))}- } catch (error) {- message.error(t('messages.withdrawFailed'));- } finally {- setWithdrawSubmitting(false);}- };+ catch (error) {+ message.error(t('messages.withdrawFailed'))+ }+ finally {+ setWithdrawSubmitting(false)+ }+ }// 获取收入类型显示文本const getIncomeTypeText = (type: string) => {- const typeMap: { [key: string]: { color: string; text: string } } = {- 'task': { color: 'green', text: t('incomeTypes.task') },- 'task_back': { color: 'orange', text: t('incomeTypes.task_back') },- 'reward_back': { color: 'blue', text: t('incomeTypes.reward_back') },- 'task_withdraw': { color: 'purple', text: t('incomeTypes.task_withdraw' as any) }- };- const config = typeMap[type] || { color: 'default', text: type };- return <Tag color={config.color}>{config.text}</Tag>;- };+ const typeMap: { [key: string]: { color: string, text: string } } = {+ task: { color: 'green', text: t('incomeTypes.task') },+ task_back: { color: 'orange', text: t('incomeTypes.task_back') },+ reward_back: { color: 'blue', text: t('incomeTypes.reward_back') },+ task_withdraw: { color: 'purple', text: t('incomeTypes.task_withdraw' as any) },+ }+ const config = typeMap[type] || { color: 'default', text: type }+ return <Tag color={config.color}>{config.text}</Tag>+ }// 获取提现状态显示const getWithdrawStatusTag = (status: WithdrawRecordStatus) => {@@ -141,15 +152,15 @@ export default function IncomePage() {[WithdrawRecordStatus.WAIT]: { color: 'orange', text: t('withdrawStatus.wait'), icon: <ClockCircleOutlined /> },[WithdrawRecordStatus.SUCCESS]: { color: 'green', text: t('withdrawStatus.success'), icon: <CheckCircleOutlined /> },[WithdrawRecordStatus.FAIL]: { color: 'red', text: t('withdrawStatus.fail'), icon: <CloseCircleOutlined /> },- [WithdrawRecordStatus.TASK_WITHDRAW]: { color: 'blue', text: t('withdrawStatus.task_withdraw' as any), icon: <DollarOutlined /> }- };- const config = statusMap[status] || { color: 'default', text: '未知状态', icon: null };+ [WithdrawRecordStatus.TASK_WITHDRAW]: { color: 'blue', text: t('withdrawStatus.task_withdraw' as any), icon: <DollarOutlined /> },+ }+ const config = statusMap[status] || { color: 'default', text: '未知状态', icon: null }return (<Tag color={config.color} icon={config.icon}>{config.text}</Tag>- );- };+ )+ }// 收入记录表格列const incomeColumns = [@@ -166,7 +177,9 @@ export default function IncomePage() {key: 'amount',render: (amount: number) => (<span style={{ color: '#52c41a', fontWeight: 'bold' }}>- CNY {amount/100}+ CNY+ {' '}+ {amount / 100}</span>),},@@ -193,19 +206,21 @@ export default function IncomePage() {key: 'action',render: (_: any, record: IncomeRecord) => (<Space>- {record.type === 'task' && record.status === 0 ? (- <Button- type="primary"- size="small"- onClick={() => handleWithdraw(record)}- >- {t('applyWithdraw')}- </Button>- ) : null}+ {record.type === 'task' && record.status === 0+ ? (+ <Button+ type="primary"+ size="small"+ onClick={() => handleWithdraw(record)}+ >+ {t('applyWithdraw')}+ </Button>+ )+ : null}</Space>),},- ];+ ]// 提现记录表格列const withdrawColumns = [@@ -222,7 +237,9 @@ export default function IncomePage() {key: 'amount',render: (amount: number) => (<span style={{ color: '#1890ff', fontWeight: 'bold' }}>- CNY {amount/100}+ CNY+ {' '}+ {amount / 100}</span>),},@@ -250,19 +267,19 @@ export default function IncomePage() {key: 'updatedAt',render: (date: Date) => new Date(date).toLocaleString(),},- ];+ ]useEffect(() => {if (!token) {- message.error(t('messages.pleaseLoginFirst'));- router.push('/login');- return;+ message.error(t('messages.pleaseLoginFirst'))+ router.push('/login')+ return}-+// 初始加载数据- fetchIncomeRecords(1, 10);- fetchWithdrawRecords(1, 10);- }, [token, router]);+ fetchIncomeRecords(1, 10)+ fetchWithdrawRecords(1, 10)+ }, [token, router])return (<div className={styles.container}>@@ -285,15 +302,18 @@ export default function IncomePage() {</div><div className={styles.balanceInfo}><div className={styles.balanceLabel}>{t('currentBalance')}</div>- <div className={styles.balanceAmount}>CNY {(userInfo?.income as number / 100 || 0).toFixed(2)}</div>+ <div className={styles.balanceAmount}>+ CNY+ {(userInfo?.income as number / 100 || 0).toFixed(2)}+ </div></div></div><spanclassName={styles.walletLink}role="button"onClick={() => {- const effectiveLng = (params as any)?.lng || lang || "zh-CN";- router.push(`/${effectiveLng}/wallet`);+ const effectiveLng = (params as any)?.lng || lang || 'zh-CN'+ router.push(`/${effectiveLng}/wallet`)}}>{t('myWallet')}@@ -305,13 +325,14 @@ export default function IncomePage() {{/* 主要内容 */}<div className={styles.content}><Tabs defaultActiveKey="income" size="large">- <TabPane- tab={+ <TabPane+ tab={(<span>- <DollarOutlined /> + <DollarOutlined />+ {t('incomeRecords')}</span>- }+ )}key="income"><Card>@@ -325,28 +346,29 @@ export default function IncomePage() {pageSize: incomePagination.pageSize,total: incomePagination.total,onChange: (page, size) => {- fetchIncomeRecords(page, size || 10);+ fetchIncomeRecords(page, size || 10)},showSizeChanger: true,showQuickJumper: true,- showTotal: (total) => t('messages.totalRecords', { total }),+ showTotal: total => t('messages.totalRecords', { total }),pageSizeOptions: ['10', '20', '50'],}}scroll={{ x: 800 }}locale={{- emptyText: incomeLoading ? t('messages.loading') : t('messages.noIncomeRecords')+ emptyText: incomeLoading ? t('messages.loading') : t('messages.noIncomeRecords'),}}/></Card></TabPane>-- <TabPane- tab={++ <TabPane+ tab={(<span>- <HistoryOutlined /> + <HistoryOutlined />+ {t('withdrawRecords')}</span>- }+ )}key="withdraw"><Card>@@ -360,16 +382,16 @@ export default function IncomePage() {pageSize: withdrawPagination.pageSize,total: withdrawPagination.total,onChange: (page, size) => {- fetchWithdrawRecords(page, size || 10);+ fetchWithdrawRecords(page, size || 10)},showSizeChanger: true,showQuickJumper: true,- showTotal: (total) => t('messages.totalRecords', { total }),+ showTotal: total => t('messages.totalRecords', { total }),pageSizeOptions: ['10', '20', '50'],}}scroll={{ x: 800 }}locale={{- emptyText: withdrawLoading ? t('messages.loading') : t('messages.noWithdrawRecords')+ emptyText: withdrawLoading ? t('messages.loading') : t('messages.noWithdrawRecords'),}}/></Card>@@ -382,24 +404,27 @@ export default function IncomePage() {title={t('confirmWithdraw')}open={withdrawModalVisible}onCancel={() => {- setWithdrawModalVisible(false);- setSelectedIncomeRecord(null);+ setWithdrawModalVisible(false)+ setSelectedIncomeRecord(null)}}footer={[- <Button key="cancel" onClick={() => {- setWithdrawModalVisible(false);- setSelectedIncomeRecord(null);- }}>+ <Button+ key="cancel"+ onClick={() => {+ setWithdrawModalVisible(false)+ setSelectedIncomeRecord(null)+ }}+ >{t('cancel')}</Button>,- <Button- key="confirm"- type="primary"+ <Button+ key="confirm"+ type="primary"loading={withdrawSubmitting}onClick={handleConfirmWithdraw}>{t('confirm')}- </Button>+ </Button>,]}width={500}centered@@ -408,27 +433,42 @@ export default function IncomePage() {<div className={styles.withdrawModalContent}><div className={styles.withdrawInfo}><div className={styles.withdrawItem}>- <span className={styles.withdrawLabel}>{t('incomeId')}:</span>+ <span className={styles.withdrawLabel}>+ {t('incomeId')}+ :+ </span><span className={styles.withdrawValue}>{selectedIncomeRecord._id}</span></div><div className={styles.withdrawItem}>- <span className={styles.withdrawLabel}>{t('withdrawAmount')}:</span>- <span className={styles.withdrawAmount}>CNY {selectedIncomeRecord.amount/100}</span>+ <span className={styles.withdrawLabel}>+ {t('withdrawAmount')}+ :+ </span>+ <span className={styles.withdrawAmount}>+ CNY+ {selectedIncomeRecord.amount / 100}+ </span></div><div className={styles.withdrawItem}>- <span className={styles.withdrawLabel}>{t('incomeType')}:</span>+ <span className={styles.withdrawLabel}>+ {t('incomeType')}+ :+ </span><span>{getIncomeTypeText(selectedIncomeRecord.type)}</span></div>{selectedIncomeRecord.desc && (<div className={styles.withdrawItem}>- <span className={styles.withdrawLabel}>{t('description')}:</span>+ <span className={styles.withdrawLabel}>+ {t('description')}+ :+ </span><span className={styles.withdrawValue}>{selectedIncomeRecord.desc}</span></div>)}</div><Form form={form} layout="vertical">- <Form.Item name="userWalletAccountId" label={t('myWallet')} rules={[{ required: true, message: t('messages.pleaseLoginFirst') }]}>+ <Form.Item name="userWalletAccountId" label={t('myWallet')} rules={[{ required: true, message: t('messages.pleaseLoginFirst') }]}><WalletAccountSelect /></Form.Item></Form>@@ -441,5 +481,5 @@ export default function IncomePage() {)}</Modal></div>- );+ )}diff --git a/project/web/src/app/[lng]/interactive/interactive.module.css b/project/web/src/app/[lng]/interactive/interactive.module.cssindex 06361852..020f815e 100644--- a/project/web/src/app/[lng]/interactive/interactive.module.css+++ b/project/web/src/app/[lng]/interactive/interactive.module.css@@ -33,8 +33,13 @@}@keyframes shimmer {- 0%, 100% { transform: translateX(-100%); }- 50% { transform: translateX(100%); }+ 0%,+ 100% {+ transform: translateX(-100%);+ }+ 50% {+ transform: translateX(100%);+ }}.headerLeft {@@ -100,7 +105,6 @@min-width: 200px;}-.walletLink {display: inline-flex;align-items: center;@@ -379,69 +383,69 @@.container {padding: 12px;}-+.headerContent {flex-direction: column;gap: 20px;padding: 20px;text-align: center;}-+.headerLeft {flex-direction: column;gap: 12px;}-+.headerIcon {width: 48px;height: 48px;font-size: 20px;}-+.headerTitle {font-size: 24px;}-+.headerSubtitle {font-size: 14px;}-+.balanceCard {min-width: auto;width: 100%;justify-content: center;}-+.balanceAmount {font-size: 20px;}-+.content {padding: 16px;}-+.content .ant-tabs > .ant-tabs-nav .ant-tabs-tab {padding: 8px 16px;font-size: 14px;}-+.content .ant-table-thead > tr > th,.content .ant-table-tbody > tr > td {padding: 8px 6px;font-size: 12px;}-+.content .ant-btn {font-size: 12px;padding: 4px 8px;}-+.withdrawItem {flex-direction: column;align-items: flex-start;gap: 4px;}-+.withdrawValue {max-width: none;text-align: left;@@ -452,19 +456,19 @@.headerContent {padding: 16px;}-+.headerTitle {font-size: 20px;}-+.balanceCard {padding: 16px;}-+.content {padding: 12px;}-+.content .ant-tabs > .ant-tabs-nav .ant-tabs-tab {padding: 6px 12px;font-size: 12px;@@ -500,7 +504,7 @@height: 100%;object-fit: cover;}-.playIcon{+.playIcon {position: absolute;left: 50%;top: 50%;@@ -511,17 +515,20 @@width: 56px;height: 56px;border-radius: 50%;- background: rgba(0,0,0,0.25);+ background: rgba(0, 0, 0, 0.25);}.thumbPlaceholder {position: absolute;inset: 0;- display: flex; align-items: center; justify-content: center;+ display: flex;+ align-items: center;+ justify-content: center;color: #999;}.mediaType {position: absolute;- left: 8px; bottom: 8px;+ left: 8px;+ bottom: 8px;}.postMeta {padding: 12px;@@ -533,10 +540,14 @@margin-top: 8px;}.postTitle {- font-size: 14px; font-weight: 600; color: #111;- line-height: 1.4; max-height: 3.2em; overflow: hidden;+ font-size: 14px;+ font-weight: 600;+ color: #111;+ line-height: 1.4;+ max-height: 3.2em;+ overflow: hidden;}-.postContent{+.postContent {margin-top: 6px;font-size: 12px;color: #4b5563;@@ -545,7 +556,10 @@overflow: hidden;}.statsRow {- display: flex; gap: 12px; color: #666; font-size: 12px;+ display: flex;+ gap: 12px;+ color: #666;+ font-size: 12px;}/* 评论弹窗布局修正 */@@ -566,4 +580,4 @@}.commentBtn:hover {border-color: #d1d5db;-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/interactive/page.tsx b/project/web/src/app/[lng]/interactive/page.tsxindex 1c35e3ec..ce73574a 100644--- a/project/web/src/app/[lng]/interactive/page.tsx+++ b/project/web/src/app/[lng]/interactive/page.tsx@@ -1,153 +1,158 @@-"use client";--import { useEffect, useRef, useState } from "react";-import { Card, Button, message, Tag, Space, Select, Modal, Input, List, Avatar } from "antd";-import { DollarOutlined, HistoryOutlined, WalletOutlined, CommentOutlined, LikeOutlined, EyeOutlined, PlayCircleOutlined, RobotOutlined } from "@ant-design/icons";-import { useParams, useRouter } from "next/navigation";-import { useUserStore } from "@/store/user";-import { apiGetEngagementnew, apiGetEngagementPosts, apiGetEngagementComments, apiReplyEngagementComment, apiGetPostComments, apiPublishPostComment, apiPublishCommentReply, apiGetCommentReplies } from "@/api/engagement";-import { getChatModels, createAiReplyTask } from "@/api/ai";-import { EngagementPostItem, EngagementPlatform } from "@/api/types/engagement";-import { useTransClient } from "@/app/i18n/client";-import { request } from "@/utils/request";-import styles from "./interactive.module.css";-import WalletAccountSelect from "@/components/WalletAccountSelect";-import { useAccountStore } from "@/store/account";-import { useShallow } from "zustand/react/shallow";-import AccountSidebar from "@/app/[lng]/accounts/components/AccountSidebar/AccountSidebar";-// import { NoSSR } from "@kwooshung/react-no-ssr";-+'use client'+import type { EngagementPlatform, EngagementPostItem } from '@/api/types/engagement'+import { CommentOutlined, DollarOutlined, EyeOutlined, HistoryOutlined, LikeOutlined, PlayCircleOutlined, RobotOutlined, WalletOutlined } from '@ant-design/icons'+import { Avatar, Button, Card, Input, List, message, Modal, Select, Space, Tag } from 'antd'+import { useParams, useRouter } from 'next/navigation'+import { useEffect, useRef, useState } from 'react'+import { useShallow } from 'zustand/react/shallow'+import { createAiReplyTask, getChatModels } from '@/api/ai'+import { apiGetCommentReplies, apiGetEngagementComments, apiGetEngagementnew, apiGetEngagementPosts, apiGetPostComments, apiPublishCommentReply, apiPublishPostComment, apiReplyEngagementComment } from '@/api/engagement'+import AccountSidebar from '@/app/[lng]/accounts/components/AccountSidebar/AccountSidebar'+import { useTransClient } from '@/app/i18n/client'+import WalletAccountSelect from '@/components/WalletAccountSelect'+import { useAccountStore } from '@/store/account'+import { useUserStore } from '@/store/user'+import { request } from '@/utils/request'+import styles from './interactive.module.css'+// import { NoSSR } from "@kwooshung/react-no-ssr";-const { Option } = Select;+const { Option } = Selectexport default function InteractivePage() {- const router = useRouter();- const { lng } = useParams();- const { userInfo, token } = useUserStore();- const { t } = useTransClient('interactive' as any);+ const router = useRouter()+ const { lng } = useParams()+ const { userInfo, token } = useUserStore()+ const { t } = useTransClient('interactive' as any)// 账户侧边栏相关const { accountInit, accountActive, setAccountActive } = useAccountStore(- useShallow((state) => ({+ useShallow(state => ({accountInit: state.accountInit,accountActive: state.accountActive,setAccountActive: state.setAccountActive,})),- );-+ )+// 互动帖子列表状态- const [posts, setPosts] = useState<EngagementPostItem[]>([]);- const [loading, setLoading] = useState(false);- const [pagination, setPagination] = useState({ current: 1, pageSize: 20, total: 0 });- const [hasMore, setHasMore] = useState(true);- const [platform, setPlatform] = useState<EngagementPlatform | undefined>(undefined);- const loadMoreRef = useRef<HTMLDivElement | null>(null);- const [postsCursor, setPostsCursor] = useState<{ before?: string; after?: string }>({});- const prevAccountIdRef = useRef<string | undefined>();+ const [posts, setPosts] = useState<EngagementPostItem[]>([])+ const [loading, setLoading] = useState(false)+ const [pagination, setPagination] = useState({ current: 1, pageSize: 20, total: 0 })+ const [hasMore, setHasMore] = useState(true)+ const [platform, setPlatform] = useState<EngagementPlatform | undefined>(undefined)+ const loadMoreRef = useRef<HTMLDivElement | null>(null)+ const [postsCursor, setPostsCursor] = useState<{ before?: string, after?: string }>({})+ const prevAccountIdRef = useRef<string | undefined>()// 评论状态- const [commentVisible, setCommentVisible] = useState(false);- const [commentLoading, setCommentLoading] = useState(false);- const [commentPost, setCommentPost] = useState<EngagementPostItem | null>(null);- const [comments, setComments] = useState<any[]>([]);- const [commentsCursor, setCommentsCursor] = useState<{ before?: string; after?: string } | undefined>();- const [commentsTotal, setCommentsTotal] = useState<number | undefined>(undefined);- const [replyText, setReplyText] = useState('');- const [replyTarget, setReplyTarget] = useState<any>(null);- const [sending, setSending] = useState(false);- const replyInputRef = useRef<any>(null);+ const [commentVisible, setCommentVisible] = useState(false)+ const [commentLoading, setCommentLoading] = useState(false)+ const [commentPost, setCommentPost] = useState<EngagementPostItem | null>(null)+ const [comments, setComments] = useState<any[]>([])+ const [commentsCursor, setCommentsCursor] = useState<{ before?: string, after?: string } | undefined>()+ const [commentsTotal, setCommentsTotal] = useState<number | undefined>(undefined)+ const [replyText, setReplyText] = useState('')+ const [replyTarget, setReplyTarget] = useState<any>(null)+ const [sending, setSending] = useState(false)+ const replyInputRef = useRef<any>(null)// 二级回复:按评论ID存储- const [repliesByComment, setRepliesByComment] = useState<Record<string, { list: any[]; cursor?: { before?: string; after?: string }; loading: boolean; expanded: boolean }>>({});-+ const [repliesByComment, setRepliesByComment] = useState<Record<string, { list: any[], cursor?: { before?: string, after?: string }, loading: boolean, expanded: boolean }>>({})+// AI回复相关状态- const [aiModalVisible, setAiModalVisible] = useState(false);- const [aiPrompt, setAiPrompt] = useState('');- const [aiModel, setAiModel] = useState('');- const [aiModels, setAiModels] = useState<any[]>([]);- const [aiLoading, setAiLoading] = useState(false);- const [aiReplyTarget, setAiReplyTarget] = useState<{ postId: string; commentId?: string } | null>(null);- const [aiSuggestLoading, setAiSuggestLoading] = useState(false);+ const [aiModalVisible, setAiModalVisible] = useState(false)+ const [aiPrompt, setAiPrompt] = useState('')+ const [aiModel, setAiModel] = useState('')+ const [aiModels, setAiModels] = useState<any[]>([])+ const [aiLoading, setAiLoading] = useState(false)+ const [aiReplyTarget, setAiReplyTarget] = useState<{ postId: string, commentId?: string } | null>(null)+ const [aiSuggestLoading, setAiSuggestLoading] = useState(false)// 获取AI模型列表const fetchAiModels = async () => {try {- const res = await getChatModels();+ const res = await getChatModels()if (res?.data && Array.isArray(res.data)) {- setAiModels(res.data);+ setAiModels(res.data)if (res.data.length > 0 && !aiModel) {- setAiModel(res.data[0].name);+ setAiModel(res.data[0].name)}}- } catch (error) {- console.error('获取AI模型列表失败:', error);}- };+ catch (error) {+ console.error('获取AI模型列表失败:', error)+ }+ }// 获取互动帖子const fetchEngagementPosts = async (direction?: 'next' | 'prev', customCursor?: string) => {- if (!accountActive?.uid || !platform) return;- setLoading(true);+ if (!accountActive?.uid || !platform)+ return+ setLoading(true)try {const params: any = {platform,accountId: accountActive.id,-- };-++ }+// 根据方向添加 cursor 参数if (direction === 'next' && customCursor) {- params.pagination.after = customCursor;- } else if (direction === 'prev' && postsCursor.before) {- params.pagination.before = postsCursor.before;+ params.pagination.after = customCursor+ }+ else if (direction === 'prev' && postsCursor.before) {+ params.pagination.before = postsCursor.before}-- const res = await apiGetEngagementnew(params);++ const res = await apiGetEngagementnew(params)if (res?.data) {- const list = res.data.posts || [];+ const list = res.data.posts || []// 首次加载或切换方向时替换,加载更多时追加if (direction === 'next') {- setPosts(prev => [...prev, ...list]);- } else if (direction === 'prev') {- setPosts(prev => [...list, ...prev]);- } else {- setPosts(list);+ setPosts(prev => [...prev, ...list])+ }+ else if (direction === 'prev') {+ setPosts(prev => [...list, ...prev])+ }+ else {+ setPosts(list)}-+// 更新 cursorif (res.data.cursor) {- setPostsCursor(res.data.cursor);+ setPostsCursor(res.data.cursor)// 判断是否还有更多内容- setHasMore(!!res.data.cursor.after);- } else {- setHasMore(false);+ setHasMore(!!res.data.cursor.after)+ }+ else {+ setHasMore(false)}}- } finally {- setLoading(false);}- };+ finally {+ setLoading(false)+ }+ }// 当切换账户或平台时加载数据useEffect(() => {// 如果没有选中账户,清空数据if (!accountActive) {- setPlatform(undefined);- setPosts([]);- setPostsCursor({});- setPagination((prev) => ({ ...prev, total: 0, current: 1 }));- setHasMore(false);- prevAccountIdRef.current = undefined;- return;+ setPlatform(undefined)+ setPosts([])+ setPostsCursor({})+ setPagination(prev => ({ ...prev, total: 0, current: 1 }))+ setHasMore(false)+ prevAccountIdRef.current = undefined+ return}-- const currentAccountId = accountActive.id;- const accountChanged = prevAccountIdRef.current !== currentAccountId;-++ const currentAccountId = accountActive.id+ const accountChanged = prevAccountIdRef.current !== currentAccountId+// 如果账户切换了,需要设置新的platformif (accountChanged) {- prevAccountIdRef.current = currentAccountId;-- const type = String((accountActive as any).type || '').toLowerCase();+ prevAccountIdRef.current = currentAccountId++ const type = String((accountActive as any).type || '').toLowerCase()const map: Record<string, EngagementPlatform> = {bilibili: 'bilibili',douyin: 'douyin',@@ -164,76 +169,78 @@ export default function InteractivePage() {xhs: 'xhs',redbook: 'xhs',youtube: 'youtube',- };- const mapped = map[type];-+ }+ const mapped = map[type]+// 重置数据- setPosts([]);- setPostsCursor({});- setPagination((prev) => ({ ...prev, total: 0, current: 1 }));-+ setPosts([])+ setPostsCursor({})+ setPagination(prev => ({ ...prev, total: 0, current: 1 }))+// 设置platform(会触发下面的加载逻辑)if (mapped) {- setHasMore(true);- setPlatform(mapped);- } else {- setHasMore(false);- setPlatform(undefined);+ setHasMore(true)+ setPlatform(mapped)}- return; // 等platform更新后再加载数据+ else {+ setHasMore(false)+ setPlatform(undefined)+ }+ return // 等platform更新后再加载数据}-+// 如果账户没变,但platform或uid变了,重新加载数据if (accountActive?.uid && platform) {- setPosts([]);- setPostsCursor({});- setHasMore(true);- fetchEngagementPosts();+ setPosts([])+ setPostsCursor({})+ setHasMore(true)+ fetchEngagementPosts()}- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [accountActive?.id, accountActive?.uid, platform]);+ }, [accountActive?.id, accountActive?.uid, platform])const PostCard = ({ item }: { item: EngagementPostItem }) => {- const [currentMediaIndex, setCurrentMediaIndex] = useState(0);- const medias = (item as any).medias || [];- const currentMedia = medias[currentMediaIndex];-+ const [currentMediaIndex, setCurrentMediaIndex] = useState(0)+ const medias = (item as any).medias || []+ const currentMedia = medias[currentMediaIndex]+// 处理媒体点击const handleMediaClick = (e: React.MouseEvent) => {if (medias.length > 1) {- e.preventDefault();- setCurrentMediaIndex((prev) => (prev + 1) % medias.length);+ e.preventDefault()+ setCurrentMediaIndex(prev => (prev + 1) % medias.length)}- };-+ }+// 显示视频预览模态框- const [videoModalVisible, setVideoModalVisible] = useState(false);- const [videoUrl, setVideoUrl] = useState('');-+ const [videoModalVisible, setVideoModalVisible] = useState(false)+ const [videoUrl, setVideoUrl] = useState('')+const handleVideoPlay = (e: React.MouseEvent) => {- e.preventDefault();+ e.preventDefault()if (currentMedia?.type === 'video' && currentMedia?.url) {- setVideoUrl(currentMedia.url);- setVideoModalVisible(true);+ setVideoUrl(currentMedia.url)+ setVideoModalVisible(true)}- };-+ }+return (<><div className={styles.postCard}><div className={styles.thumb} onClick={handleMediaClick} style={{ cursor: medias.length > 1 ? 'pointer' : 'default' }}>- {currentMedia?.thumbnail || currentMedia?.url ? (- <>- <img src={currentMedia.thumbnail || currentMedia.url} alt={item.title} />- {currentMedia.type === 'video' && (- <span className={styles.playIcon} onClick={handleVideoPlay}>- <PlayCircleOutlined style={{ fontSize: 40, color: 'rgba(255,255,255,0.95)' }} />- </span>+ {currentMedia?.thumbnail || currentMedia?.url+ ? (+ <>+ <img src={currentMedia.thumbnail || currentMedia.url} alt={item.title} />+ {currentMedia.type === 'video' && (+ <span className={styles.playIcon} onClick={handleVideoPlay}>+ <PlayCircleOutlined style={{ fontSize: 40, color: 'rgba(255,255,255,0.95)' }} />+ </span>+ )}+ </>+ )+ : (+ <div className={styles.thumbPlaceholder}>{t('ui.noImage')}</div>)}- </>- ) : (- <div className={styles.thumbPlaceholder}>{t('ui.noImage')}</div>- )}{medias.length > 0 && (<span className={styles.mediaType}><Tag color={currentMedia?.type === 'video' ? 'blue' : currentMedia?.type === 'image' ? 'green' : 'purple'}>@@ -252,9 +259,18 @@ export default function InteractivePage() {)}<div className={styles.postFooter}><div className={styles.statsRow}>- <span><LikeOutlined style={{ marginRight: 6 }} />{item.likeCount}</span>- <span><CommentOutlined style={{ marginRight: 6 }} />{item.commentCount}</span>- <span><EyeOutlined style={{ marginRight: 6 }} />{item.viewCount}</span>+ <span>+ <LikeOutlined style={{ marginRight: 6 }} />+ {item.likeCount}+ </span>+ <span>+ <CommentOutlined style={{ marginRight: 6 }} />+ {item.commentCount}+ </span>+ <span>+ <EyeOutlined style={{ marginRight: 6 }} />+ {item.viewCount}+ </span></div><Space size={8}><Button className={styles.commentBtn} type="text" onClick={() => openAiModal(item.id)}>@@ -267,7 +283,7 @@ export default function InteractivePage() {</div></div></div>-+{/* 视频播放模态框 */}<Modaltitle={t('ui.videoPreview' as any)}@@ -287,51 +303,54 @@ export default function InteractivePage() {)}</Modal></>- );- };+ )+ }const openComments = async (item: EngagementPostItem) => {- setCommentPost(item);- setComments([]);- setCommentVisible(true);- setReplyTarget(null);- await loadCommentsV2(item.id, undefined, undefined);- };+ setCommentPost(item)+ setComments([])+ setCommentVisible(true)+ setReplyTarget(null)+ await loadCommentsV2(item.id, undefined, undefined)+ }const loadCommentsV2 = async (postId: string, before?: string, after?: string) => {- if (!accountActive?.id || !platform) return;- setCommentLoading(true);+ if (!accountActive?.id || !platform)+ return+ setCommentLoading(true)try {const res = await apiGetPostComments({accountId: accountActive.id,platform: platform as any,postId,- pagination: { before, after, limit: 20 }- });+ pagination: { before, after, limit: 20 },+ })if (res?.data) {- const list = res.data.comments || [];- setComments((prev) => after || before ? [...prev, ...list] : list);- setCommentsTotal(res.data.total);- setCommentsCursor(res.data.cursor);+ const list = res.data.comments || []+ setComments(prev => after || before ? [...prev, ...list] : list)+ setCommentsTotal(res.data.total)+ setCommentsCursor(res.data.cursor)}- } finally {- setCommentLoading(false);}- };+ finally {+ setCommentLoading(false)+ }+ }const expandReplies = async (commentId: string) => {- if (!accountActive?.id || !platform) return;- setRepliesByComment((prev) => ({+ if (!accountActive?.id || !platform)+ return+ setRepliesByComment(prev => ({...prev,[commentId]: { ...(prev[commentId] || { list: [], cursor: {}, expanded: true }), loading: true, expanded: true },- }));+ }))const res = await apiGetCommentReplies({accountId: accountActive.id,platform: platform as any,commentId,pagination: { limit: 20 },- });- setRepliesByComment((prev) => ({+ })+ setRepliesByComment(prev => ({...prev,[commentId]: {list: res?.data?.comments || [],@@ -339,142 +358,154 @@ export default function InteractivePage() {loading: false,expanded: true,},- }));- };+ }))+ }const collapseReplies = (commentId: string) => {- setRepliesByComment((prev) => ({+ setRepliesByComment(prev => ({...prev,[commentId]: { ...(prev[commentId] || { list: [], cursor: {} }), expanded: false, loading: false },- }));- };+ }))+ }const loadMoreReplies = async (commentId: string) => {- const state = repliesByComment[commentId];- if (!state?.cursor?.after || !accountActive?.id || !platform) return;- setRepliesByComment((prev) => ({ ...prev, [commentId]: { ...(prev[commentId] as any), loading: true } }));+ const state = repliesByComment[commentId]+ if (!state?.cursor?.after || !accountActive?.id || !platform)+ return+ setRepliesByComment(prev => ({ ...prev, [commentId]: { ...(prev[commentId] as any), loading: true } }))const res = await apiGetCommentReplies({accountId: accountActive.id,platform: platform as any,commentId,pagination: { after: state.cursor.after, limit: 20 },- });- setRepliesByComment((prev) => ({+ })+ setRepliesByComment(prev => ({...prev,[commentId]: {- list: [ ...(prev[commentId]?.list || []), ...(res?.data?.comments || []) ],+ list: [...(prev[commentId]?.list || []), ...(res?.data?.comments || [])],cursor: res?.data?.cursor,loading: false,expanded: true,},- }));- };+ }))+ }/*** 提交帖子评论*/const submitPostComment = async () => {- if (!commentPost || !replyText.trim() || !accountActive?.id || !platform || sending) return;- setSending(true);+ if (!commentPost || !replyText.trim() || !accountActive?.id || !platform || sending)+ return+ setSending(true)try {- const res = await apiPublishPostComment({ accountId: accountActive.id, platform: platform as any, postId: commentPost.id, message: replyText.trim() });+ const res = await apiPublishPostComment({ accountId: accountActive.id, platform: platform as any, postId: commentPost.id, message: replyText.trim() })if (res) {- setReplyText('');- setReplyTarget(null);- await loadCommentsV2(commentPost.id);- message.success(t('messages.commentSuccess'));+ setReplyText('')+ setReplyTarget(null)+ await loadCommentsV2(commentPost.id)+ message.success(t('messages.commentSuccess'))}- } catch (error) {- message.error(t('messages.commentFailed'));- } finally {- setSending(false);}- };+ catch (error) {+ message.error(t('messages.commentFailed'))+ }+ finally {+ setSending(false)+ }+ }/*** 提交评论回复*/const submitReply = async (parentId?: string) => {- if (!commentPost || !replyText.trim() || !accountActive?.id || !platform || sending) return;- setSending(true);+ if (!commentPost || !replyText.trim() || !accountActive?.id || !platform || sending)+ return+ setSending(true)try {- const res = await apiPublishCommentReply({ accountId: accountActive.id, platform: platform as any, commentId: parentId || '', message: replyText.trim() });+ const res = await apiPublishCommentReply({ accountId: accountActive.id, platform: platform as any, commentId: parentId || '', message: replyText.trim() })if (res) {- setReplyText('');- setReplyTarget(null);- await loadCommentsV2(commentPost.id);- message.success(t('messages.replySuccess'));+ setReplyText('')+ setReplyTarget(null)+ await loadCommentsV2(commentPost.id)+ message.success(t('messages.replySuccess'))}- } catch (error) {- message.error(t('messages.replyFailed'));- } finally {- setSending(false);}- };+ catch (error) {+ message.error(t('messages.replyFailed'))+ }+ finally {+ setSending(false)+ }+ }/*** 打开AI回复弹窗*/const openAiModal = (postId: string, commentId?: string) => {- setAiReplyTarget({ postId, commentId });- setAiModalVisible(true);- setAiPrompt('');+ setAiReplyTarget({ postId, commentId })+ setAiModalVisible(true)+ setAiPrompt('')if (aiModels.length === 0) {- fetchAiModels();+ fetchAiModels()}- };+ }/*** 提交AI回复*/const submitAiReply = async () => {- if (!aiReplyTarget || !aiPrompt.trim() || !aiModel || !accountActive?.id || !platform || aiLoading) return;- setAiLoading(true);+ if (!aiReplyTarget || !aiPrompt.trim() || !aiModel || !accountActive?.id || !platform || aiLoading)+ return+ setAiLoading(true)try {const res = await createAiReplyTask({accountId: accountActive.id,postId: aiReplyTarget.postId,prompt: aiPrompt.trim(),platform: platform as string,- model: aiModel- });+ model: aiModel,+ })if (res) {- setAiModalVisible(false);- setAiPrompt('');- setAiReplyTarget(null);- message.success(t('messages.aiReplyTaskCreated'));+ setAiModalVisible(false)+ setAiPrompt('')+ setAiReplyTarget(null)+ message.success(t('messages.aiReplyTaskCreated'))// 刷新评论列表if (commentPost) {- await loadCommentsV2(commentPost.id);+ await loadCommentsV2(commentPost.id)}}- } catch (error) {- message.error(t('messages.aiReplyTaskFailed'));- } finally {- setAiLoading(false);}- };+ catch (error) {+ message.error(t('messages.aiReplyTaskFailed'))+ }+ finally {+ setAiLoading(false)+ }+ }// 获取AI评论建议,并填充到输入框const fetchAiSuggestion = async () => {if (!replyTarget || !replyTarget.id || !replyTarget.text) {- message.warning(t('ui.reply') as any);- return;+ message.warning(t('ui.reply') as any)+ return}try {- setAiSuggestLoading(true);+ setAiSuggestLoading(true)// 选择模型:优先取用户配置的 aiInfo.agent.defaultModel;否则取聊天模型列表第一个- let modelName: string | undefined = (userInfo as any)?.aiInfo?.agent?.defaultModel;+ let modelName: string | undefined = (userInfo as any)?.aiInfo?.agent?.defaultModelif (!modelName) {try {if (aiModels.length > 0) {- modelName = aiModels[0]?.name;- } else {- const listRes = await getChatModels();- const list = (listRes?.data as any[]) || [];- modelName = list[0]?.name;+ modelName = aiModels[0]?.name}- } catch {}+ else {+ const listRes = await getChatModels()+ const list = (listRes?.data as any[]) || []+ modelName = list[0]?.name+ }+ }+ catch {}}const res: any = await request({url: 'channel/engagement/comment/ai/replies',@@ -482,307 +513,325 @@ export default function InteractivePage() {data: {model: modelName || 'gpt-5',prompt: '',- comments: [{+ comments: [{id: replyTarget.id,- comment: replyTarget.text+ comment: replyTarget.text,}],},- });- const objjs = res?.data || {};- const content = objjs?.[replyTarget.id] || objjs?.text;+ })+ const objjs = res?.data || {}+ const content = objjs?.[replyTarget.id] || objjs?.textif (content) {- setReplyText(content);- setTimeout(() => replyInputRef.current?.focus?.(), 0);- } else {- message.warning(t('ui.noContent' as any) || '暂无AI建议');+ setReplyText(content)+ setTimeout(() => replyInputRef.current?.focus?.(), 0)+ }+ else {+ message.warning(t('ui.noContent' as any) || '暂无AI建议')}- } catch (e) {- message.error(t('ui.requestFailed' as any) || '请求失败');- } finally {- setAiSuggestLoading(false);}- };--+ catch (e) {+ message.error(t('ui.requestFailed' as any) || '请求失败')+ }+ finally {+ setAiSuggestLoading(false)+ }+ }// 删除收入/提现相关列定义(本页不需要)useEffect(() => {if (!token) {- message.error(t('messages.pleaseLoginFirst'));- router.push('/login');- return;+ message.error(t('messages.pleaseLoginFirst'))+ router.push('/login')+ return}-+// 初始化账户- accountInit();- }, [token, router]);+ accountInit()+ }, [token, router])// 底部自动加载更多(IntersectionObserver)useEffect(() => {- if (!loadMoreRef.current) return;- const el = loadMoreRef.current;+ if (!loadMoreRef.current)+ return+ const el = loadMoreRef.currentconst io = new IntersectionObserver((entries) => {- const first = entries[0];+ const first = entries[0]if (first.isIntersecting && hasMore && !loading && postsCursor.after) {- fetchEngagementPosts('next', postsCursor.after);+ fetchEngagementPosts('next', postsCursor.after)}- }, { rootMargin: '200px' });- io.observe(el);- return () => io.disconnect();- }, [loadMoreRef.current, hasMore, loading, postsCursor.after]);+ }, { rootMargin: '200px' })+ io.observe(el)+ return () => io.disconnect()+ }, [loadMoreRef.current, hasMore, loading, postsCursor.after])return (<>- <div className={styles.container} style={{ display: 'flex', gap: 16 }}>- {/* 左侧账户选择栏 */}- <div >- <AccountSidebar- activeAccountId={accountActive?.id || ''}- onAccountChange={(account) => {- if (account.id === accountActive?.id) {- setAccountActive(undefined);- } else {- setAccountActive(account);- }- }}- isInteractivePage={true}- />- </div>+ <div className={styles.container} style={{ display: 'flex', gap: 16 }}>+ {/* 左侧账户选择栏 */}+ <div>+ <AccountSidebar+ activeAccountId={accountActive?.id || ''}+ onAccountChange={(account) => {+ if (account.id === accountActive?.id) {+ setAccountActive(undefined)+ }+ else {+ setAccountActive(account)+ }+ }}+ isInteractivePage={true}+ />+ </div>- {/* 右侧内容 */}- <div style={{ flex: 1, minWidth: 0, height: '100%', overflow: 'auto' }}>- {!accountActive?.uid ? (- <Card style={{ height: '100%', minHeight: 360, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>- <div style={{ textAlign: 'center', maxWidth: 520 }}>- <div style={{- width: 72, height: 72, borderRadius: 16, border: '1px solid #e5e7eb',- display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16- }}>- <CommentOutlined style={{ fontSize: 36, color: '#9ca3af' }} />+ {/* 右侧内容 */}+ <div style={{ flex: 1, minWidth: 0, height: '100%', overflow: 'auto' }}>+ {!accountActive?.uid ? (+ <Card style={{ height: '100%', minHeight: 360, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>+ <div style={{ textAlign: 'center', maxWidth: 520 }}>+ <div style={{+ width: 72,+ height: 72,+ borderRadius: 16,+ border: '1px solid #e5e7eb',+ display: 'inline-flex',+ alignItems: 'center',+ justifyContent: 'center',+ marginBottom: 16,+ }}+ >+ <CommentOutlined style={{ fontSize: 36, color: '#9ca3af' }} />+ </div>+ <div style={{ fontSize: 18, fontWeight: 600, color: '#111827', marginBottom: 8 }}>{t('ui.selectChannel')}</div>+ <div style={{ color: '#6b7280' }}>{t('ui.selectChannelDesc')}</div>+ </div>+ </Card>+ ) : (+ /* 主要内容:互动帖子卡片瀑布流 */+ <div className={styles.content}>+ <div className={styles.grid}>+ {posts.map(item => (+ <PostCard key={`${item.id}`} item={item} />+ ))}+ </div>+ <div style={{ display: 'flex', justifyContent: 'center', marginTop: 12 }}>+ {hasMore && postsCursor.after+ ? (+ <Button+ loading={loading}+ onClick={() => fetchEngagementPosts('next', postsCursor.after)}+ disabled={loading}+ >+ {t('ui.loadMore')}+ </Button>+ )+ : posts.length > 0+ ? (+ <span style={{ color: '#999' }}>{t('ui.noMorePosts')}</span>+ )+ : null}+ </div>+ <div ref={loadMoreRef} style={{ height: 1 }} /></div>- <div style={{ fontSize: 18, fontWeight: 600, color: '#111827', marginBottom: 8 }}>{t('ui.selectChannel')}</div>- <div style={{ color: '#6b7280' }}>{t('ui.selectChannelDesc')}</div>- </div>- </Card>- ) : (- /* 主要内容:互动帖子卡片瀑布流 */- <div className={styles.content}>- <div className={styles.grid}>- {posts.map((item) => (- <PostCard key={`${item.id}`} item={item} />- ))}- </div>- <div style={{ display: 'flex', justifyContent: 'center', marginTop: 12 }}>- {hasMore && postsCursor.after ? (- <Button- loading={loading}- onClick={() => fetchEngagementPosts('next', postsCursor.after)}- disabled={loading}- >- {t('ui.loadMore')}- </Button>- ) : posts.length > 0 ? (- <span style={{ color: '#999' }}>{t('ui.noMorePosts')}</span>- ) : null}+ )}</div>- <div ref={loadMoreRef} style={{ height: 1 }} />- </div>- )}- </div>- {/* 评论弹窗 */}- <Modal- open={commentVisible}- onCancel={() => setCommentVisible(false)}- title={commentPost?.title || t('ui.reply')}- footer={null}- width={600}+ {/* 评论弹窗 */}+ <Modal+ open={commentVisible}+ onCancel={() => setCommentVisible(false)}+ title={commentPost?.title || t('ui.reply')}+ footer={null}+ width={600}// height={600}// style={{ maxHeight: '80vh' }}- >- <List- itemLayout="vertical"- loading={commentLoading}- dataSource={comments}- style={{ maxHeight: '600px', overflow: 'auto' }}- renderItem={(c: any) => {- const canExpand = !!c.hasReplies;- const replyState = repliesByComment[c.id];- const expanded = !!replyState?.expanded;- return (- <List.Item- style={{ alignItems: 'flex-start' }}- actions={[- canExpand && !expanded ? (- <a key="expand" onClick={() => expandReplies(c.id)}>{t('ui.expandReplies')}</a>- ) : canExpand && expanded ? (- <a key="collapse" onClick={() => collapseReplies(c.id)}>{t('ui.collapseReplies')}</a>- ) : null,+ >+ <List+ itemLayout="vertical"+ loading={commentLoading}+ dataSource={comments}+ style={{ maxHeight: '600px', overflow: 'auto' }}+ renderItem={(c: any) => {+ const canExpand = !!c.hasReplies+ const replyState = repliesByComment[c.id]+ const expanded = !!replyState?.expanded+ return (+ <List.Item+ style={{ alignItems: 'flex-start' }}+ actions={[+ canExpand && !expanded+ ? (+ <a key="expand" onClick={() => expandReplies(c.id)}>{t('ui.expandReplies')}</a>+ )+ : canExpand && expanded+ ? (+ <a key="collapse" onClick={() => collapseReplies(c.id)}>{t('ui.collapseReplies')}</a>+ )+ : null,// <a// key="ai-reply"// onClick={() => openAiModal(commentPost!.id, c.id)}// >// AI回复// </a>,- ].filter(Boolean)}- >- <List.Item.Meta- avatar={- c.author?.avatar && (- <Avatar src={c.author.avatar} />- )- }- title={<span style={{ fontSize: '15px', fontWeight: 500 }}>{c.author?.username || c.author?.name}</span>}- description={- <div style={{display: 'flex', flexDirection:'row', justifyContent:'space-between', alignItems: 'flex-start'}}>- <div>- <span style={{ fontSize: '14px', color: '#333' }}>{c.message}</span>- <a- style={{ marginLeft: '12px', fontSize: '12px', color: '#a66ae4', cursor: 'pointer' }}- onClick={() => {- const name = c.author?.username || c.author?.name || c.author?.id || '';- setReplyTarget({ id: c.id, name, text: c.message });- setTimeout(() => replyInputRef.current?.focus?.(), 0);- }}- >- {t('ui.reply')}- </a>+ ].filter(Boolean)}+ >+ <List.Item.Meta+ avatar={+ c.author?.avatar && (+ <Avatar src={c.author.avatar} />+ )+ }+ title={<span style={{ fontSize: '15px', fontWeight: 500 }}>{c.author?.username || c.author?.name}</span>}+ description={(+ <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start' }}>+ <div>+ <span style={{ fontSize: '14px', color: '#333' }}>{c.message}</span>+ <a+ style={{ marginLeft: '12px', fontSize: '12px', color: '#a66ae4', cursor: 'pointer' }}+ onClick={() => {+ const name = c.author?.username || c.author?.name || c.author?.id || ''+ setReplyTarget({ id: c.id, name, text: c.message })+ setTimeout(() => replyInputRef.current?.focus?.(), 0)+ }}+ >+ {t('ui.reply')}+ </a>+ </div>+ <span style={{ fontSize: '12px', color: '#999', marginTop: '4px', whiteSpace: 'nowrap', marginLeft: '12px' }}>+ {new Date(c.createdAt).toLocaleString()}+ </span>+ </div>+ )}+ />+ {expanded && (+ <div className={styles.replyBlock}>+ <List+ size="small"+ itemLayout="vertical"+ dataSource={replyState?.list || []}+ loading={replyState?.loading}+ renderItem={(r: any) => (+ <List.Item style={{ padding: '4px 0' }}>+ <List.Item.Meta+ avatar={+ r.author?.avatar && (+ <Avatar src={r.author.avatar} />+ )+ }+ title={<span style={{ fontSize: '14px', fontWeight: 500 }}>{r.author?.username || r.author?.name}</span>}+ description={(+ <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start' }}>+ <span style={{ fontSize: '14px', color: '#333' }}>{r.message}</span>+ <span style={{ fontSize: '12px', color: '#999', whiteSpace: 'nowrap', marginLeft: '12px' }}>+ {new Date(r.createdAt).toLocaleString()}+ </span>+ </div>+ )}+ />+ </List.Item>+ )}+ />+ <div style={{ display: 'flex', justifyContent: 'flex-start', paddingLeft: 0 }}>+ <Button style={{ paddingLeft: 0 }} size="small" type="link" onClick={() => loadMoreReplies(c.id)} disabled={!replyState?.cursor?.after} loading={replyState?.loading}>+ {t('ui.loadMoreReplies')}+ </Button></div>- <span style={{ fontSize: '12px', color: '#999', marginTop: '4px', whiteSpace: 'nowrap', marginLeft: '12px' }}>- {new Date(c.createdAt).toLocaleString()}- </span>- </div>- }- />- {expanded && (- <div className={styles.replyBlock}>- <List- size="small"- itemLayout="vertical"- dataSource={replyState?.list || []}- loading={replyState?.loading}- renderItem={(r: any) => (- <List.Item style={{ padding: '4px 0' }}>- <List.Item.Meta- avatar={- r.author?.avatar && (- <Avatar src={r.author.avatar} />- )- }- title={<span style={{ fontSize: '14px', fontWeight: 500 }}>{r.author?.username || r.author?.name}</span>}- description={- <div style={{display: 'flex', flexDirection:'row', justifyContent:'space-between', alignItems: 'flex-start'}}>- <span style={{ fontSize: '14px', color: '#333' }}>{r.message}</span>- <span style={{ fontSize: '12px', color: '#999', whiteSpace: 'nowrap', marginLeft: '12px' }}>- {new Date(r.createdAt).toLocaleString()}- </span>- </div>- }- />- </List.Item>- )}- />- <div style={{ display: 'flex', justifyContent: 'flex-start', paddingLeft: 0 }}>- <Button style={{ paddingLeft: 0 }} size="small" type="link" onClick={() => loadMoreReplies(c.id)} disabled={!replyState?.cursor?.after} loading={replyState?.loading}>- {t('ui.loadMoreReplies')}- </Button></div>- </div>- )}- </List.Item>- );- }}- />- {commentsCursor?.after && (- <div- style={{ textAlign: 'center', marginTop: 10, color: '#1677ff', cursor: 'pointer' }}- onClick={() => !commentLoading && loadCommentsV2(commentPost!.id, undefined, commentsCursor?.after)}- >- {commentLoading ? t('ui.loading') : t('ui.loadMoreComments')}+ )}+ </List.Item>+ )+ }}+ />+ {commentsCursor?.after && (+ <div+ style={{ textAlign: 'center', marginTop: 10, color: '#1677ff', cursor: 'pointer' }}+ onClick={() => !commentLoading && loadCommentsV2(commentPost!.id, undefined, commentsCursor?.after)}+ >+ {commentLoading ? t('ui.loading') : t('ui.loadMoreComments')}+ </div>+ )}+ <div style={{ display: 'flex', gap: 8, marginTop: 12, paddingBottom: 20 }}>+ <div style={{ flex: 1, position: 'relative' }}>+ <Input+ style={{ paddingRight: 30 }}+ ref={replyInputRef}+ value={replyText}+ onChange={e => setReplyText(e.target.value)}+ placeholder={replyTarget ? `${t('ui.replyPlaceholder')}${replyTarget.name} - ${replyTarget.text.substring(0, 50)}${replyTarget.text.length > 50 ? '...' : ''}` : t('ui.commentPlaceholder')}+ />+ <Button+ type="text"+ onClick={fetchAiSuggestion}+ loading={aiSuggestLoading}+ style={{ position: 'absolute', right: 6, top: 1, padding: 4 }}+ title={t('ui.aiSuggest' as any) || 'AI建议'}+ disabled={!replyTarget}+ >+ <RobotOutlined style={{ fontSize: 18 }} />+ </Button>+ </div>++ <Button+ type="primary"+ loading={sending}+ disabled={sending || !replyText.trim()}+ onClick={() => (replyTarget ? submitReply(replyTarget.id) : submitPostComment())}+ style={{ width: 88, minWidth: 88 }}+ >+ {sending ? t('ui.sending') : t('ui.send')}+ </Button>+ </div>+ </Modal>++ {/* AI回复弹窗 */}+ <Modal+ open={aiModalVisible}+ onCancel={() => setAiModalVisible(false)}+ title={t('ui.aiReplyModalTitle')}+ footer={null}+ width={500}+ >+ <div style={{ marginBottom: 16 }}>+ <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>{t('ui.selectAiModel')}</label>+ <Select+ value={aiModel}+ onChange={setAiModel}+ style={{ width: '100%' }}+ placeholder={t('ui.aiModelPlaceholder')}+ loading={aiModels.length === 0}+ >+ {aiModels.map(model => (+ <Option key={model.name} value={model.name}>+ {model.description}+ </Option>+ ))}+ </Select></div>- )}- <div style={{ display: 'flex', gap: 8, marginTop: 12, paddingBottom: 20 }}>- <div style={{ flex: 1, position: 'relative'}}>- <Input- style={{ paddingRight: 30 }}- ref={replyInputRef}- value={replyText}- onChange={(e) => setReplyText(e.target.value)}- placeholder={replyTarget ? `${t('ui.replyPlaceholder')}${replyTarget.name} - ${replyTarget.text.substring(0, 50)}${replyTarget.text.length > 50 ? '...' : ''}` : t('ui.commentPlaceholder')}+ <div style={{ marginBottom: 16 }}>+ <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>{t('ui.replyPrompt')}</label>+ <Input.TextArea+ value={aiPrompt}+ onChange={e => setAiPrompt(e.target.value)}+ rows={4}+ placeholder={t('ui.promptPlaceholder')}/>- <Button- type="text"- onClick={fetchAiSuggestion}- loading={aiSuggestLoading}- style={{ position: 'absolute', right: 6, top: 1, padding: 4 }}- title={t('ui.aiSuggest' as any) || 'AI建议'}- disabled={!replyTarget}+ </div>+ <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>+ <Button onClick={() => setAiModalVisible(false)}>+ {t('ui.cancel')}+ </Button>+ <Button+ type="primary"+ loading={aiLoading}+ disabled={!aiPrompt.trim() || !aiModel || aiLoading}+ onClick={submitAiReply}>- <RobotOutlined style={{ fontSize: 18 }} />+ {aiLoading ? t('ui.creating') : t('ui.createAiReplyTask')}</Button></div>-- <Button- type="primary"- loading={sending}- disabled={sending || !replyText.trim()}- onClick={() => (replyTarget ? submitReply(replyTarget.id) : submitPostComment())}- style={{ width: 88, minWidth: 88 }}- >- {sending ? t('ui.sending') : t('ui.send')}- </Button>- </div>- </Modal>-- {/* AI回复弹窗 */}- <Modal- open={aiModalVisible}- onCancel={() => setAiModalVisible(false)}- title={t('ui.aiReplyModalTitle')}- footer={null}- width={500}- >- <div style={{ marginBottom: 16 }}>- <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>{t('ui.selectAiModel')}</label>- <Select- value={aiModel}- onChange={setAiModel}- style={{ width: '100%' }}- placeholder={t('ui.aiModelPlaceholder')}- loading={aiModels.length === 0}- >- {aiModels.map((model) => (- <Option key={model.name} value={model.name}>- {model.description}- </Option>- ))}- </Select>- </div>- <div style={{ marginBottom: 16 }}>- <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>{t('ui.replyPrompt')}</label>- <Input.TextArea- value={aiPrompt}- onChange={(e) => setAiPrompt(e.target.value)}- rows={4}- placeholder={t('ui.promptPlaceholder')}- />- </div>- <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>- <Button onClick={() => setAiModalVisible(false)}>- {t('ui.cancel')}- </Button>- <Button- type="primary"- loading={aiLoading}- disabled={!aiPrompt.trim() || !aiModel || aiLoading}- onClick={submitAiReply}- >- {aiLoading ? t('ui.creating') : t('ui.createAiReplyTask')}- </Button>- </div>- </Modal>- </div>+ </Modal>+ </div></>- );+ )}diff --git a/project/web/src/app/[lng]/layout.tsx b/project/web/src/app/[lng]/layout.tsxindex 5f7f81e5..f49a1225 100644--- a/project/web/src/app/[lng]/layout.tsx+++ b/project/web/src/app/[lng]/layout.tsx@@ -1,44 +1,45 @@-import "@/app/var.css";-import "../globals.css";-import { Providers } from "../layout/Providers";-import { dir } from "i18next";-import { languages, fallbackLng } from "@/app/i18n/settings";-import { useTranslation } from "@/app/i18n";-import ConditionalHeader from "../layout/ConditionalHeader";+import { dir } from 'i18next'+import { useTranslation } from '@/app/i18n'+import { fallbackLng, languages } from '@/app/i18n/settings'+import ConditionalHeader from '../layout/ConditionalHeader'+import { Providers } from '../layout/Providers'+import '@/app/var.css'+import '../globals.css'export async function generateMetadata({params,}: {- params: Promise<{ lng: string }>;+ params: Promise<{ lng: string }>}) {- let { lng } = await params;- if (languages.indexOf(lng) < 0) lng = fallbackLng;- const { t } = await useTranslation(lng);+ let { lng } = await params+ if (!languages.includes(lng))+ lng = fallbackLng+ const { t } = await useTranslation(lng)return {- title: t("title"),- description: t("content"),- keywords: "aitoearn, AiToEarn, ai, earn, aitoearn.com",- };+ title: t('title'),+ description: t('content'),+ keywords: 'aitoearn, AiToEarn, ai, earn, aitoearn.com',+ }}export default async function RootLayout({children,params,}: Readonly<{- children: React.ReactNode;- params: Promise<{ lng: string }>;+ children: React.ReactNode+ params: Promise<{ lng: string }>}>) {- const { lng } = await params;+ const { lng } = await paramsreturn (<html lang={lng} dir={dir(lng)}><body><Providers lng={lng}><divstyle={{- height: "100vh",- display: "flex",- flexDirection: "column",- minHeight: "0",+ height: '100vh',+ display: 'flex',+ flexDirection: 'column',+ minHeight: '0',}}><ConditionalHeader />@@ -47,5 +48,5 @@ export default async function RootLayout({</Providers></body></html>- );+ )}diff --git a/project/web/src/app/[lng]/login/login.module.css b/project/web/src/app/[lng]/login/login.module.cssindex cfcb409b..b5fa23b1 100644--- a/project/web/src/app/[lng]/login/login.module.css+++ b/project/web/src/app/[lng]/login/login.module.css@@ -211,4 +211,4 @@align-items: center;gap: 12px;}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/login/page.tsx b/project/web/src/app/[lng]/login/page.tsxindex cd9a236c..3f0e71d5 100644--- a/project/web/src/app/[lng]/login/page.tsx+++ b/project/web/src/app/[lng]/login/page.tsx@@ -1,114 +1,120 @@-"use client";+'use client'-import { useState, useEffect } from "react";-import Link from "next/link";-import { FcGoogle } from "react-icons/fc";-import { GoogleLogin } from "@react-oauth/google";-import { message, Modal, Form, Input, Button } from "antd";-import { useRouter } from "next/navigation";-import styles from "./login.module.css";-import {- loginWithMailApi,- getRegistUrlApi,- checkRegistStatusApi,- mailRegistApi,+import { GoogleLogin } from '@react-oauth/google'+import { Button, Form, Input, message, Modal } from 'antd'+import Link from 'next/link'+import { useRouter } from 'next/navigation'+import { useEffect, useState } from 'react'+import { FcGoogle } from 'react-icons/fc'+import {+ checkRegistStatusApi,+ getRegistUrlApi,googleLoginApi,- GoogleLoginParams-} from "@/api/apiReq";-import { useUserStore } from "@/store/user";-import { useTransClient } from "@/app/i18n/client";+ GoogleLoginParams,+ loginWithMailApi,+ mailRegistApi,+} from '@/api/apiReq'+import { useTransClient } from '@/app/i18n/client'+import { useUserStore } from '@/store/user'+import styles from './login.module.css'export default function LoginPage() {- const router = useRouter();- const { setToken, setUserInfo } = useUserStore();- const { t } = useTransClient("login");- const [email, setEmail] = useState("");- const [password, setPassword] = useState("");- const [isChecking, setIsChecking] = useState(false);- const [isModalOpen, setIsModalOpen] = useState(false);- const [registCode, setRegistCode] = useState("");- const [form] = Form.useForm();- const [isActivating, setIsActivating] = useState(false);- const [activationTimer, setActivationTimer] = useState<NodeJS.Timeout | null>(null);- const [registUrl, setRegistUrl] = useState("");- const [showRegistModal, setShowRegistModal] = useState(false);+ const router = useRouter()+ const { setToken, setUserInfo } = useUserStore()+ const { t } = useTransClient('login')+ const [email, setEmail] = useState('')+ const [password, setPassword] = useState('')+ const [isChecking, setIsChecking] = useState(false)+ const [isModalOpen, setIsModalOpen] = useState(false)+ const [registCode, setRegistCode] = useState('')+ const [form] = Form.useForm()+ const [isActivating, setIsActivating] = useState(false)+ const [activationTimer, setActivationTimer] = useState<NodeJS.Timeout | null>(null)+ const [registUrl, setRegistUrl] = useState('')+ const [showRegistModal, setShowRegistModal] = useState(false)const handleSubmit = async (e: React.FormEvent) => {- e.preventDefault();+ e.preventDefault()try {- const response = await loginWithMailApi({ mail: email, password });- if (!response) return;-+ const response = await loginWithMailApi({ mail: email, password })+ if (!response)+ return+if (response.code === 0) {if (response.data.type === 'regist') {// 用户未注册,显示弹窗提示,并设置表单的默认密码值- setRegistCode(response.data.code || '');- form.setFieldsValue({ password: password }); // 设置密码字段的默认值- setIsModalOpen(true);- setIsChecking(true);- } else if (response.data.token) {+ setRegistCode(response.data.code || '')+ form.setFieldsValue({ password }) // 设置密码字段的默认值+ setIsModalOpen(true)+ setIsChecking(true)+ }+ else if (response.data.token) {// 登录成功- setToken(response.data.token);+ setToken(response.data.token)if (response.data.userInfo) {- setUserInfo(response.data.userInfo);+ setUserInfo(response.data.userInfo)}- message.success(t('loginSuccess'));- router.push('/accounts');+ message.success(t('loginSuccess'))+ router.push('/accounts')}- } else {- message.error(response.message || t('loginFailed'));}- } catch (error) {- message.error(t('loginError'));+ else {+ message.error(response.message || t('loginFailed'))+ }}- };+ catch (error) {+ message.error(t('loginError'))+ }+ }- const handleRegistSubmit = async (values: { password: string; code: string; inviteCode?: string }) => {+ const handleRegistSubmit = async (values: { password: string, code: string, inviteCode?: string }) => {try {- setIsActivating(true);-+ setIsActivating(true)+const response = await mailRegistApi({mail: email,code: values.code,password: values.password,- inviteCode: values.inviteCode || ''- });-+ inviteCode: values.inviteCode || '',+ })+if (!response) {- message.error(t('registerError'));- setIsActivating(false);- return;+ message.error(t('registerError'))+ setIsActivating(false)+ return}-+if (response.code === 0 && response.data.token) {// 注册成功- setIsActivating(false);- setIsModalOpen(false);- form.resetFields(); // 重置表单- setToken(response.data.token);+ setIsActivating(false)+ setIsModalOpen(false)+ form.resetFields() // 重置表单+ setToken(response.data.token)if (response.data.userInfo) {- setUserInfo(response.data.userInfo);+ setUserInfo(response.data.userInfo)}- message.success(t('registerSuccess'));- router.push('/accounts');- } else {- message.error(response.message || t('registerError'));- setIsActivating(false);+ message.success(t('registerSuccess'))+ router.push('/accounts')}- } catch (error) {- message.error(t('registerError'));- setIsActivating(false);+ else {+ message.error(response.message || t('registerError'))+ setIsActivating(false)+ }+ }+ catch (error) {+ message.error(t('registerError'))+ setIsActivating(false)}- };+ }// 组件卸载时清除定时器useEffect(() => {return () => {if (activationTimer) {- clearInterval(activationTimer);+ clearInterval(activationTimer)}- };- }, [activationTimer]);+ }+ }, [activationTimer])const handleGoogleSuccess = async (credentialResponse: any) => {console.log('credentialResponse', credentialResponse)@@ -117,37 +123,39 @@ export default function LoginPage() {const params: any = {platform: 'google',clientId: credentialResponse.clientId,- credential: credentialResponse.credential- };+ credential: credentialResponse.credential,+ }- const response: any = await googleLoginApi(params);+ const response: any = await googleLoginApi(params)console.log('login response', response)if (!response) {- message.error(t('googleLoginFailed'));- return;+ message.error(t('googleLoginFailed'))+ return}if (response.code === 0) {if (response.data.type === 'login') {// 直接登录成功- setToken(response.data.token);+ setToken(response.data.token)if (response.data.userInfo) {- setUserInfo(response.data.userInfo);+ setUserInfo(response.data.userInfo)}- message.success(t('loginSuccess'));- router.push('/accounts');+ message.success(t('loginSuccess'))+ router.push('/accounts')}- } else {- message.error(response.message || t('googleLoginFailed'));}- } catch (error) {- message.error(t('googleLoginFailed'));+ else {+ message.error(response.message || t('googleLoginFailed'))+ }+ }+ catch (error) {+ message.error(t('googleLoginFailed'))}- };+ }const handleGoogleError = () => {- console.log(t('googleLoginFailed'));- };+ console.log(t('googleLoginFailed'))+ }return (<div className={styles.container}>@@ -159,7 +167,7 @@ export default function LoginPage() {type="email"placeholder={t('emailPlaceholder')}value={email}- onChange={(e) => setEmail(e.target.value)}+ onChange={e => setEmail(e.target.value)}className={styles.input}required/>@@ -169,7 +177,7 @@ export default function LoginPage() {type="password"placeholder={t('passwordPlaceholder')}value={password}- onChange={(e) => setPassword(e.target.value)}+ onChange={e => setPassword(e.target.value)}className={styles.input}required/>@@ -208,12 +216,12 @@ export default function LoginPage() {title={t('completeRegistration')}open={isModalOpen}onCancel={() => {- setIsModalOpen(false);- setIsChecking(false);- setIsActivating(false);- form.resetFields(); // 重置表单+ setIsModalOpen(false)+ setIsChecking(false)+ setIsActivating(false)+ form.resetFields() // 重置表单if (activationTimer) {- clearInterval(activationTimer);+ clearInterval(activationTimer)}}}maskClosable={false}@@ -232,23 +240,23 @@ export default function LoginPage() {name="code"rules={[{ required: true, message: t('emailCodeRequired') },- { len: 6, message: t('emailCodeLength') }+ { len: 6, message: t('emailCodeLength') },]}><Input placeholder={t('enterEmailCode')} maxLength={6} /></Form.Item>-+<Form.Itemlabel={t('setPassword')}name="password"rules={[{ required: true, message: t('passwordRequired') },- { min: 6, message: t('passwordMinLength') }+ { min: 6, message: t('passwordMinLength') },]}><Input.Password placeholder={t('enterPassword')} /></Form.Item>-+<Form.Itemlabel={t('inviteCode')}name="inviteCode"@@ -257,10 +265,10 @@ export default function LoginPage() {</Form.Item><Form.Item>- <Button- type="primary"- htmlType="submit"- block+ <Button+ type="primary"+ htmlType="submit"+ blockloading={isActivating}>{isActivating ? t('registering') : t('completeRegistration')}@@ -269,5 +277,5 @@ export default function LoginPage() {</Form></Modal></div>- );-}\ No newline at end of file+ )+}diff --git a/project/web/src/app/[lng]/material/ai-generate/ai-generate.module.scss b/project/web/src/app/[lng]/material/ai-generate/ai-generate.module.scssindex 05ddeea3..a3b2f085 100644--- a/project/web/src/app/[lng]/material/ai-generate/ai-generate.module.scss+++ b/project/web/src/app/[lng]/material/ai-generate/ai-generate.module.scss@@ -23,7 +23,7 @@overflow: hidden;position: relative;-+iframe {width: 100%;height: 100%;@@ -45,7 +45,7 @@margin-bottom: 24px;padding: 16px;background-color: #f8f9fa;-+box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);border: 1px solid rgba(0, 0, 0, 0.05);@@ -114,8 +114,8 @@.leftSidebar {background: #fff;- border: 1px solid rgba(0,0,0,0.06);-+ border: 1px solid rgba(0, 0, 0, 0.06);+display: flex;flex-direction: column;}@@ -134,26 +134,31 @@align-items: center;justify-content: center;cursor: pointer;- transition: all .2s ease;+ transition: all 0.2s ease;color: #666;:global {.anticon {font-size: 18px;color: inherit;- transition: color .2s ease;+ transition: color 0.2s ease;}}}-.moduleTab:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(0,0,0,.08); }+.moduleTab:hover {+ transform: translateY(-1px);+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);+}.moduleTabActive {/* 顶部图片/视频切换:更浅的选中底色,与下方子菜单区分 */- background: rgba(166,106,228,.1);+ background: rgba(166, 106, 228, 0.1);color: var(--theColor5);:global {- .anticon { color: var(--theColor5); }+ .anticon {+ color: var(--theColor5);+ }}}@@ -174,16 +179,21 @@align-items: center;justify-content: center;cursor: pointer;- transition: all .2s ease;+ transition: all 0.2s ease;padding: 6px 4px;}-.subTab:hover { background: #f0f1f3; }-.subTabActive { background: rgba(166,106,228,.3); color: var(--theColor5); border-color: transparent; }+.subTab:hover {+ background: #f0f1f3;+}+.subTabActive {+ background: rgba(166, 106, 228, 0.3);+ color: var(--theColor5);+ border-color: transparent;+}.rightContent {background: #f8f9fa;-}.tabs {@@ -227,71 +237,305 @@.section {padding: 20px;border: 1px solid rgba(0, 0, 0, 0.05);-+background-color: #fff;}// 新增:textToImage 左右分栏-.twoColumn { display: grid; grid-template-columns: 399px 1fr; gap: 16px; }-.leftPanel { display: flex; flex-direction: column; gap: 12px; }-.rightPanel {+.twoColumn {+ display: grid;+ grid-template-columns: 399px 1fr;+ gap: 16px;+}+.leftPanel {+ display: flex;+ flex-direction: column;+ gap: 12px;+}+.rightPanel {display: flex;flex-direction: column;}-.blockTitle { font-size: 14px; color: #999; }+.blockTitle {+ font-size: 14px;+ color: #999;+}-.modelList { display: flex; flex-direction: column; gap: 8px; }-.modelSelect { position: relative; }-.modelSelectBtn { width: 100%; display: flex; gap: 5px; align-items: center; padding: 10px; border: 1px solid rgba(0,0,0,.06); background: #fff; cursor: pointer; }-.modelCaret { margin-left: auto; color: #999; }-.modelDropdown { position: absolute; left: 0; right: 0; top: calc(100% + 6px); background: #fff; border: 1px solid rgba(0,0,0,.1); box-shadow: 0 8px 24px rgba(0,0,0,.08); z-index: 10; border-radius: 8px; }-.modelListScrollable { max-height: 340px; overflow: auto; padding: 8px; display: flex; flex-direction: column; gap: 8px; }+.modelList {+ display: flex;+ flex-direction: column;+ gap: 8px;+}+.modelSelect {+ position: relative;+}+.modelSelectBtn {+ width: 100%;+ display: flex;+ gap: 5px;+ align-items: center;+ padding: 10px;+ border: 1px solid rgba(0, 0, 0, 0.06);+ background: #fff;+ cursor: pointer;+}+.modelCaret {+ margin-left: auto;+ color: #999;+}+.modelDropdown {+ position: absolute;+ left: 0;+ right: 0;+ top: calc(100% + 6px);+ background: #fff;+ border: 1px solid rgba(0, 0, 0, 0.1);+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);+ z-index: 10;+ border-radius: 8px;+}+.modelListScrollable {+ max-height: 340px;+ overflow: auto;+ padding: 8px;+ display: flex;+ flex-direction: column;+ gap: 8px;+}.modelItem {- display: flex; gap: 10px; padding: 10px; border: 1px solid rgba(0,0,0,.06); background: #fafafa; cursor: pointer; transition: all .2s ease; border-radius: 5px;-}-.modelItem:hover { background: #f0f1f3; }-.modelItemActive { background: rgba(166,106,228,.12); border-color: rgba(166,106,228,.25); }-.modelIconSelect { width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; color: var(--theColor5); }-.modelIcon { height: 28px; display: flex; align-items: center; justify-content: center; color: var(--theColor5); }-.modelMain { flex: 1; display: flex; flex-direction: column; gap: 4px; align-items: flex-start; }-.modelHeader { display: flex; align-items: center; gap: 6px; }-.modelName { font-size: 14px; color: #333; font-weight: 600; line-height: 1; }-.modelTag { font-size: 11px; color: #fff; background: var(--theColor5); padding: 0px 6px; border-radius: 10px; line-height: 1.5; }-.modelDesc { font-size: 12px; color: #999; }-.modelMeta { font-size: 12px; color: #999; margin-top: 4px; }-.modelMeta span { margin-right: 6px; border: 1px solid #ccc; padding: 0px 6px; border-radius: 5px; line-height: 1.5; }--.exampleChips { display: flex; flex-wrap: wrap; gap: 8px; }-.exampleChip { padding: 4px 8px; border-radius: 12px; background: #f5f6f8; color: #555; cursor: pointer; }-.exampleChip:hover { background: #eef0f2; }--.pillRow { display: flex; flex-direction: column; gap: 6px; margin-top: 12px; }-.pillGroupBox { background: rgba(166,106,228,.08); border: 1px solid rgba(166,106,228,.15); border-radius: 10px; padding: 6px; }-.pillGroup { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; }-.pill { height: 36px; border-radius: 8px; background: #fff; border: 1px solid rgba(166,106,228,.2); color: var(--theColor5); cursor: pointer; transition: all .15s ease; }-.pill:hover { background: rgba(166,106,228,.12); }-.pillActive { background: var(--theColor5); color: #fff; border-color: transparent; }+ display: flex;+ gap: 10px;+ padding: 10px;+ border: 1px solid rgba(0, 0, 0, 0.06);+ background: #fafafa;+ cursor: pointer;+ transition: all 0.2s ease;+ border-radius: 5px;+}+.modelItem:hover {+ background: #f0f1f3;+}+.modelItemActive {+ background: rgba(166, 106, 228, 0.12);+ border-color: rgba(166, 106, 228, 0.25);+}+.modelIconSelect {+ width: 40px;+ height: 40px;+ display: flex;+ align-items: center;+ justify-content: center;+ color: var(--theColor5);+}+.modelIcon {+ height: 28px;+ display: flex;+ align-items: center;+ justify-content: center;+ color: var(--theColor5);+}+.modelMain {+ flex: 1;+ display: flex;+ flex-direction: column;+ gap: 4px;+ align-items: flex-start;+}+.modelHeader {+ display: flex;+ align-items: center;+ gap: 6px;+}+.modelName {+ font-size: 14px;+ color: #333;+ font-weight: 600;+ line-height: 1;+}+.modelTag {+ font-size: 11px;+ color: #fff;+ background: var(--theColor5);+ padding: 0px 6px;+ border-radius: 10px;+ line-height: 1.5;+}+.modelDesc {+ font-size: 12px;+ color: #999;+}+.modelMeta {+ font-size: 12px;+ color: #999;+ margin-top: 4px;+}+.modelMeta span {+ margin-right: 6px;+ border: 1px solid #ccc;+ padding: 0px 6px;+ border-radius: 5px;+ line-height: 1.5;+}++.exampleChips {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+}+.exampleChip {+ padding: 4px 8px;+ border-radius: 12px;+ background: #f5f6f8;+ color: #555;+ cursor: pointer;+}+.exampleChip:hover {+ background: #eef0f2;+}++.pillRow {+ display: flex;+ flex-direction: column;+ gap: 6px;+ margin-top: 12px;+}+.pillGroupBox {+ background: rgba(166, 106, 228, 0.08);+ border: 1px solid rgba(166, 106, 228, 0.15);+ border-radius: 10px;+ padding: 6px;+}+.pillGroup {+ display: grid;+ grid-template-columns: repeat(4, 1fr);+ gap: 10px;+}+.pill {+ height: 36px;+ border-radius: 8px;+ background: #fff;+ border: 1px solid rgba(166, 106, 228, 0.2);+ color: var(--theColor5);+ cursor: pointer;+ transition: all 0.15s ease;+}+.pill:hover {+ background: rgba(166, 106, 228, 0.12);+}+.pillActive {+ background: var(--theColor5);+ color: #fff;+ border-color: transparent;+}// 示例轮播-.sampleCarousel { width: 100%; height: 100%; display: flex; flex-direction: column; gap: 10px; align-items: center; justify-content: center; }-.sampleStage { position: relative; width: 100%; aspect-ratio: 16/10; background: #2a2a2a; border-radius: 8px; overflow: hidden; }-.sampleStage img { width: 100%; height: 100%; object-fit: cover; }-.samplePrev, .sampleNext { position: absolute; top: 50%; transform: translateY(-50%); width: 36px; height: 36px; border-radius: 18px; background: rgba(0,0,0,.4); color: #fff; border: none; cursor: pointer; }-.samplePrev { left: 10px; }-.sampleNext { right: 10px; }-.sampleDots { display: flex; gap: 6px; }-.sampleDot { width: 6px; height: 6px; border-radius: 3px; background: #c9c9c9; cursor: pointer; }-.sampleDotActive { background: var(--theColor5); }+.sampleCarousel {+ width: 100%;+ height: 100%;+ display: flex;+ flex-direction: column;+ gap: 10px;+ align-items: center;+ justify-content: center;+}+.sampleStage {+ position: relative;+ width: 100%;+ aspect-ratio: 16/10;+ background: #2a2a2a;+ border-radius: 8px;+ overflow: hidden;+}+.sampleStage img {+ width: 100%;+ height: 100%;+ object-fit: cover;+}+.samplePrev,+.sampleNext {+ position: absolute;+ top: 50%;+ transform: translateY(-50%);+ width: 36px;+ height: 36px;+ border-radius: 18px;+ background: rgba(0, 0, 0, 0.4);+ color: #fff;+ border: none;+ cursor: pointer;+}+.samplePrev {+ left: 10px;+}+.sampleNext {+ right: 10px;+}+.sampleDots {+ display: flex;+ gap: 6px;+}+.sampleDot {+ width: 6px;+ height: 6px;+ border-radius: 3px;+ background: #c9c9c9;+ cursor: pointer;+}+.sampleDotActive {+ background: var(--theColor5);+}// 视频首尾帧上传面板-.uploadPanel { flex-direction: row; align-items: center; gap: 12px; width: 100%; }-.uploadCard { flex: 1; height: 120px; padding: 10px 0; border: 1px dashed rgba(0,0,0,.15); border-radius: 8px; background: #fff; display: flex; align-items: center; justify-content: center; cursor: pointer; overflow: hidden; }-.uploadCard img { max-width: 100%; max-height: 100%; object-fit: cover; }-.uploadPlaceholder { display: flex; flex-direction: column; align-items: center; gap: 8px; color: #999; }-.uploadIcon { width: 28px; height: 28px; border-radius: 14px; background: rgba(166,106,228,.12); color: var(--theColor5); display: inline-flex; align-items: center; justify-content: center; font-weight: 600; }-.uploadText { font-size: 12px; color: #666; }-.swapIcon { color: #bbb; }+.uploadPanel {+ flex-direction: row;+ align-items: center;+ gap: 12px;+ width: 100%;+}+.uploadCard {+ flex: 1;+ height: 120px;+ padding: 10px 0;+ border: 1px dashed rgba(0, 0, 0, 0.15);+ border-radius: 8px;+ background: #fff;+ display: flex;+ align-items: center;+ justify-content: center;+ cursor: pointer;+ overflow: hidden;+}+.uploadCard img {+ max-width: 100%;+ max-height: 100%;+ object-fit: cover;+}+.uploadPlaceholder {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 8px;+ color: #999;+}+.uploadIcon {+ width: 28px;+ height: 28px;+ border-radius: 14px;+ background: rgba(166, 106, 228, 0.12);+ color: var(--theColor5);+ display: inline-flex;+ align-items: center;+ justify-content: center;+ font-weight: 600;+}+.uploadText {+ font-size: 12px;+ color: #666;+}+.swapIcon {+ color: #bbb;+}.form {display: flex;@@ -299,14 +543,16 @@gap: 16px;:global {- .ant-input, .ant-input-textarea {+ .ant-input,+ .ant-input-textarea {background-color: #fff;border: 1px solid rgba(0, 0, 0, 0.1);color: #333;border-radius: 8px;transition: all 0.3s ease;- &:hover, &:focus {+ &:hover,+ &:focus {border-color: var(--theColor5);box-shadow: 0 0 0 2px rgba(166, 106, 228, 0.2);}@@ -320,7 +566,8 @@border-radius: 8px;transition: all 0.3s ease;- &:hover, &:focus {+ &:hover,+ &:focus {border-color: var(--theColor5);box-shadow: 0 0 0 2px rgba(166, 106, 228, 0.2);}@@ -375,7 +622,7 @@gap: 6px;white-space: nowrap;}-.options label input[type="checkbox"] {+.options label input[type='checkbox'] {margin: 0;}@@ -384,7 +631,7 @@text-align: center;padding: 24px;background-color: #f8f9fa;-+animation: fadeIn 0.3s ease;border: 1px solid rgba(0, 0, 0, 0.05);@@ -404,7 +651,7 @@text-align: center;padding: 8px;border: 1px dashed rgba(0, 0, 0, 0.1);-+animation: fadeIn 0.3s ease;background-color: #fff;@@ -415,9 +662,26 @@}}-.imageCard { position: relative; width: 100%; border-radius: 8px; overflow: hidden; }-.imageCard img { width: 100%; height: 100%; max-height: 100vh; object-fit: cover; display: block; }-.imageActions { position: absolute; right: 8px; bottom: 8px; display: flex; gap: 6px; }+.imageCard {+ position: relative;+ width: 100%;+ border-radius: 8px;+ overflow: hidden;+}+.imageCard img {+ width: 100%;+ height: 100%;+ max-height: 100vh;+ object-fit: cover;+ display: block;+}+.imageActions {+ position: absolute;+ right: 8px;+ bottom: 8px;+ display: flex;+ gap: 6px;+}// 模板选择网格.templateGrid {@@ -439,13 +703,36 @@padding: 6px 10px;}-.templateCard:hover { border-color: var(--theColor5); box-shadow: 0 2px 10px rgba(166,106,228,.12); }-.templateCardActive { background: rgba(166,106,228,.12); border-color: var(--theColor5); }+.templateCard:hover {+ border-color: var(--theColor5);+ box-shadow: 0 2px 10px rgba(166, 106, 228, 0.12);+}+.templateCardActive {+ background: rgba(166, 106, 228, 0.12);+ border-color: var(--theColor5);+}-.templateThumb { width: 22px; height: 22px; border-radius: 4px; overflow: hidden; background: #f6f7f9; display: flex; align-items: center; justify-content: center; }-.templateThumb img { width: 100%; height: 100%; object-fit: cover; }+.templateThumb {+ width: 22px;+ height: 22px;+ border-radius: 4px;+ overflow: hidden;+ background: #f6f7f9;+ display: flex;+ align-items: center;+ justify-content: center;+}+.templateThumb img {+ width: 100%;+ height: 100%;+ object-fit: cover;+}-.templateLabel { font-size: 12px; color: #444; font-weight: 500; }+.templateLabel {+ font-size: 12px;+ color: #444;+ font-weight: 500;+}@keyframes fadeIn {from {@@ -480,8 +767,12 @@padding: 16px;}- .mainLayout { grid-template-columns: 1fr; }- .leftSidebar { flex-direction: row; }+ .mainLayout {+ grid-template-columns: 1fr;+ }+ .leftSidebar {+ flex-direction: row;+ }.tabs {:global {@@ -504,12 +795,12 @@.templateGrid {gap: 8px;-+.templateCard {width: 140px;}}-}+}// 图片要求提示样式.imageRequirements {@@ -572,13 +863,13 @@height: 80px;border-radius: 8px;border: 1px solid #e8e8e8;-+img {width: 100%;height: 100%;object-fit: cover;}-+.removeBtn {position: absolute;top: -6px;@@ -595,9 +886,9 @@display: flex;align-items: center;justify-content: center;- box-shadow: 0 2px 4px rgba(0,0,0,0.2);+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);transition: all 0.2s ease;-+&:hover {background-color: #ff7875;transform: scale(1.1);@@ -610,8 +901,8 @@border: none;cursor: pointer;text-decoration: underline;-+&:hover {color: #ff7875;}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/material/ai-generate/md2card.ts b/project/web/src/app/[lng]/material/ai-generate/md2card.tsindex d56d7dfc..fcc02f87 100644--- a/project/web/src/app/[lng]/material/ai-generate/md2card.ts+++ b/project/web/src/app/[lng]/material/ai-generate/md2card.ts@@ -1,9 +1,9 @@// md2card 模板类export interface Md2CardTemplate {- id: string;- nameCn: string;- nameEn: string;- preview: string;+ id: string+ nameCn: string+ nameEn: string+ preview: string}// md2card 模板列表@@ -26,12 +26,12 @@ export const md2CardTemplates: Md2CardTemplate[] = [{ id: 'typewriter', nameCn: '复古打字机', nameEn: 'Vintage Typewriter', preview: 'https://aitoearn.s3.ap-southeast-1.amazonaws.com/ai/images/md2card/mejypwo3-1755693735431_19p6s4.png' },{ id: 'watercolor', nameCn: '水彩艺术', nameEn: 'Watercolor Art', preview: 'https://aitoearn.s3.ap-southeast-1.amazonaws.com/ai/images/md2card/mejyqc5i-1755693755298_2kncmc.png' },{ id: 'traditional-chinese', nameCn: '中国传统', nameEn: 'Traditional Chinese', preview: 'https://aitoearn.s3.ap-southeast-1.amazonaws.com/ai/images/md2card/mejyqsuc-1755693777223_oa1j2.png' },- { id: 'fairytale', nameCn: '儿童童话', nameEn: "Children's Fairy Tale", preview: 'https://aitoearn.s3.ap-southeast-1.amazonaws.com/ai/images/md2card/mejyrimw-1755693810619_gm7tdq.png' },+ { id: 'fairytale', nameCn: '儿童童话', nameEn: 'Children\'s Fairy Tale', preview: 'https://aitoearn.s3.ap-southeast-1.amazonaws.com/ai/images/md2card/mejyrimw-1755693810619_gm7tdq.png' },{ id: 'business', nameCn: '商务简报', nameEn: 'Business Brief', preview: 'https://aitoearn.s3.ap-southeast-1.amazonaws.com/ai/images/md2card/mejyrzsx-1755693832927_ig6pam.png' },{ id: 'japanese-magazine', nameCn: '日本杂志', nameEn: 'Japanese Magazine', preview: 'https://aitoearn.s3.ap-southeast-1.amazonaws.com/ai/images/md2card/mejyslq2-1755693861264_767tr.png' },{ id: 'cyberpunk', nameCn: '赛博朋克', nameEn: 'Cyberpunk', preview: 'https://aitoearn.s3.ap-southeast-1.amazonaws.com/ai/images/md2card/mejyt0xp-1755693880945_yj6yts.png' },{ id: 'meadow-dawn', nameCn: '青野晨光', nameEn: 'meadow dawn', preview: 'https://aitoearn.s3.ap-southeast-1.amazonaws.com/ai/images/md2card/mejyte9q-1755693897993_t99xm.png' },-];+]// 默认的Markdown内容export const defaultMarkdown = `# Default Markdown@@ -51,5 +51,4 @@ This is a sample Markdown content. You can type the content you want to convert2. Choose a suitable theme3. Adjust parameter settings4. Click the generate button-`;-+`diff --git a/project/web/src/app/[lng]/material/ai-generate/page.tsx b/project/web/src/app/[lng]/material/ai-generate/page.tsxindex 9bdc8c7c..ea082f20 100644--- a/project/web/src/app/[lng]/material/ai-generate/page.tsx+++ b/project/web/src/app/[lng]/material/ai-generate/page.tsx@@ -1,22 +1,22 @@-"use client";--import { useState, useEffect, useRef, useMemo } from "react";-import { useParams, useRouter, useSearchParams } from "next/navigation";-import { message, Input, Button, Select, Row, Col, Modal, Progress } from "antd";-import { ArrowLeftOutlined, RobotOutlined, FireOutlined, PictureOutlined, FileTextOutlined, UploadOutlined, VideoCameraOutlined, DownloadOutlined, MessageOutlined } from "@ant-design/icons";-import styles from "./ai-generate.module.scss";-import { generateImage, generateFireflyCard, getImageGenerationModels, generateVideo, getVideoTaskStatus, getVideoGenerationModels, generateMd2Card, getVideoGenerations, getImageTaskStatus, editImage, getImageEditTaskStatus, getImageEditModels } from "@/api/ai";-import { getOssUrl } from "@/utils/oss";-import { uploadToOss } from "@/api/oss";-import { getMediaGroupList, createMedia } from "@/api/media";-import { useTransClient } from "@/app/i18n/client";-import { md2CardTemplates, defaultMarkdown } from "./md2card";-import Chat from "@/components/Chat";-import { OSS_URL } from "@/constant";-import VipContentModal from "@/components/modals/VipContentModal";--const { TextArea } = Input;-const { Option } = Select;+'use client'++import { ArrowLeftOutlined, DownloadOutlined, FileTextOutlined, FireOutlined, MessageOutlined, PictureOutlined, RobotOutlined, UploadOutlined, VideoCameraOutlined } from '@ant-design/icons'+import { Button, Col, Input, message, Modal, Progress, Row, Select } from 'antd'+import { useParams, useRouter, useSearchParams } from 'next/navigation'+import { useEffect, useMemo, useRef, useState } from 'react'+import { editImage, generateFireflyCard, generateImage, generateMd2Card, generateVideo, getImageEditModels, getImageEditTaskStatus, getImageGenerationModels, getImageTaskStatus, getVideoGenerationModels, getVideoGenerations, getVideoTaskStatus } from '@/api/ai'+import { createMedia, getMediaGroupList } from '@/api/media'+import { uploadToOss } from '@/api/oss'+import { useTransClient } from '@/app/i18n/client'+import Chat from '@/components/Chat'+import VipContentModal from '@/components/modals/VipContentModal'+import { OSS_URL } from '@/constant'+import { getOssUrl } from '@/utils/oss'+import styles from './ai-generate.module.scss'+import { defaultMarkdown, md2CardTemplates } from './md2card'++const { TextArea } = Input+const { Option } = Select// Sample image URL constantsconst SAMPLE_IMAGE_URLS = {@@ -24,10 +24,7 @@ const SAMPLE_IMAGE_URLS = {shili22: 'https://aitoearn.s3.ap-southeast-1.amazonaws.com/common/web/shili/image-ai-sample-2-2.jpeg',shili23: 'https://aitoearn.s3.ap-southeast-1.amazonaws.com/common/web/shili/image-ai-sample-2-3.jpeg',shili24: 'https://aitoearn.s3.ap-southeast-1.amazonaws.com/common/web/shili/image-ai-sample-2-4.jpeg',-};---+}/*** AI tool page (left-right layout)@@ -35,962 +32,1160 @@ const SAMPLE_IMAGE_URLS = {* - Right: Display corresponding functions based on module (reuse existing logic, no changes to interfaces and state flow)*/export default function AIGeneratePage() {- const params = useParams();- const router = useRouter();- const searchParams = useSearchParams();- const { t } = useTransClient("material");- const lng = (params as any).lng as string;- const isEnglishLang = typeof lng === "string" ? lng.toLowerCase().startsWith("en") : false;+ const params = useParams()+ const searchParams = useSearchParams()+ const { t } = useTransClient('material')+ const lng = (params as any).lng as string+ const isEnglishLang = typeof lng === 'string' ? lng.toLowerCase().startsWith('en') : false// Initialize module and sub-tabs based on URL- const queryTab = (searchParams.get("tab") || "").toString();- const initIsVideo = ["videoGeneration", "text2video", "image2video"].includes(queryTab);- const initImageTab = ["textToImage", "imageToImage", "textToFireflyCard", "md2card", "chat"].includes(queryTab) ? (queryTab as any) : "textToImage";- const initVideoTab = ["image2video"].includes(queryTab) ? (queryTab as any) : "text2video";+ const queryTab = (searchParams.get('tab') || '').toString()+ const initIsVideo = ['videoGeneration', 'text2video', 'image2video'].includes(queryTab)+ const initImageTab = ['textToImage', 'imageToImage', 'textToFireflyCard', 'md2card', 'chat'].includes(queryTab) ? (queryTab as any) : 'textToImage'+ const initVideoTab = ['image2video'].includes(queryTab) ? (queryTab as any) : 'text2video'// Left module switching- const [activeModule, setActiveModule] = useState<"image" | "video">(initIsVideo ? "video" : "image");+ const [activeModule, setActiveModule] = useState<'image' | 'video'>(initIsVideo ? 'video' : 'image')// Image sub-module switching- const [activeImageTab, setActiveImageTab] = useState<"textToImage" | "imageToImage" | "textToFireflyCard" | "md2card" | "chat">(initImageTab);+ const [activeImageTab, setActiveImageTab] = useState<'textToImage' | 'imageToImage' | 'textToFireflyCard' | 'md2card' | 'chat'>(initImageTab)// Video sub-module switching- const [activeVideoTab, setActiveVideoTab] = useState<"text2video" | "image2video">(initVideoTab);+ const [activeVideoTab, setActiveVideoTab] = useState<'text2video' | 'image2video'>(initVideoTab)- // VIP modal state- const [vipModalOpen, setVipModalOpen] = useState(false);+ // VIP modal state+ const [vipModalOpen, setVipModalOpen] = useState(false)// Text to image- const [prompt, setPrompt] = useState("");- const [size, setSize] = useState("1024x1024");- const [n, setN] = useState(1);- const [quality, setQuality] = useState<"standard" | "hd">("standard");- const [style, setStyle] = useState<"vivid" | "natural">("vivid");- const [model, setModel] = useState("");- const [loading, setLoading] = useState(false);- const [result, setResult] = useState<string[] | null>(null);- const [imageTaskId, setImageTaskId] = useState<string | null>(null);- const [imageStatus, setImageStatus] = useState<string>("");- const [imageProgress, setImageProgress] = useState(0);- const [checkingImageStatus, setCheckingImageStatus] = useState(false);+ const [prompt, setPrompt] = useState('')+ const [size, setSize] = useState('1024x1024')+ const [n, setN] = useState(1)+ const [quality, setQuality] = useState<'standard' | 'hd'>('standard')+ const [style, setStyle] = useState<'vivid' | 'natural'>('vivid')+ const [model, setModel] = useState('')+ const [loading, setLoading] = useState(false)+ const [result, setResult] = useState<string[] | null>(null)+ const [imageTaskId, setImageTaskId] = useState<string | null>(null)+ const [imageStatus, setImageStatus] = useState<string>('')+ const [imageProgress, setImageProgress] = useState(0)+ const [checkingImageStatus, setCheckingImageStatus] = useState(false)// Firefly card- const [content, setContent] = useState("");- const [title, setTitle] = useState("");- const [temp, setTemp] = useState("tempA");- const [loadingFirefly, setLoadingFirefly] = useState(false);- const [fireflyResult, setFireflyResult] = useState<string | null>(null);- const TEMPLATE_BASE = "https://aitoearn.s3.ap-southeast-1.amazonaws.com/common/firefly";+ const [content, setContent] = useState('')+ const [title, setTitle] = useState('')+ const [temp, setTemp] = useState('tempA')+ const [loadingFirefly, setLoadingFirefly] = useState(false)+ const [fireflyResult, setFireflyResult] = useState<string | null>(null)+ const TEMPLATE_BASE = 'https://aitoearn.s3.ap-southeast-1.amazonaws.com/common/firefly'const templateList = [- { key: "tempA", name: t("aiGenerate.templateA") },- { key: "tempB", name: t("aiGenerate.templateB") },- { key: "tempC", name: t("aiGenerate.templateC") },- { key: "tempJin", name: t("aiGenerate.templateJin") },- { key: "tempMemo", name: t("aiGenerate.templateMemo") },- { key: "tempEasy", name: t("aiGenerate.templateEasy") },- { key: "tempE", name: t("aiGenerate.templateE") },- { key: "tempWrite", name: t("aiGenerate.templateWrite") },- { key: "tempD", name: t("aiGenerate.templateD") },- ];+ { key: 'tempA', name: t('aiGenerate.templateA') },+ { key: 'tempB', name: t('aiGenerate.templateB') },+ { key: 'tempC', name: t('aiGenerate.templateC') },+ { key: 'tempJin', name: t('aiGenerate.templateJin') },+ { key: 'tempMemo', name: t('aiGenerate.templateMemo') },+ { key: 'tempEasy', name: t('aiGenerate.templateEasy') },+ { key: 'tempE', name: t('aiGenerate.templateE') },+ { key: 'tempWrite', name: t('aiGenerate.templateWrite') },+ { key: 'tempD', name: t('aiGenerate.templateD') },+ ]// Video generation- const [videoPrompt, setVideoPrompt] = useState("");- const [videoModel, setVideoModel] = useState("");- const [videoSize, setVideoSize] = useState("720p");- const [videoDuration, setVideoDuration] = useState(5);- const [videoMode, setVideoMode] = useState("text2video");- const [videoImage, setVideoImage] = useState("");- const [videoImageTail, setVideoImageTail] = useState("");- const [videoImages, setVideoImages] = useState<string[]>([]);- const [loadingVideo, setLoadingVideo] = useState(false);- const [videoTaskId, setVideoTaskId] = useState<string | null>(null);- const [videoStatus, setVideoStatus] = useState<string>("");- const [videoResult, setVideoResult] = useState<string | null>(null);- const [checkingStatus, setCheckingStatus] = useState(false);- const [videoProgress, setVideoProgress] = useState(0);+ const [videoPrompt, setVideoPrompt] = useState('')+ const [videoModel, setVideoModel] = useState('')+ const [videoSize, setVideoSize] = useState('720p')+ const [videoDuration, setVideoDuration] = useState(5)+ const [videoMode, setVideoMode] = useState('text2video')+ const [videoImage, setVideoImage] = useState('')+ const [videoImageTail, setVideoImageTail] = useState('')+ const [videoImages, setVideoImages] = useState<string[]>([])+ const [loadingVideo, setLoadingVideo] = useState(false)+ const [videoTaskId, setVideoTaskId] = useState<string | null>(null)+ const [videoStatus, setVideoStatus] = useState<string>('')+ const [videoResult, setVideoResult] = useState<string | null>(null)+ const [checkingStatus, setCheckingStatus] = useState(false)+ const [videoProgress, setVideoProgress] = useState(0)// Video history- const [videoHistory, setVideoHistory] = useState<any[]>([]);- const [loadingHistory, setLoadingHistory] = useState(false);- const [showHistory, setShowHistory] = useState(false);+ const [videoHistory, setVideoHistory] = useState<any[]>([])+ const [loadingHistory, setLoadingHistory] = useState(false)+ const [showHistory, setShowHistory] = useState(false)// First/tail frame upload- const firstFrameInputRef = useRef<HTMLInputElement | null>(null);- const tailFrameInputRef = useRef<HTMLInputElement | null>(null);- const [uploadingFirstFrame, setUploadingFirstFrame] = useState(false);- const [uploadingTailFrame, setUploadingTailFrame] = useState(false);- const MAX_IMAGE_SIZE = 30 * 1024 * 1024;+ const firstFrameInputRef = useRef<HTMLInputElement | null>(null)+ const tailFrameInputRef = useRef<HTMLInputElement | null>(null)+ const [uploadingFirstFrame, setUploadingFirstFrame] = useState(false)+ const [uploadingTailFrame, setUploadingTailFrame] = useState(false)+ const MAX_IMAGE_SIZE = 30 * 1024 * 1024const checkFileSize = (file: File) => {if (file.size > MAX_IMAGE_SIZE) {- message.error(`${t("aiGenerate.imageSizeLimit" as any)}: 30MB`);- return false;+ message.error(`${t('aiGenerate.imageSizeLimit' as any)}: 30MB`)+ return false}- return true;- };+ return true+ }const checkImageFormat = (file: File) => {- const allowed = ["image/jpeg", "image/jpg", "image/png", "image/webp"];+ const allowed = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp']if (!allowed.includes(file.type)) {- message.error(`${t("aiGenerate.imageFormatSupport" as any)}: JPG, PNG, WEBP`);- return false;+ message.error(`${t('aiGenerate.imageFormatSupport' as any)}: JPG, PNG, WEBP`)+ return false}- return true;- };- const handlePickFirstFrame = () => firstFrameInputRef.current?.click();- const handlePickTailFrame = () => tailFrameInputRef.current?.click();+ return true+ }+ const handlePickFirstFrame = () => firstFrameInputRef.current?.click()+ const handlePickTailFrame = () => tailFrameInputRef.current?.click()const handleFirstFrameChange = async (e: React.ChangeEvent<HTMLInputElement>) => {- const file = e.target.files && e.target.files[0];- if (!file) return;- if (!checkFileSize(file) || !checkImageFormat(file)) { if (e.target) e.target.value = ""; return; }- try { setUploadingFirstFrame(true); const key = await uploadToOss(file); setVideoImage(getOssUrl(key)); message.success(t("aiGenerate.uploadSuccess")); }- catch { message.error(t("aiGenerate.uploadFailed")); }- finally { setUploadingFirstFrame(false); if (e.target) e.target.value = ""; }- };+ const file = e.target.files && e.target.files[0]+ if (!file)+ return+ if (!checkFileSize(file) || !checkImageFormat(file)) {+ if (e.target)+ e.target.value = ''+ return+ }+ try {+ setUploadingFirstFrame(true)+ const key = await uploadToOss(file)+ setVideoImage(getOssUrl(key))+ message.success(t('aiGenerate.uploadSuccess'))+ }+ catch { message.error(t('aiGenerate.uploadFailed')) }+ finally {+ setUploadingFirstFrame(false)+ if (e.target)+ e.target.value = ''+ }+ }const handleTailFrameChange = async (e: React.ChangeEvent<HTMLInputElement>) => {- const file = e.target.files && e.target.files[0];- if (!file) return;- if (!checkFileSize(file) || !checkImageFormat(file)) { if (e.target) e.target.value = ""; return; }- try { setUploadingTailFrame(true); const key = await uploadToOss(file); setVideoImageTail(getOssUrl(key)); message.success(t("aiGenerate.uploadSuccess")); }- catch { message.error(t("aiGenerate.uploadFailed")); }- finally { setUploadingTailFrame(false); if (e.target) e.target.value = ""; }- };+ const file = e.target.files && e.target.files[0]+ if (!file)+ return+ if (!checkFileSize(file) || !checkImageFormat(file)) {+ if (e.target)+ e.target.value = ''+ return+ }+ try {+ setUploadingTailFrame(true)+ const key = await uploadToOss(file)+ setVideoImageTail(getOssUrl(key))+ message.success(t('aiGenerate.uploadSuccess'))+ }+ catch { message.error(t('aiGenerate.uploadFailed')) }+ finally {+ setUploadingTailFrame(false)+ if (e.target)+ e.target.value = ''+ }+ }// Multi-image upload handlingconst handleMultiImageChange = async (e: React.ChangeEvent<HTMLInputElement>) => {- const files = e.target.files;- if (!files || files.length === 0) return;-- const validFiles: File[] = [];+ const files = e.target.files+ if (!files || files.length === 0)+ return++ const validFiles: File[] = []for (let i = 0; i < files.length; i++) {- const file = files[i];+ const file = files[i]if (checkFileSize(file) && checkImageFormat(file)) {- validFiles.push(file);+ validFiles.push(file)}}-+if (validFiles.length === 0) {- if (e.target) e.target.value = "";- return;+ if (e.target)+ e.target.value = ''+ return}-+try {- setUploadingFirstFrame(true);- const uploadPromises = validFiles.map(file => uploadToOss(file));- const keys = await Promise.all(uploadPromises);- const urls = keys.map(key => getOssUrl(key));- setVideoImages(prev => [...prev, ...urls]);- message.success(`成功上传 ${validFiles.length} 张图片`);- } catch (error) {- message.error(t("aiGenerate.uploadFailed"));- } finally {- setUploadingFirstFrame(false);- if (e.target) e.target.value = "";- }- };+ setUploadingFirstFrame(true)+ const uploadPromises = validFiles.map(file => uploadToOss(file))+ const keys = await Promise.all(uploadPromises)+ const urls = keys.map(key => getOssUrl(key))+ setVideoImages(prev => [...prev, ...urls])+ message.success(`成功上传 ${validFiles.length} 张图片`)+ }+ catch (error) {+ message.error(t('aiGenerate.uploadFailed'))+ }+ finally {+ setUploadingFirstFrame(false)+ if (e.target)+ e.target.value = ''+ }+ }// Remove imageconst handleRemoveImage = (index: number) => {- setVideoImages(prev => prev.filter((_, i) => i !== index));- };+ setVideoImages(prev => prev.filter((_, i) => i !== index))+ }// Clear all imagesconst handleClearAllImages = () => {- setVideoImages([]);- };+ setVideoImages([])+ }// md2card- const [markdownContent, setMarkdownContent] = useState(defaultMarkdown);- const [selectedTheme, setSelectedTheme] = useState("apple-notes");- const [themeMode, setThemeMode] = useState("light");- const [cardWidth, setCardWidth] = useState(440);- const [cardHeight, setCardHeight] = useState(586);- const [splitMode, setSplitMode] = useState("noSplit");- const [mdxMode, setMdxMode] = useState(false);- const [overHiddenMode, setOverHiddenMode] = useState(false);- const [loadingMd2Card, setLoadingMd2Card] = useState(false);- const [md2CardResult, setMd2CardResult] = useState<string | null>(null);-- const [mediaGroups, setMediaGroups] = useState<any[]>([]);- const [selectedMediaGroup, setSelectedMediaGroup] = useState<string | null>(null);- const [uploadModalVisible, setUploadModalVisible] = useState(false);- const [uploading, setUploading] = useState(false);- const [loadingMediaGroups, setLoadingMediaGroups] = useState(false);- const [defaultMediaGroup, setDefaultMediaGroup] = useState<string | null>(null);- const [uploadedContent, setUploadedContent] = useState<Set<string>>(new Set());-- const [imageModels, setImageModels] = useState<any[]>([]);- const [videoModels, setVideoModels] = useState<any[]>([]);- const [imageEditModels, setImageEditModels] = useState<any[]>([]);+ const [markdownContent, setMarkdownContent] = useState(defaultMarkdown)+ const [selectedTheme, setSelectedTheme] = useState('apple-notes')+ const [themeMode, setThemeMode] = useState('light')+ const [cardWidth, setCardWidth] = useState(440)+ const [cardHeight, setCardHeight] = useState(586)+ const [splitMode, setSplitMode] = useState('noSplit')+ const [mdxMode, setMdxMode] = useState(false)+ const [overHiddenMode, setOverHiddenMode] = useState(false)+ const [loadingMd2Card, setLoadingMd2Card] = useState(false)+ const [md2CardResult, setMd2CardResult] = useState<string | null>(null)++ const [mediaGroups, setMediaGroups] = useState<any[]>([])+ const [selectedMediaGroup, setSelectedMediaGroup] = useState<string | null>(null)+ const [uploadModalVisible, setUploadModalVisible] = useState(false)+ const [uploading, setUploading] = useState(false)+ const [loadingMediaGroups, setLoadingMediaGroups] = useState(false)+ const [defaultMediaGroup, setDefaultMediaGroup] = useState<string | null>(null)+ const [uploadedContent, setUploadedContent] = useState<Set<string>>(new Set())++ const [imageModels, setImageModels] = useState<any[]>([])+ const [videoModels, setVideoModels] = useState<any[]>([])+ const [imageEditModels, setImageEditModels] = useState<any[]>([])// Image-to-image related state- const [imageEditPrompt, setImageEditPrompt] = useState("");- const [imageEditModel, setImageEditModel] = useState("");- const [imageEditSize, setImageEditSize] = useState("1024x1024");- const [imageEditN, setImageEditN] = useState(1);- const [imageEditLoading, setImageEditLoading] = useState(false);- const [imageEditResult, setImageEditResult] = useState<string[] | null>(null);- const [imageEditTaskId, setImageEditTaskId] = useState<string | null>(null);- const [imageEditStatus, setImageEditStatus] = useState<string>("");- const [imageEditProgress, setImageEditProgress] = useState(0);- const [checkingImageEditStatus, setCheckingImageEditStatus] = useState(false);- const [sourceImages, setSourceImages] = useState<string[]>([]);- const [uploadingSourceImage, setUploadingSourceImage] = useState(false);+ const [imageEditPrompt, setImageEditPrompt] = useState('')+ const [imageEditModel, setImageEditModel] = useState('')+ const [imageEditSize, setImageEditSize] = useState('1024x1024')+ const [imageEditN, setImageEditN] = useState(1)+ const [imageEditLoading, setImageEditLoading] = useState(false)+ const [imageEditResult, setImageEditResult] = useState<string[] | null>(null)+ const [imageEditTaskId, setImageEditTaskId] = useState<string | null>(null)+ const [imageEditStatus, setImageEditStatus] = useState<string>('')+ const [imageEditProgress, setImageEditProgress] = useState(0)+ const [checkingImageEditStatus, setCheckingImageEditStatus] = useState(false)+ const [sourceImages, setSourceImages] = useState<string[]>([])+ const [uploadingSourceImage, setUploadingSourceImage] = useState(false)// Custom model dropdown- const [showModelDropdown, setShowModelDropdown] = useState(false);- const [showVideoModelDropdown, setShowVideoModelDropdown] = useState(false);+ const [showModelDropdown, setShowModelDropdown] = useState(false)+ const [showVideoModelDropdown, setShowVideoModelDropdown] = useState(false)// Sample carousel- const sampleImages = [SAMPLE_IMAGE_URLS.shili21, SAMPLE_IMAGE_URLS.shili22, SAMPLE_IMAGE_URLS.shili23, SAMPLE_IMAGE_URLS.shili24];- const [sampleIdx, setSampleIdx] = useState(0);- const handlePrevSample = () => setSampleIdx((p) => (p - 1 + sampleImages.length) % sampleImages.length);- const handleNextSample = () => setSampleIdx((p) => (p + 1) % sampleImages.length);-- // Save results to local- const handleSaveResults = async () => {- try {- if (!result || !result.length) { message.warning(t('aiGenerate.imageGenerationFailed')); return; }- for (let i = 0; i < result.length; i++) {- const url = getOssUrl(result[i]);- const link = document.createElement('a');- link.href = url;- link.download = `image_${i + 1}.png`;- document.body.appendChild(link);- link.click();- document.body.removeChild(link);- }- message.success(t('aiGenerate.uploadSuccess'));- } catch (e) {- message.error(t('aiGenerate.uploadFailed'));- }- };+ const sampleImages = [SAMPLE_IMAGE_URLS.shili21, SAMPLE_IMAGE_URLS.shili22, SAMPLE_IMAGE_URLS.shili23, SAMPLE_IMAGE_URLS.shili24]+ const [sampleIdx, setSampleIdx] = useState(0)+ const handlePrevSample = () => setSampleIdx(p => (p - 1 + sampleImages.length) % sampleImages.length)+ const handleNextSample = () => setSampleIdx(p => (p + 1) % sampleImages.length)const handleDownloadUrl = (url: string) => {- const real = getOssUrl(url);- const a = document.createElement('a');- a.href = real;- a.download = real.split('/').pop() || 'image.png';- document.body.appendChild(a);- a.click();- document.body.removeChild(a);- };+ const real = getOssUrl(url)+ const a = document.createElement('a')+ a.href = real+ a.download = real.split('/').pop() || 'image.png'+ document.body.appendChild(a)+ a.click()+ document.body.removeChild(a)+ }// Image editing related functionsconst handleSourceImageChange = async (e: React.ChangeEvent<HTMLInputElement>) => {- const files = e.target.files;- if (!files || files.length === 0) return;-+ const files = e.target.files+ if (!files || files.length === 0)+ return+// Check current model's maximum image count limit- const selectedModel = imageEditModels.find((m: any) => m.name === imageEditModel);- const maxImages = selectedModel?.maxInputImages || 1;-+ const selectedModel = imageEditModels.find((m: any) => m.name === imageEditModel)+ const maxImages = selectedModel?.maxInputImages || 1+// Calculate number of images that can be uploaded- const remainingSlots = maxImages - sourceImages.length;+ const remainingSlots = maxImages - sourceImages.lengthif (remainingSlots <= 0) {- message.warning(t('aiGenerate.maxUploadLimitReached' as any, { count: maxImages }));- if (e.target) e.target.value = "";- return;- }-- const validFiles: File[] = [];- const filesToProcess = Array.from(files).slice(0, remainingSlots);-+ message.warning(t('aiGenerate.maxUploadLimitReached' as any, { count: maxImages }))+ if (e.target)+ e.target.value = ''+ return+ }++ const validFiles: File[] = []+ const filesToProcess = Array.from(files).slice(0, remainingSlots)+for (let i = 0; i < filesToProcess.length; i++) {- const file = filesToProcess[i];+ const file = filesToProcess[i]if (checkFileSize(file) && checkImageFormat(file)) {- validFiles.push(file);+ validFiles.push(file)}}-+if (validFiles.length === 0) {- if (e.target) e.target.value = "";- return;+ if (e.target)+ e.target.value = ''+ return}-+if (filesToProcess.length < files.length) {- message.warning(t('aiGenerate.autoSelectImages' as any, { count: remainingSlots }));+ message.warning(t('aiGenerate.autoSelectImages' as any, { count: remainingSlots }))}-+try {- setUploadingSourceImage(true);- const uploadPromises = validFiles.map(file => uploadToOss(file));- const keys = await Promise.all(uploadPromises);- const urls = keys.map(key => getOssUrl(key));- setSourceImages(prev => [...prev, ...urls]);- message.success(t('aiGenerate.uploadSuccessCount' as any, { count: validFiles.length }));- } catch (error) {- message.error(t("aiGenerate.uploadFailed"));- } finally {- setUploadingSourceImage(false);- if (e.target) e.target.value = "";- }- };+ setUploadingSourceImage(true)+ const uploadPromises = validFiles.map(file => uploadToOss(file))+ const keys = await Promise.all(uploadPromises)+ const urls = keys.map(key => getOssUrl(key))+ setSourceImages(prev => [...prev, ...urls])+ message.success(t('aiGenerate.uploadSuccessCount' as any, { count: validFiles.length }))+ }+ catch (error) {+ message.error(t('aiGenerate.uploadFailed'))+ }+ finally {+ setUploadingSourceImage(false)+ if (e.target)+ e.target.value = ''+ }+ }const handleRemoveSourceImage = (index: number) => {- setSourceImages(prev => prev.filter((_, i) => i !== index));- };+ setSourceImages(prev => prev.filter((_, i) => i !== index))+ }const handleClearAllSourceImages = () => {- setSourceImages([]);- };+ setSourceImages([])+ }- const handleImageEdit = async () => {- if (!imageEditPrompt) { message.error(t("aiGenerate.pleaseEnterPrompt")); return; }- if (!sourceImages.length) { message.error(t("aiGenerate.pleaseUploadFirstFrame")); return; }- if (!imageEditModel) { message.error(t("aiGenerate.pleaseSelectVideoModel")); return; }+ const replaceOssUrl = (url: string) => {+ return url.replace('/ossProxy/', OSS_URL)+ }- const sourceImagess = sourceImages.map((item:string)=> replaceOssUrl(item));+ // Auto upload to default media group+ const autoUploadToDefaultGroup = async (mediaUrl: string, mediaType: 'video' | 'img', modelName: string, description: string) => {try {- setImageEditLoading(true);- setImageEditStatus("submitted");- setImageEditProgress(10);- const res: any = await editImage({- model: imageEditModel,- image: sourceImagess,- prompt: imageEditPrompt,- n: imageEditN,- size: imageEditSize,- response_format: "url"- });- if (res?.data?.logId) {- setImageEditTaskId(res.data.logId);- setImageEditStatus(res.data.status);- message.success(t("aiGenerate.taskSubmittedSuccess"));- pollImageEditTaskStatus(res.data.logId);- } else {- setVipModalOpen(true);- setImageEditStatus("");+ // Check if already uploaded+ if (uploadedContent.has(mediaUrl)) {+ console.log('Content already uploaded:', mediaUrl)+ return+ }++ // Get media group list and find default group+ const res: any = await getMediaGroupList(1, 100, mediaType)+ let defaultGroupId = null++ if (res.data) {+ const groups = res.data.list || []+ const defaultGroup = groups.find((group: any) => group.isDefault === true)+ if (defaultGroup) {+ defaultGroupId = defaultGroup._id+ setDefaultMediaGroup(defaultGroupId)+ }+ else {+ defaultGroupId = groups[0]._id+ setDefaultMediaGroup(defaultGroupId)+ }+ }++ if (!defaultGroupId) {+ console.warn('No default media group found')+ message.error(t('aiGenerate.noDefaultMediaGroup' as any))+ return+ }++ const now = new Date()+ const timeStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`+ const uploadTitle = modelName ? `${modelName} ${timeStr}` : timeStr++ console.log('开始上传到默认组:', defaultGroupId, mediaUrl)++ const uploadRes: any = await createMedia({+ groupId: defaultGroupId,+ url: mediaUrl,+ type: mediaType,+ title: uploadTitle,+ desc: description,+ })++ if (uploadRes.data) {+ // Mark as uploaded+ setUploadedContent(prev => new Set([...prev, mediaUrl]))+ message.success(mediaType === 'video' ? t('aiGenerate.videoUploadSuccess') : t('aiGenerate.uploadSuccess'))+ console.log('上传成功')+ }+ else {+ message.error(mediaType === 'video' ? t('aiGenerate.videoUploadFailed') : t('aiGenerate.uploadFailed'))+ console.log('上传失败:', uploadRes)}- } catch { setImageEditStatus(""); } finally { setImageEditLoading(false); }- };+ }+ catch (error) {+ console.error('Auto upload failed:', error)+ message.error(mediaType === 'video' ? t('aiGenerate.videoUploadFailed') : t('aiGenerate.uploadFailed'))+ }+ }const pollImageEditTaskStatus = async (logId: string) => {const checkStatus = async () => {try {- setCheckingImageEditStatus(true);- const res: any = await getImageEditTaskStatus(logId);+ setCheckingImageEditStatus(true)+ const res: any = await getImageEditTaskStatus(logId)if (res.data) {- const { status, fail_reason, response, images } = res.data;- const up = typeof status === "string" ? status.toUpperCase() : "";- const normalized = up === "SUCCESS" ? "completed" : up === "FAILED" ? "failed" : up === "PROCESSING" || up === "GENERATING" ? "processing" : up === "NOT_START" || up === "NOT_STARTED" || up === "QUEUED" || up === "PENDING" ? "submitted" : (status || "").toString().toLowerCase();- setImageEditStatus(normalized);-- let percent = 0;- if (normalized === "submitted") percent = 10;- else if (normalized === "processing") percent = 50;- else if (normalized === "completed") percent = 100;- else if (normalized === "failed") percent = 0;-- if (normalized === "completed") {- const imageUrls = (images || response?.list || []).map((i: any) => i.url) || [];- setImageEditResult(imageUrls);- setImageEditProgress(100);- message.success(t('aiGenerate.imageEditCompleted' as any));-+ const { status, fail_reason, response, images } = res.data+ const up = typeof status === 'string' ? status.toUpperCase() : ''+ const normalized = up === 'SUCCESS' ? 'completed' : up === 'FAILED' ? 'failed' : up === 'PROCESSING' || up === 'GENERATING' ? 'processing' : up === 'NOT_START' || up === 'NOT_STARTED' || up === 'QUEUED' || up === 'PENDING' ? 'submitted' : (status || '').toString().toLowerCase()+ setImageEditStatus(normalized)++ let percent = 0+ if (normalized === 'submitted')+ percent = 10+ else if (normalized === 'processing')+ percent = 50+ else if (normalized === 'completed')+ percent = 100+ else if (normalized === 'failed')+ percent = 0++ if (normalized === 'completed') {+ const imageUrls = (images || response?.list || []).map((i: any) => i.url) || []+ setImageEditResult(imageUrls)+ setImageEditProgress(100)+ message.success(t('aiGenerate.imageEditCompleted' as any))+// Auto upload first image to default media groupif (imageUrls.length > 0) {- await autoUploadToDefaultGroup(imageUrls[0], "img", imageEditModel, imageEditPrompt);+ await autoUploadToDefaultGroup(imageUrls[0], 'img', imageEditModel, imageEditPrompt)}- return true;+ return true}- if (normalized === "failed") {- setImageEditProgress(0);- message.error(fail_reason || t("aiGenerate.imageGenerationFailed"));- return true;+ if (normalized === 'failed') {+ setImageEditProgress(0)+ message.error(fail_reason || t('aiGenerate.imageGenerationFailed'))+ return true}- setImageEditProgress(percent);- return false;+ setImageEditProgress(percent)+ return false}- return false;- } catch { return false; } finally { setCheckingImageEditStatus(false); }- };- const poll = async () => { const done = await checkStatus(); if (!done) setTimeout(poll, 5000); };- poll();- };+ return false+ }+ catch { return false }+ finally { setCheckingImageEditStatus(false) }+ }+ const poll = async () => {+ const done = await checkStatus()+ if (!done)+ setTimeout(poll, 5000)+ }+ poll()+ }++ const handleImageEdit = async () => {+ if (!imageEditPrompt) {+ message.error(t('aiGenerate.pleaseEnterPrompt'))+ return+ }+ if (!sourceImages.length) {+ message.error(t('aiGenerate.pleaseUploadFirstFrame'))+ return+ }+ if (!imageEditModel) {+ message.error(t('aiGenerate.pleaseSelectVideoModel'))+ return+ }++ const sourceImagess = sourceImages.map((item: string) => replaceOssUrl(item))+ try {+ setImageEditLoading(true)+ setImageEditStatus('submitted')+ setImageEditProgress(10)+ const res: any = await editImage({+ model: imageEditModel,+ image: sourceImagess,+ prompt: imageEditPrompt,+ n: imageEditN,+ size: imageEditSize,+ response_format: 'url',+ })+ if (res?.data?.logId) {+ setImageEditTaskId(res.data.logId)+ setImageEditStatus(res.data.status)+ message.success(t('aiGenerate.taskSubmittedSuccess'))+ pollImageEditTaskStatus(res.data.logId)+ }+ else {+ setVipModalOpen(true)+ setImageEditStatus('')+ }+ }+ catch { setImageEditStatus('') }+ finally { setImageEditLoading(false) }+ }const getVideoModelCreditCost = (modelName: string, duration: number, size: string): number => {- const m = videoModels.find((v) => v.name === modelName);- if (!m) return 0;-+ const m = videoModels.find(v => v.name === modelName)+ if (!m)+ return 0+// If kling model, use mode field for matchingif (m?.channel === 'kling' && m?.pricing) {- const item = m.pricing.find((p: any) => p.duration === duration && p.mode === size);- return item ? item.price : 0;+ const item = m.pricing.find((p: any) => p.duration === duration && p.mode === size)+ return item ? item.price : 0}-+// Other models use resolution field for matching- const item = m?.pricing?.find((p: any) => p.duration === duration && p.resolution === size);- return item ? item.price : 0;- };+ const item = m?.pricing?.find((p: any) => p.duration === duration && p.resolution === size)+ return item ? item.price : 0+ }++ const pollVideoTaskStatus = async (taskId: string) => {+ const checkStatus = async () => {+ try {+ setCheckingStatus(true)+ const res: any = await getVideoTaskStatus(taskId)+ if (res.data) {+ const { status, fail_reason, video_url, progress } = res.data+ const up = typeof status === 'string' ? status.toUpperCase() : ''+ const normalized = up === 'SUCCESS' ? 'completed' : up === 'FAILED' ? 'failed' : up === 'PROCESSING' ? 'processing' : up === 'NOT_START' || up === 'NOT_STARTED' || up === 'QUEUED' || up === 'PENDING' ? 'submitted' : (status || '').toString().toLowerCase()+ setVideoStatus(normalized)+ let percent = 0+ if (typeof progress === 'string') {+ const m = progress.match(/(\d+)/)+ percent = m ? Number(m[1]) : 0+ }+ else if (typeof progress === 'number') {+ percent = progress > -1 ? Math.round(progress) : Math.round(progress * 100)+ }+ if (normalized === 'completed') {+ const videoUrl = res.data?.data?.video_url+ setVideoResult(videoUrl)+ setVideoProgress(100)+ message.success(t('aiGenerate.videoGenerationSuccess'))++ // Auto upload to default media group+ if (videoUrl) {+ await autoUploadToDefaultGroup(videoUrl, 'video', videoModel, videoPrompt)+ }+ return true+ }+ if (normalized === 'failed') {+ setVideoProgress(0)+ message.error(fail_reason || t('aiGenerate.videoGenerationFailed'))+ return true+ }+ setVideoProgress(percent)+ return false+ }+ return false+ }+ catch { return false }+ finally { setCheckingStatus(false) }+ }+ const poll = async () => {+ const done = await checkStatus()+ if (!done)+ setTimeout(poll, 5000)+ }+ poll()+ }++ const pollImageTaskStatus = async (logId: string) => {+ const checkStatus = async () => {+ try {+ setCheckingImageStatus(true)+ const res: any = await getImageTaskStatus(logId)+ if (res.data) {+ const { status, fail_reason, response, images } = res.data+ const up = typeof status === 'string' ? status.toUpperCase() : ''+ const normalized = up === 'SUCCESS' ? 'completed' : up === 'FAILED' ? 'failed' : up === 'PROCESSING' || up === 'GENERATING' ? 'processing' : up === 'NOT_START' || up === 'NOT_STARTED' || up === 'QUEUED' || up === 'PENDING' ? 'submitted' : (status || '').toString().toLowerCase()+ setImageStatus(normalized)++ // Calculate progress - if no explicit progress field, estimate based on status+ let percent = 0+ if (normalized === 'submitted')+ percent = 10+ else if (normalized === 'processing')+ percent = 50+ else if (normalized === 'completed')+ percent = 100+ else if (normalized === 'failed')+ percent = 0++ if (normalized === 'completed') {+ // Prefer images field, otherwise use response.list+ const imageUrls = (images || response?.list || []).map((i: any) => i.url) || []+ setResult(imageUrls)+ setImageProgress(100)+ message.success(t('aiGenerate.imageGenerationCompleted' as any))++ // Auto upload first image to default media group+ if (imageUrls.length > 0) {+ await autoUploadToDefaultGroup(imageUrls[0], 'img', model, prompt)+ }+ return true+ }+ if (normalized === 'failed') {+ setImageProgress(0)+ message.error(fail_reason || t('aiGenerate.imageGenerationFailed'))+ return true+ }+ setImageProgress(percent)+ return false+ }+ return false+ }+ catch { return false }+ finally { setCheckingImageStatus(false) }+ }+ const poll = async () => {+ const done = await checkStatus()+ if (!done)+ setTimeout(poll, 5000)+ }+ poll()+ }const filteredVideoModels = useMemo(() => {- if (!Array.isArray(videoModels)) return [] as any[];- if (videoMode === "text2video") return (videoModels as any[]).filter((m: any) => (m?.modes || []).includes("text2video"));- if (videoMode === "image2video") {+ if (!Array.isArray(videoModels))+ return [] as any[]+ if (videoMode === 'text2video')+ return (videoModels as any[]).filter((m: any) => (m?.modes || []).includes('text2video'))+ if (videoMode === 'image2video') {// Merge all video modes that support imagesreturn (videoModels as any[]).filter((m: any) => {- const modes = m?.modes || [];- return modes.includes("image2video") || modes.includes("flf2video") || modes.includes("lf2video") || modes.includes("multi-image2video");- });+ const modes = m?.modes || []+ return modes.includes('image2video') || modes.includes('flf2video') || modes.includes('lf2video') || modes.includes('multi-image2video')+ })}- return (videoModels as any[]).filter((m: any) => (m?.modes || []).includes("image2video"));- }, [videoModels, videoMode]);+ return (videoModels as any[]).filter((m: any) => (m?.modes || []).includes('image2video'))+ }, [videoModels, videoMode])const fetchImageModels = async () => {- try { const res: any = await getImageGenerationModels(); if (res.data) { setImageModels(res.data); if (res.data.length) setModel(res.data[0].name); } }- catch (e) { console.error(e); }- };+ try {+ const res: any = await getImageGenerationModels()+ if (res.data) {+ setImageModels(res.data)+ if (res.data.length)+ setModel(res.data[0].name)+ }+ }+ catch (e) { console.error(e) }+ }const fetchImageEditModels = async () => {- try { const res: any = await getImageEditModels(); if (res.data) { setImageEditModels(res.data); if (res.data.length) setImageEditModel(res.data[0].name); } }- catch (e) { console.error(e); }- };+ try {+ const res: any = await getImageEditModels()+ if (res.data) {+ setImageEditModels(res.data)+ if (res.data.length)+ setImageEditModel(res.data[0].name)+ }+ }+ catch (e) { console.error(e) }+ }const fetchVideoModels = async () => {try {- const res: any = await getVideoGenerationModels();+ const res: any = await getVideoGenerationModels()if (res.data) {- setVideoModels(res.data);+ setVideoModels(res.data)if (res.data.length) {- const first = res.data[0];- setVideoModel(first.name);- if (first?.durations?.length) setVideoDuration(first.durations[0]);- if (first?.resolutions?.length) setVideoSize(first.resolutions[0]);- if (first?.modes?.includes("image2video") || first?.modes?.includes("flf2video") || first?.modes?.includes("lf2video") || first?.modes?.includes("multi-image2video")) setVideoMode("image2video");- else if (first?.modes?.includes("text2video")) setVideoMode("text2video");+ const first = res.data[0]+ setVideoModel(first.name)+ if (first?.durations?.length)+ setVideoDuration(first.durations[0])+ if (first?.resolutions?.length)+ setVideoSize(first.resolutions[0])+ if (first?.modes?.includes('image2video') || first?.modes?.includes('flf2video') || first?.modes?.includes('lf2video') || first?.modes?.includes('multi-image2video'))+ setVideoMode('image2video')+ else if (first?.modes?.includes('text2video'))+ setVideoMode('text2video')}}- } catch (e) { console.error(e); }- };+ }+ catch (e) { console.error(e) }+ }const fetchVideoHistory = async () => {try {- setLoadingHistory(true);- const res: any = await getVideoGenerations({ page: 1, pageSize: 20 });+ setLoadingHistory(true)+ const res: any = await getVideoGenerations({ page: 1, pageSize: 20 })if (res.data?.list) {- setVideoHistory(res.data.list);+ setVideoHistory(res.data.list)}- } catch (e) {- console.error(e);- message.error(t("aiGenerate.taskFailed"));- } finally {- setLoadingHistory(false);}- };+ catch (e) {+ console.error(e)+ message.error(t('aiGenerate.taskFailed'))+ }+ finally {+ setLoadingHistory(false)+ }+ }// Format timestampconst formatTime = (timestamp: number) => {- if (!timestamp) return '-';- const date = new Date(timestamp * 1000);- return date.toLocaleString();- };+ if (!timestamp)+ return '-'+ const date = new Date(timestamp * 1000)+ return date.toLocaleString()+ }// Get status display textconst getStatusText = (status: string) => {switch (status?.toUpperCase()) {case 'SUCCESS':- return t('aiGenerate.completed' as any);+ return t('aiGenerate.completed' as any)case 'FAILED':- return t('aiGenerate.failed' as any);+ return t('aiGenerate.failed' as any)case 'PROCESSING':- return t('aiGenerate.processing' as any);+ return t('aiGenerate.processing' as any)case 'SUBMITTED':case 'PENDING':case 'QUEUED':- return t('aiGenerate.submitted' as any);+ return t('aiGenerate.submitted' as any)default:- return status || '-';+ return status || '-'}- };+ }// Handle history item clickconst handleHistoryItemClick = async (item: any) => {if (item.status === 'SUCCESS' && item.data?.video_url) {- setVideoResult(item.data.video_url);- setVideoStatus('completed');- setVideoProgress(100);-+ setVideoResult(item.data.video_url)+ setVideoStatus('completed')+ setVideoProgress(100)+// Auto upload to default media group- await autoUploadToDefaultGroup(item.data.video_url, "video", item.model || "Unknown Model", item.prompt || "");- } else if (item.status === 'PROCESSING') {- setVideoTaskId(item.task_id);- setVideoStatus('processing');- pollVideoTaskStatus(item.task_id);+ await autoUploadToDefaultGroup(item.data.video_url, 'video', item.model || 'Unknown Model', item.prompt || '')}- };- useEffect(() => { fetchImageModels(); fetchVideoModels(); fetchImageEditModels(); }, []);+ else if (item.status === 'PROCESSING') {+ setVideoTaskId(item.task_id)+ setVideoStatus('processing')+ pollVideoTaskStatus(item.task_id)+ }+ }+ useEffect(() => {+ fetchImageModels()+ fetchVideoModels()+ fetchImageEditModels()+ }, [])// Auto load history when switching to video moduleuseEffect(() => {- if (activeModule === "video" && videoHistory.length === 0) {- fetchVideoHistory();+ if (activeModule === 'video' && videoHistory.length === 0) {+ fetchVideoHistory()}- }, [activeModule]);+ }, [activeModule])// Auto set appropriate quality and size values when model changesuseEffect(() => {- if (!model || !imageModels.length) return;-- const selectedModel = imageModels.find((m: any) => m.name === model);- const qualities = selectedModel?.qualities || [];- const sizes = selectedModel?.sizes || [];-+ if (!model || !imageModels.length)+ return++ const selectedModel = imageModels.find((m: any) => m.name === model)+ const qualities = selectedModel?.qualities || []+ const sizes = selectedModel?.sizes || []+if (qualities.length > 0) {// If current quality is not in model's qualities list, set to first available qualityif (!qualities.includes(quality)) {- setQuality(qualities[0]);+ setQuality(qualities[0])}}-+if (sizes.length > 0) {// If current size is not in model's sizes list, set to first available sizeif (!sizes.includes(size)) {- setSize(sizes[0]);+ setSize(sizes[0])}}- }, [model, imageModels, quality, size]);+ }, [model, imageModels, quality, size])// Auto set appropriate size value and handle image count limit when image edit model changesuseEffect(() => {- if (!imageEditModel || !imageEditModels.length) return;-- const selectedModel = imageEditModels.find((m: any) => m.name === imageEditModel);- const sizes = selectedModel?.sizes || [];- const maxImages = selectedModel?.maxInputImages || 1;-+ if (!imageEditModel || !imageEditModels.length)+ return++ const selectedModel = imageEditModels.find((m: any) => m.name === imageEditModel)+ const sizes = selectedModel?.sizes || []+ const maxImages = selectedModel?.maxInputImages || 1+if (sizes.length > 0) {// If current size is not in model's sizes list, set to first available sizeif (!sizes.includes(imageEditSize)) {- setImageEditSize(sizes[0]);+ setImageEditSize(sizes[0])}}-+// If current image count exceeds new model's maximum limit, remove excess imagesif (sourceImages.length > maxImages) {- const removedCount = sourceImages.length - maxImages;- setSourceImages(prev => prev.slice(0, maxImages));- message.warning(t('aiGenerate.autoRemoveExcessImages' as any, { maxCount: maxImages, removedCount: removedCount }));+ const removedCount = sourceImages.length - maxImages+ setSourceImages(prev => prev.slice(0, maxImages))+ message.warning(t('aiGenerate.autoRemoveExcessImages' as any, { maxCount: maxImages, removedCount }))}- }, [imageEditModel, imageEditModels, imageEditSize, sourceImages.length]);+ }, [imageEditModel, imageEditModels, imageEditSize, sourceImages.length])// Initialize/respond to module and sub-tab switching based on URL ?tab=...useEffect(() => {- const tab = searchParams.get('tab') || '';- if (!tab) return;+ const tab = searchParams.get('tab') || ''+ if (!tab)+ returnif (tab === 'videoGeneration' || tab === 'text2video' || tab === 'image2video' || tab === 'flf2video' || tab === 'lf2video' || tab === 'multi-image2video') {- setActiveModule('video');+ setActiveModule('video')// Map all image-related video modes to image2videoif (tab === 'flf2video' || tab === 'lf2video' || tab === 'multi-image2video') {- setActiveVideoTab('image2video');- } else {- setActiveVideoTab(tab as any);+ setActiveVideoTab('image2video')}- } else if (tab === 'textToImage' || tab === 'imageToImage' || tab === 'textToFireflyCard' || tab === 'md2card' || tab === 'chat') {- setActiveModule('image');- setActiveImageTab(tab as any);+ else {+ setActiveVideoTab(tab as any)+ }+ }+ else if (tab === 'textToImage' || tab === 'imageToImage' || tab === 'textToFireflyCard' || tab === 'md2card' || tab === 'chat') {+ setActiveModule('image')+ setActiveImageTab(tab as any)}- }, [searchParams]);+ }, [searchParams])useEffect(() => {if ((filteredVideoModels as any[]).length > 0) {if (!(filteredVideoModels as any[]).find((m: any) => m.name === videoModel)) {- setVideoModel((filteredVideoModels as any[])[0].name);+ setVideoModel((filteredVideoModels as any[])[0].name)}}- if (videoMode === "text2video") { setVideoImage(""); setVideoImageTail(""); setVideoImages([]); }- }, [videoMode, filteredVideoModels]);+ if (videoMode === 'text2video') {+ setVideoImage('')+ setVideoImageTail('')+ setVideoImages([])+ }+ }, [videoMode, filteredVideoModels])useEffect(() => {- if (!videoModel || !videoModels?.length) return;- const current: any = (videoModels as any[]).find((m: any) => m.name === videoModel);- if (!current) return;-- let durations: any[] = [];- let resolutions: any[] = [];-+ if (!videoModel || !videoModels?.length)+ return+ const current: any = (videoModels as any[]).find((m: any) => m.name === videoModel)+ if (!current)+ return++ let durations: any[] = []+ let resolutions: any[] = []+// If kling model, get options from pricingif (current?.channel === 'kling' && current?.pricing) {- durations = [...new Set(current.pricing.map((p: any) => p.duration))];- resolutions = [...new Set(current.pricing.map((p: any) => p.mode))];- } else {+ durations = [...new Set(current.pricing.map((p: any) => p.duration))]+ resolutions = [...new Set(current.pricing.map((p: any) => p.mode))]+ }+ else {// Other models get from original fields- durations = current?.durations || [];- resolutions = current?.resolutions || [];- }-- const { supportedParameters = [] } = current || {};-- if (durations.length && !durations.includes(videoDuration)) setVideoDuration(durations[0]);- if (resolutions.length && !resolutions.includes(videoSize)) setVideoSize(resolutions[0]);- if (!supportedParameters.includes("image") && videoImage) setVideoImage("");- if (!supportedParameters.includes("image_tail") && videoImageTail) setVideoImageTail("");- }, [videoModel, videoModels]);-- const fetchMediaGroups = async (type: "video" | "img" = "img") => {- try {- setLoadingMediaGroups(true);- const res: any = await getMediaGroupList(1, 100, type);+ durations = current?.durations || []+ resolutions = current?.resolutions || []+ }++ const { supportedParameters = [] } = current || {}++ if (durations.length && !durations.includes(videoDuration))+ setVideoDuration(durations[0])+ if (resolutions.length && !resolutions.includes(videoSize))+ setVideoSize(resolutions[0])+ if (!supportedParameters.includes('image') && videoImage)+ setVideoImage('')+ if (!supportedParameters.includes('image_tail') && videoImageTail)+ setVideoImageTail('')+ }, [videoModel, videoModels])++ const fetchMediaGroups = async (type: 'video' | 'img' = 'img') => {+ try {+ setLoadingMediaGroups(true)+ const res: any = await getMediaGroupList(1, 100, type)if (res.data) {- const groups = res.data.list || [];- setMediaGroups(groups);+ const groups = res.data.list || []+ setMediaGroups(groups)// Find default group- const defaultGroup = groups.find((group: any) => group.isDefault === true);+ const defaultGroup = groups.find((group: any) => group.isDefault === true)if (defaultGroup) {- setDefaultMediaGroup(defaultGroup._id);- }else{- setDefaultMediaGroup(groups[0]._id);+ setDefaultMediaGroup(defaultGroup._id)+ }+ else {+ setDefaultMediaGroup(groups[0]._id)}}}- catch { message.error(t("aiGenerate.getMediaGroupListFailed")); }- finally { setLoadingMediaGroups(false); }- };+ catch { message.error(t('aiGenerate.getMediaGroupListFailed')) }+ finally { setLoadingMediaGroups(false) }+ }const handleTextToImage = async () => {- if (!prompt) { message.error(t("aiGenerate.pleaseEnterPrompt")); return; }+ if (!prompt) {+ message.error(t('aiGenerate.pleaseEnterPrompt'))+ return+ }try {- setLoading(true);- setImageStatus("submitted");- setImageProgress(10);- const res: any = await generateImage({ prompt, n, quality, style, size, model, response_format: "url" });+ setLoading(true)+ setImageStatus('submitted')+ setImageProgress(10)+ const res: any = await generateImage({ prompt, n, quality, style, size, model, response_format: 'url' })console.log('res', res)if (res?.data?.logId) {- setImageTaskId(res.data.logId);- setImageStatus(res.data.status);- message.success(t("aiGenerate.taskSubmittedSuccess"));- pollImageTaskStatus(res.data.logId);- } else {- setVipModalOpen(true);- setImageStatus("");+ setImageTaskId(res.data.logId)+ setImageStatus(res.data.status)+ message.success(t('aiGenerate.taskSubmittedSuccess'))+ pollImageTaskStatus(res.data.logId)+ }+ else {+ setVipModalOpen(true)+ setImageStatus('')}- } catch {- setImageStatus("");- } finally { setLoading(false); }- };+ }+ catch {+ setImageStatus('')+ }+ finally { setLoading(false) }+ }const handleTextToFireflyCard = async () => {- if (!content || !title) { message.error(t("aiGenerate.pleaseEnterContentAndTitle")); return; }- try {- setLoadingFirefly(true);- const res: any = await generateFireflyCard({ content, temp, title });+ if (!content || !title) {+ message.error(t('aiGenerate.pleaseEnterContentAndTitle'))+ return+ }+ try {+ setLoadingFirefly(true)+ const res: any = await generateFireflyCard({ content, temp, title })if (res.data?.image) {- setFireflyResult(res.data.image);-+ setFireflyResult(res.data.image)+// Auto upload to default media group- await autoUploadToDefaultGroup(res.data.image, "img", "Firefly Card", `${title}: ${content}`);- } else {- message.error(t("aiGenerate.fireflyCardGenerationFailed"));+ await autoUploadToDefaultGroup(res.data.image, 'img', 'Firefly Card', `${title}: ${content}`)+ }+ else {+ message.error(t('aiGenerate.fireflyCardGenerationFailed'))}}- catch { message.error(t("aiGenerate.fireflyCardGenerationFailed")); } finally { setLoadingFirefly(false); }- };-- const replaceOssUrl = (url: string) => {- return url.replace("/ossProxy/", OSS_URL);- };+ catch { message.error(t('aiGenerate.fireflyCardGenerationFailed')) }+ finally { setLoadingFirefly(false) }+ }const handleVideoGeneration = async () => {- if (!videoPrompt) { message.error(t("aiGenerate.pleaseEnterVideoDescription")); return; }- if (!videoModel) { message.error(t("aiGenerate.pleaseSelectVideoModel")); return; }- if (videoMode === "image2video") {- const current: any = (filteredVideoModels as any[]).find((m: any) => m.name === videoModel) || {};- const supported: string[] = current?.supportedParameters || [];- const modes: string[] = current?.modes || [];-+ if (!videoPrompt) {+ message.error(t('aiGenerate.pleaseEnterVideoDescription'))+ return+ }+ if (!videoModel) {+ message.error(t('aiGenerate.pleaseSelectVideoModel'))+ return+ }+ if (videoMode === 'image2video') {+ const current: any = (filteredVideoModels as any[]).find((m: any) => m.name === videoModel) || {}+ const supported: string[] = current?.supportedParameters || []+ const modes: string[] = current?.modes || []+// Check multi-image video- if (modes.includes('multi-image2video') && supported.includes("image") && videoImages.length === 0) {- message.error(t('aiGenerate.pleaseUploadAtLeastOneImage' as any));- return;+ if (modes.includes('multi-image2video') && supported.includes('image') && videoImages.length === 0) {+ message.error(t('aiGenerate.pleaseUploadAtLeastOneImage' as any))+ return}-+// Check single image video- if (modes.includes('image2video') && !modes.includes('multi-image2video') && supported.includes("image") && !videoImage) {- message.error(t("aiGenerate.pleaseUploadFirstFrame"));- return;+ if (modes.includes('image2video') && !modes.includes('multi-image2video') && supported.includes('image') && !videoImage) {+ message.error(t('aiGenerate.pleaseUploadFirstFrame'))+ return}-+// Check first and tail frame video- if (modes.includes('flf2video') && supported.includes("image") && !videoImage) {- message.error(t("aiGenerate.pleaseUploadFirstFrame"));- return;+ if (modes.includes('flf2video') && supported.includes('image') && !videoImage) {+ message.error(t('aiGenerate.pleaseUploadFirstFrame'))+ return}- if (modes.includes('flf2video') && supported.includes("image_tail") && !videoImageTail) {- message.error(t("aiGenerate.pleaseUploadTailFrame"));- return;+ if (modes.includes('flf2video') && supported.includes('image_tail') && !videoImageTail) {+ message.error(t('aiGenerate.pleaseUploadTailFrame'))+ return}-+// Check tail frame only video- if (modes.includes('lf2video') && supported.includes("image_tail") && !videoImageTail) {- message.error(t("aiGenerate.pleaseUploadTailFrame"));- return;+ if (modes.includes('lf2video') && supported.includes('image_tail') && !videoImageTail) {+ message.error(t('aiGenerate.pleaseUploadTailFrame'))+ return}}try {- setLoadingVideo(true); setVideoStatus("submitted"); setVideoProgress(10);- const current: any = (filteredVideoModels as any[]).find((m: any) => m.name === videoModel) || {};- const data: any = { model: videoModel, prompt: videoPrompt, duration: videoDuration };-+ setLoadingVideo(true)+ setVideoStatus('submitted')+ setVideoProgress(10)+ const current: any = (filteredVideoModels as any[]).find((m: any) => m.name === videoModel) || {}+ const data: any = { model: videoModel, prompt: videoPrompt, duration: videoDuration }+// If kling model, pass mode parameter instead of size parameterif (current?.channel === 'kling') {- data.mode = videoSize;- } else {- data.size = videoSize;+ data.mode = videoSize+ }+ else {+ data.size = videoSize}-- const supported: string[] = current?.supportedParameters || [];- const modes: string[] = current?.modes || [];-- if (videoMode === "image2video") {++ const supported: string[] = current?.supportedParameters || []+ const modes: string[] = current?.modes || []++ if (videoMode === 'image2video') {// Multi-image video- if (modes.includes('multi-image2video') && supported.includes("image") && videoImages.length > 0) {- data.image = videoImages.map((image: string) => replaceOssUrl(image));+ if (modes.includes('multi-image2video') && supported.includes('image') && videoImages.length > 0) {+ data.image = videoImages.map((image: string) => replaceOssUrl(image))}// Single image video- else if (modes.includes('image2video') && !modes.includes('multi-image2video') && supported.includes("image") && videoImage) {-- data.image = replaceOssUrl(videoImage);+ else if (modes.includes('image2video') && !modes.includes('multi-image2video') && supported.includes('image') && videoImage) {+ data.image = replaceOssUrl(videoImage)}// First and tail frame videoelse if (modes.includes('flf2video')) {- if (supported.includes("image") && videoImage) data.image = replaceOssUrl(videoImage);- if (supported.includes("image_tail") && videoImageTail) data.image_tail = replaceOssUrl(videoImageTail);+ if (supported.includes('image') && videoImage)+ data.image = replaceOssUrl(videoImage)+ if (supported.includes('image_tail') && videoImageTail)+ data.image_tail = replaceOssUrl(videoImageTail)}// Tail frame only video- else if (modes.includes('lf2video') && supported.includes("image_tail") && videoImageTail) {- data.image_tail = replaceOssUrl(videoImageTail);+ else if (modes.includes('lf2video') && supported.includes('image_tail') && videoImageTail) {+ data.image_tail = replaceOssUrl(videoImageTail)}}- const res: any = await generateVideo(data);- if (res?.data?.task_id) { setVideoTaskId(res.data.task_id); setVideoStatus(res.data.status); message.success(t("aiGenerate.taskSubmittedSuccess")); pollVideoTaskStatus(res.data.task_id); }- else { setVipModalOpen(true); setVideoStatus(""); }- } catch { setVideoStatus(""); } finally { setLoadingVideo(false); }- };-- const pollVideoTaskStatus = async (taskId: string) => {- const checkStatus = async () => {- try {- setCheckingStatus(true);- const res: any = await getVideoTaskStatus(taskId);- if (res.data) {- const { status, fail_reason, video_url, progress } = res.data;- const up = typeof status === "string" ? status.toUpperCase() : "";- const normalized = up === "SUCCESS" ? "completed" : up === "FAILED" ? "failed" : up === "PROCESSING" ? "processing" : up === "NOT_START" || up === "NOT_STARTED" || up === "QUEUED" || up === "PENDING" ? "submitted" : (status || "").toString().toLowerCase();- setVideoStatus(normalized);- let percent = 0;- if (typeof progress === "string") { const m = progress.match(/(\d+)/); percent = m ? Number(m[1]) : 0; }- else if (typeof progress === "number") { percent = progress > -1 ? Math.round(progress) : Math.round(progress * 100); }- if (normalized === "completed") {- const videoUrl = res.data?.data?.video_url;- setVideoResult(videoUrl);- setVideoProgress(100);- message.success(t("aiGenerate.videoGenerationSuccess"));-- // Auto upload to default media group- if (videoUrl) {- await autoUploadToDefaultGroup(videoUrl, "video", videoModel, videoPrompt);- }- return true;- }- if (normalized === "failed") { setVideoProgress(0); message.error(fail_reason || t("aiGenerate.videoGenerationFailed")); return true; }- setVideoProgress(percent); return false;- }- return false;- } catch { return false; } finally { setCheckingStatus(false); }- };- const poll = async () => { const done = await checkStatus(); if (!done) setTimeout(poll, 5000); };- poll();- };-- const pollImageTaskStatus = async (logId: string) => {- const checkStatus = async () => {- try {- setCheckingImageStatus(true);- const res: any = await getImageTaskStatus(logId);- if (res.data) {- const { status, fail_reason, response, images } = res.data;- const up = typeof status === "string" ? status.toUpperCase() : "";- const normalized = up === "SUCCESS" ? "completed" : up === "FAILED" ? "failed" : up === "PROCESSING" || up === "GENERATING" ? "processing" : up === "NOT_START" || up === "NOT_STARTED" || up === "QUEUED" || up === "PENDING" ? "submitted" : (status || "").toString().toLowerCase();- setImageStatus(normalized);-- // Calculate progress - if no explicit progress field, estimate based on status- let percent = 0;- if (normalized === "submitted") percent = 10;- else if (normalized === "processing") percent = 50;- else if (normalized === "completed") percent = 100;- else if (normalized === "failed") percent = 0;-- if (normalized === "completed") {- // Prefer images field, otherwise use response.list- const imageUrls = (images || response?.list || []).map((i: any) => i.url) || [];- setResult(imageUrls);- setImageProgress(100);- message.success(t('aiGenerate.imageGenerationCompleted' as any));-- // Auto upload first image to default media group- if (imageUrls.length > 0) {- await autoUploadToDefaultGroup(imageUrls[0], "img", model, prompt);- }- return true;- }- if (normalized === "failed") {- setImageProgress(0);- message.error(fail_reason || t("aiGenerate.imageGenerationFailed"));- return true;- }- setImageProgress(percent);- return false;- }- return false;- } catch { return false; } finally { setCheckingImageStatus(false); }- };- const poll = async () => { const done = await checkStatus(); if (!done) setTimeout(poll, 5000); };- poll();- };+ const res: any = await generateVideo(data)+ if (res?.data?.task_id) {+ setVideoTaskId(res.data.task_id)+ setVideoStatus(res.data.status)+ message.success(t('aiGenerate.taskSubmittedSuccess'))+ pollVideoTaskStatus(res.data.task_id)+ }+ else {+ setVipModalOpen(true)+ setVideoStatus('')+ }+ }+ catch { setVideoStatus('') }+ finally { setLoadingVideo(false) }+ }const handleMd2CardGeneration = async () => {- if (!markdownContent) { message.error(t("aiGenerate.pleaseEnterMarkdown")); return; }- try {- setLoadingMd2Card(true);- const res: any = await generateMd2Card({ markdown: markdownContent, theme: selectedTheme, themeMode, width: cardWidth, height: cardHeight, splitMode, mdxMode, overHiddenMode });+ if (!markdownContent) {+ message.error(t('aiGenerate.pleaseEnterMarkdown'))+ return+ }+ try {+ setLoadingMd2Card(true)+ const res: any = await generateMd2Card({ markdown: markdownContent, theme: selectedTheme, themeMode, width: cardWidth, height: cardHeight, splitMode, mdxMode, overHiddenMode })if (res?.data?.images?.length) {- const cardUrl = res.data.image[0].url;- setMd2CardResult(cardUrl);-+ const cardUrl = res.data.image[0].url+ setMd2CardResult(cardUrl)+// Auto upload to default media group- await autoUploadToDefaultGroup(cardUrl, "img", "Markdown Card", markdownContent.substring(0, 100));- } else {- setVipModalOpen(true);+ await autoUploadToDefaultGroup(cardUrl, 'img', 'Markdown Card', markdownContent.substring(0, 100))+ }+ else {+ setVipModalOpen(true)}}- catch { setVipModalOpen(true); } finally { setLoadingMd2Card(false); }- };-- const [currentUploadUrl, setCurrentUploadUrl] = useState<string | null>(null);-- // Auto upload to default media group- const autoUploadToDefaultGroup = async (mediaUrl: string, mediaType: "video" | "img", modelName: string, description: string) => {+ catch { setVipModalOpen(true) }+ finally { setLoadingMd2Card(false) }+ }++ const [currentUploadUrl, setCurrentUploadUrl] = useState<string | null>(null)++ const handleUploadToMediaGroup = async (type: string = 'img', url?: string) => {+ setSelectedMediaGroup(null)+ setCurrentUploadUrl(url || (videoResult || fireflyResult || md2CardResult) || null)+ await fetchMediaGroups(type as any)+ setUploadModalVisible(true)+ }+ const handleUploadConfirm = async () => {+ if (!selectedMediaGroup) {+ message.error(t('aiGenerate.pleaseSelectMediaGroup'))+ return+ }try {- // Check if already uploaded- if (uploadedContent.has(mediaUrl)) {- console.log('Content already uploaded:', mediaUrl);- return;- }-- // Get media group list and find default group- const res: any = await getMediaGroupList(1, 100, mediaType);- let defaultGroupId = null;-+ setUploading(true)+ const mediaUrl = currentUploadUrl || videoResult || fireflyResult || md2CardResult+ const mediaType = videoResult ? 'video' : 'img'+ const now = new Date()+ const timeStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`+ const usedModel = videoResult ? videoModel : model+ const uploadTitle = usedModel ? `${usedModel} ${timeStr}` : timeStr+ const uploadDesc = videoResult ? (videoPrompt || '') : (prompt || content || '')+ const res: any = await createMedia({ groupId: selectedMediaGroup, url: mediaUrl, type: mediaType, title: uploadTitle, desc: uploadDesc })if (res.data) {- const groups = res.data.list || [];- const defaultGroup = groups.find((group: any) => group.isDefault === true);- if (defaultGroup) {- defaultGroupId = defaultGroup._id;- setDefaultMediaGroup(defaultGroupId);- }else{- defaultGroupId = groups[0]._id;- setDefaultMediaGroup(defaultGroupId);- }+ message.success(+ videoResult+ ? t('aiGenerate.videoUploadSuccess')+ : md2CardResult+ ? t('aiGenerate.cardUploadSuccess')+ : t('aiGenerate.uploadSuccess'),+ )+ setUploadModalVisible(false)}-- if (!defaultGroupId) {- console.warn('No default media group found');- message.error(t('aiGenerate.noDefaultMediaGroup' as any));- return;- }-- const now = new Date();- const timeStr = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}-${String(now.getDate()).padStart(2,'0')} ${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}`;- const uploadTitle = modelName ? `${modelName} ${timeStr}` : timeStr;-- console.log('开始上传到默认组:', defaultGroupId, mediaUrl);-- const uploadRes: any = await createMedia({- groupId: defaultGroupId,- url: mediaUrl,- type: mediaType,- title: uploadTitle,- desc: description- });-- if (uploadRes.data) {- // Mark as uploaded- setUploadedContent(prev => new Set([...prev, mediaUrl]));- message.success(mediaType === "video" ? t("aiGenerate.videoUploadSuccess") : t("aiGenerate.uploadSuccess"));- console.log('上传成功');- } else {- message.error(mediaType === "video" ? t("aiGenerate.videoUploadFailed") : t("aiGenerate.uploadFailed"));- console.log('上传失败:', uploadRes);+ else {+ message.error(+ videoResult+ ? t('aiGenerate.videoUploadFailed')+ : md2CardResult+ ? t('aiGenerate.cardUploadFailed')+ : t('aiGenerate.uploadFailed'),+ )}- } catch (error) {- console.error('Auto upload failed:', error);- message.error(mediaType === "video" ? t("aiGenerate.videoUploadFailed") : t("aiGenerate.uploadFailed"));- }- };-- const handleUploadToMediaGroup = async (type: string = "img", url?: string) => {- setSelectedMediaGroup(null);- setCurrentUploadUrl(url || (videoResult || fireflyResult || md2CardResult) || null);- await fetchMediaGroups(type as any);- setUploadModalVisible(true);- };- const handleUploadConfirm = async () => {- if (!selectedMediaGroup) { message.error(t("aiGenerate.pleaseSelectMediaGroup")); return; }- try {- setUploading(true);- const mediaUrl = currentUploadUrl || videoResult || fireflyResult || md2CardResult;- const mediaType = videoResult ? "video" : "img";- const now = new Date();- const timeStr = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}-${String(now.getDate()).padStart(2,'0')} ${String(now.getHours()).padStart(2,'0')}:${String(now.getMinutes()).padStart(2,'0')}`;- const usedModel = videoResult ? videoModel : model;- const uploadTitle = usedModel ? `${usedModel} ${timeStr}` : timeStr;- const uploadDesc = videoResult ? (videoPrompt || "") : (prompt || content || "");- const res: any = await createMedia({ groupId: selectedMediaGroup, url: mediaUrl, type: mediaType, title: uploadTitle, desc: uploadDesc });- if (res.data) { message.success(videoResult ? t("aiGenerate.videoUploadSuccess") : md2CardResult ? t("aiGenerate.cardUploadSuccess") : t("aiGenerate.uploadSuccess")); setUploadModalVisible(false); }- else { message.error(videoResult ? t("aiGenerate.videoUploadFailed") : md2CardResult ? t("aiGenerate.cardUploadFailed") : t("aiGenerate.uploadFailed")); }- } catch { message.error(videoResult ? t("aiGenerate.videoUploadFailed") : md2CardResult ? t("aiGenerate.cardUploadFailed") : t("aiGenerate.uploadFailed")); }- finally { setUploading(false); }- };+ }+ catch {+ message.error(+ videoResult+ ? t('aiGenerate.videoUploadFailed')+ : md2CardResult+ ? t('aiGenerate.cardUploadFailed')+ : t('aiGenerate.uploadFailed'),+ )+ }+ finally { setUploading(false) }+ }return (<div className={styles.container}>-<div className={styles.mainLayout}><div className={styles.leftSidebar}><div className={styles.moduleTabs}>- <button title={t("aiGenerate.textToImage")} className={`${styles.moduleTab} ${activeModule === "image" ? styles.moduleTabActive : ""}`} onClick={() => setActiveModule("image")}>+ <button+ title={t('aiGenerate.textToImage')}+ className={`${styles.moduleTab} ${activeModule === 'image'+ ? styles.moduleTabActive+ : ''}`}+ onClick={() => setActiveModule('image')}+ ><PictureOutlined />- </button>- <button title={t("aiGenerate.videoGeneration")} className={`${styles.moduleTab} ${activeModule === "video" ? styles.moduleTabActive : ""}`} onClick={() => setActiveModule("video")}>+ </button>+ <button+ title={t('aiGenerate.videoGeneration')}+ className={`${styles.moduleTab} ${activeModule === 'video'+ ? styles.moduleTabActive+ : ''}`}+ onClick={() => setActiveModule('video')}+ ><VideoCameraOutlined /></button>- </div>- {activeModule === "image" && (+ </div>+ {activeModule === 'image' && (<div className={styles.imageSubTabs}>- <button className={`${styles.subTab} ${activeImageTab==='textToImage' ? styles.subTabActive : ''}`} onClick={()=>setActiveImageTab('textToImage')}>+ <button className={`${styles.subTab} ${activeImageTab === 'textToImage' ? styles.subTabActive : ''}`} onClick={() => setActiveImageTab('textToImage')}><div className="subTabIcon"><PictureOutlined /></div>- <div className={styles.subTabLabel}>{t("aiGenerate.textToImage")}</div>+ <div className={styles.subTabLabel}>{t('aiGenerate.textToImage')}</div></button>- <button className={`${styles.subTab} ${activeImageTab==='imageToImage' ? styles.subTabActive : ''}`} onClick={()=>setActiveImageTab('imageToImage')}>+ <button className={`${styles.subTab} ${activeImageTab === 'imageToImage' ? styles.subTabActive : ''}`} onClick={() => setActiveImageTab('imageToImage')}><div className="subTabIcon"><PictureOutlined /></div>- <div className={styles.subTabLabel}>{t("aiGenerate.imageToImage" as any)}</div>+ <div className={styles.subTabLabel}>{t('aiGenerate.imageToImage' as any)}</div></button>- <button className={`${styles.subTab} ${activeImageTab==='textToFireflyCard' ? styles.subTabActive : ''}`} onClick={()=>setActiveImageTab('textToFireflyCard')}>+ <button+ className={`${styles.subTab} ${activeImageTab === 'textToFireflyCard'+ ? styles.subTabActive+ : ''}`}+ onClick={() => setActiveImageTab('textToFireflyCard')}+ ><div className="subTabIcon"><FireOutlined /></div>- <div className={styles.subTabLabel}>{t("aiGenerate.fireflyCard")}</div>+ <div className={styles.subTabLabel}>{t('aiGenerate.fireflyCard')}</div></button>- <button className={`${styles.subTab} ${activeImageTab==='md2card' ? styles.subTabActive : ''}`} onClick={()=>setActiveImageTab('md2card')}>+ <button className={`${styles.subTab} ${activeImageTab === 'md2card' ? styles.subTabActive : ''}`} onClick={() => setActiveImageTab('md2card')}><div className="subTabIcon"><FileTextOutlined /></div>- <div className={styles.subTabLabel}>{t("aiGenerate.markdownToCard")}</div>+ <div className={styles.subTabLabel}>{t('aiGenerate.markdownToCard')}</div></button>- <button className={`${styles.subTab} ${activeImageTab==='chat' ? styles.subTabActive : ''}`} onClick={()=>setActiveImageTab('chat')}>+ <button className={`${styles.subTab} ${activeImageTab === 'chat' ? styles.subTabActive : ''}`} onClick={() => setActiveImageTab('chat')}><div className="subTabIcon"><MessageOutlined /></div><div className={styles.subTabLabel}>Nano Banana</div></button>- </div>+ </div>)}- {activeModule === "video" && (+ {activeModule === 'video' && (<div className={styles.imageSubTabs}>- <button className={`${styles.subTab} ${activeVideoTab==='text2video' ? styles.subTabActive : ''}`} onClick={()=>setActiveVideoTab('text2video')}>+ <button className={`${styles.subTab} ${activeVideoTab === 'text2video' ? styles.subTabActive : ''}`} onClick={() => setActiveVideoTab('text2video')}><div className="subTabIcon"><VideoCameraOutlined /></div><div className={styles.subTabLabel}>{t('aiGenerate.textToVideo')}</div></button>- <button className={`${styles.subTab} ${activeVideoTab==='image2video' ? styles.subTabActive : ''}`} onClick={()=>setActiveVideoTab('image2video')}>+ <button className={`${styles.subTab} ${activeVideoTab === 'image2video' ? styles.subTabActive : ''}`} onClick={() => setActiveVideoTab('image2video')}><div className="subTabIcon"><PictureOutlined /></div><div className={styles.subTabLabel}>{t('aiGenerate.imageToVideo')}</div></button>@@ -999,88 +1194,101 @@ export default function AIGeneratePage() {</div><div className={styles.rightContent}>- {activeModule === "image" ? (- <>- {activeImageTab === 'textToImage' && (- <div className={styles.section}>- <div className={styles.twoColumn}>- <div className={styles.leftPanel}>- <div className={styles.blockTitle}>{t('aiGenerate.textToImage')}</div>-- <div className={styles.blockTitle} style={{ marginTop: 12 }}>{t('aiGenerate.selectModelPlaceholder')}</div>- <div className={styles.modelSelect}>- <button className={styles.modelSelectBtn} onClick={()=>setShowModelDropdown((s)=>!s)}>- <div className={styles.modelIconSelect}><PictureOutlined style={{fontSize:'24px'}}/></div>- <div className={styles.modelMain}>- <div className={styles.modelHeader}>- <span className={styles.modelName}>{model || t('aiGenerate.selectModelPlaceholder')}</span>- </div>- <div className={styles.modelDesc} style={{ marginTop: 4 }}>- {(() => { const m:any = imageModels.find((x:any)=>x.name===model); return m?.description || ''; })()}</div>- </div>- <span className={styles.modelCaret}>▾</span>- </button>- {showModelDropdown && (- <div className={styles.modelDropdown}>- <div className={styles.modelListScrollable}>- {imageModels.map((m:any)=>{- const isActive = model === m.name;- return (- <div key={m.name} className={`${styles.modelItem} ${isActive?styles.modelItemActive:''}`} onClick={()=>{ setModel(m.name); setShowModelDropdown(false); }}>-- <div className={styles.modelMain}>- <div className={styles.modelHeader}>- <div className={styles.modelIcon}><PictureOutlined /></div>- <span className={styles.modelName}>{m.name || ''}</span>- {m.mainTag ? <span className={styles.modelTag}>New</span> : null}- </div>- <div className={styles.modelDesc}>{m.description || ''}</div>-- <div className={styles.modelMeta}>- {- m?.tags?.length > 0- ?- m?.tags.map((item:string)=> <span key={item}>{item}</span>)- : null- }+ {activeModule === 'image'+ ? (+ <>+ {activeImageTab === 'textToImage' && (+ <div className={styles.section}>+ <div className={styles.twoColumn}>+ <div className={styles.leftPanel}>+ <div className={styles.blockTitle}>{t('aiGenerate.textToImage')}</div>++ <div className={styles.blockTitle} style={{ marginTop: 12 }}>{t('aiGenerate.selectModelPlaceholder')}</div>+ <div className={styles.modelSelect}>+ <button className={styles.modelSelectBtn} onClick={() => setShowModelDropdown(s => !s)}>+ <div className={styles.modelIconSelect}><PictureOutlined style={{ fontSize: '24px' }} /></div>+ <div className={styles.modelMain}>+ <div className={styles.modelHeader}>+ <span className={styles.modelName}>{model || t('aiGenerate.selectModelPlaceholder')}</span>+ </div>+ <div className={styles.modelDesc} style={{ marginTop: 4 }}>+ {(() => {+ const m: any = imageModels.find((x: any) => x.name === model)+ return m?.description || ''+ })()}+ </div>+ </div>+ <span className={styles.modelCaret}>▾</span>+ </button>+ {showModelDropdown && (+ <div className={styles.modelDropdown}>+ <div className={styles.modelListScrollable}>+ {imageModels.map((m: any) => {+ const isActive = model === m.name+ return (+ <div+ key={m.name}+ className={`${styles.modelItem} ${isActive+ ? styles.modelItemActive+ : ''}`}+ onClick={() => {+ setModel(m.name)+ setShowModelDropdown(false)+ }}+ >++ <div className={styles.modelMain}>+ <div className={styles.modelHeader}>+ <div className={styles.modelIcon}><PictureOutlined /></div>+ <span className={styles.modelName}>{m.name || ''}</span>+ {m.mainTag ? <span className={styles.modelTag}>New</span> : null}+ </div>+ <div className={styles.modelDesc}>{m.description || ''}</div>++ <div className={styles.modelMeta}>+ {+ m?.tags?.length > 0+ ? m?.tags.map((item: string) => <span key={item}>{item}</span>)+ : null+ }+ </div>++ </div></div>-- </div>- </div>- );- })}- </div>+ )+ })}+ </div>+ </div>+ )}</div>- )}- </div>- <div className={styles.blockTitle} style={{ marginTop: 1 }}>{t('aiGenerate.promptPlaceholder')}</div>- <TextArea value={prompt} onChange={(e)=>setPrompt(e.target.value)} rows={4} />- <div className={styles.exampleChips}>- {[- t('aiGenerate.examplePrompt1' as any),- t('aiGenerate.examplePrompt2' as any),- t('aiGenerate.examplePrompt3' as any),- t('aiGenerate.examplePrompt4' as any),- t('aiGenerate.examplePrompt5' as any)- ].map((w)=> (- <span key={w as string} className={styles.exampleChip} onClick={()=>setPrompt(w as string)}>{w}</span>- ))}- </div>+ <div className={styles.blockTitle} style={{ marginTop: 1 }}>{t('aiGenerate.promptPlaceholder')}</div>+ <TextArea value={prompt} onChange={e => setPrompt(e.target.value)} rows={4} />+ <div className={styles.exampleChips}>+ {[+ t('aiGenerate.examplePrompt1' as any),+ t('aiGenerate.examplePrompt2' as any),+ t('aiGenerate.examplePrompt3' as any),+ t('aiGenerate.examplePrompt4' as any),+ t('aiGenerate.examplePrompt5' as any),+ ].map(w => (+ <span key={w as string} className={styles.exampleChip} onClick={() => setPrompt(w as string)}>{w}</span>+ ))}+ </div>- <div className={styles.blockTitle} style={{ marginTop: 6 }}>{t('aiGenerate.advancedOptions' as any)}</div>- <div className={styles.dimensions}>- <Select value={size} onChange={setSize} style={{ width: '100%' }}>- {(() => {- const selectedModel = imageModels.find((m: any) => m.name === model);- const sizes = selectedModel?.sizes || ['1024x1024'];- return sizes.map((sizeOption: string) => (- <Option key={sizeOption} value={sizeOption}>{sizeOption}</Option>- ));- })()}- </Select>- </div>- {/* <div className={styles.pillRow}>+ <div className={styles.blockTitle} style={{ marginTop: 6 }}>{t('aiGenerate.advancedOptions' as any)}</div>+ <div className={styles.dimensions}>+ <Select value={size} onChange={setSize} style={{ width: '100%' }}>+ {(() => {+ const selectedModel = imageModels.find((m: any) => m.name === model)+ const sizes = selectedModel?.sizes || ['1024x1024']+ return sizes.map((sizeOption: string) => (+ <Option key={sizeOption} value={sizeOption}>{sizeOption}</Option>+ ))+ })()}+ </Select>+ </div>+ {/* <div className={styles.pillRow}><div className={styles.blockTitle} style={{ marginBottom: 6 }}>{t('aiGenerate.outputImageCount' as any)}</div><div className={styles.pillGroupBox}><div className={styles.pillGroup}>@@ -1090,660 +1298,801 @@ export default function AIGeneratePage() {</div></div></div> */}- <div className={styles.options}>- {(() => {- const selectedModel = imageModels.find((m: any) => m.name === model);- const qualities = selectedModel?.qualities || [];-- if (qualities.length === 0) return null;-- return (- <Select value={quality} onChange={setQuality} style={{ width: '100%' }}>- {qualities.map((q: string) => (- <Option key={q} value={q}>- {q === 'high' ? t('aiGenerate.hd') :- q === 'medium' ? t('aiGenerate.standard') :- q === 'low' ? t('aiGenerate.low' as any) : q}- </Option>- ))}+ <div className={styles.options}>+ {(() => {+ const selectedModel = imageModels.find((m: any) => m.name === model)+ const qualities = selectedModel?.qualities || []++ if (qualities.length === 0)+ return null++ return (+ <Select value={quality} onChange={setQuality} style={{ width: '100%' }}>+ {qualities.map((q: string) => (+ <Option key={q} value={q}>+ {q === 'high'+ ? t('aiGenerate.hd')+ : q === 'medium'+ ? t('aiGenerate.standard')+ : q === 'low' ? t('aiGenerate.low' as any) : q}+ </Option>+ ))}+ </Select>+ )+ })()}+ <Select value={style} onChange={setStyle} style={{ width: '100%' }}>+ <Option value="vivid">{t('aiGenerate.vivid')}</Option>+ <Option value="natural">{t('aiGenerate.natural')}</Option></Select>- );- })()}- <Select value={style} onChange={setStyle} style={{ width: '100%' }}>- <Option value="vivid">{t('aiGenerate.vivid')}</Option>- <Option value="natural">{t('aiGenerate.natural')}</Option>- </Select>- </div>- {model && (()=>{ const selected = imageModels.find((m:any)=>m.name===model); const credit = selected?.pricing ? parseFloat(selected.pricing) : 0; return credit>0 ? (<div className={styles.creditCostInfo}><span style={{color:'#1890ff',fontSize:'14px'}}>💰 {t('aiGenerate.estimatedCreditCost' as any)}: {credit} {t('aiGenerate.credits' as any)}</span></div>) : null; })()}- <Button type="primary" onClick={handleTextToImage} loading={loading} disabled={!prompt || !model} icon={<PictureOutlined />}>{t('aiGenerate.generate')}</Button>+ </div>+ {model && (() => {+ const selected = imageModels.find((m: any) => m.name === model)+ const credit = selected?.pricing ? Number.parseFloat(selected.pricing) : 0+ return credit > 0+ ? (+ <div className={styles.creditCostInfo}>+ <span style={{ color: '#1890ff', fontSize: '14px' }}>+ 💰+ {t('aiGenerate.estimatedCreditCost' as any)}+ :+ {credit}+ {' '}+ {t('aiGenerate.credits' as any)}+ </span>+ </div>+ )+ : null+ })()}+ <Button type="primary" onClick={handleTextToImage} loading={loading} disabled={!prompt || !model} icon={<PictureOutlined />}>{t('aiGenerate.generate')}</Button>+ </div>+ <div className={styles.rightPanel}>+ {(imageStatus || result)+ ? (+ <div className={styles.result}>+ {imageStatus && (+ <div style={{ marginBottom: 16 }}>+ <div style={{ marginBottom: 8 }}>+ <strong>+ {t('aiGenerate.taskStatus')}+ :+ {' '}+ </strong>+ {imageStatus === 'submitted' && t('aiGenerate.taskSubmitted')}+ {imageStatus === 'processing' && t('aiGenerate.taskProcessing')}+ {imageStatus === 'completed' && t('aiGenerate.taskCompleted')}+ {imageStatus === 'failed' && t('aiGenerate.taskFailed')}+ </div>+ {imageProgress > 0 && imageProgress < 100 && (<Progress percent={imageProgress} status="active" />)}+ </div>+ )}+ {result && (+ <Row gutter={[16, 16]} justify="center">+ {result.map((img, idx) => (+ <Col key={idx} xs={24} sm={12} md={12} lg={12}>+ <div className={styles.imageCard}>+ <img src={getOssUrl(img)} alt={`${t('aiGenerate.textToImage')} ${idx + 1}`} />+ <div className={styles.imageActions}>+ <Button size="small" icon={<DownloadOutlined />} onClick={() => handleDownloadUrl(img)} />+ {/* <Button size="small" type="primary" icon={<UploadOutlined />} onClick={()=>handleUploadToMediaGroup('img', img)} /> */}+ </div>+ </div>+ </Col>+ ))}+ </Row>+ )}+ </div>+ )+ : (+ <div className={styles.sampleCarousel}>+ <div className={styles.sampleStage}>+ <img src={sampleImages[sampleIdx]} alt="sample" />+ <button className={styles.samplePrev} onClick={handlePrevSample}>‹</button>+ <button className={styles.sampleNext} onClick={handleNextSample}>›</button>+ </div>+ <div className={styles.sampleDots}>+ {sampleImages.map((_, i) => (+ <span key={i} className={`${styles.sampleDot} ${i === sampleIdx ? styles.sampleDotActive : ''}`} onClick={() => setSampleIdx(i)}></span>+ ))}+ </div>+ </div>+ )}+ </div>+ </div></div>- <div className={styles.rightPanel}>- {(imageStatus || result) ? (- <div className={styles.result}>- {imageStatus && (- <div style={{ marginBottom:16 }}>- <div style={{ marginBottom:8 }}>- <strong>{t('aiGenerate.taskStatus')}: </strong>- {imageStatus === 'submitted' && t('aiGenerate.taskSubmitted')}- {imageStatus === 'processing' && t('aiGenerate.taskProcessing')}- {imageStatus === 'completed' && t('aiGenerate.taskCompleted')}- {imageStatus === 'failed' && t('aiGenerate.taskFailed')}+ )}++ {activeImageTab === 'imageToImage' && (+ <div className={styles.section}>+ <div className={styles.twoColumn}>+ <div className={styles.leftPanel}>+ <div className={styles.blockTitle}>{t('aiGenerate.imageToImage' as any)}</div>++ <div className={styles.blockTitle} style={{ marginTop: 12 }}>{t('aiGenerate.selectModelPlaceholder')}</div>+ <div className={styles.modelSelect}>+ <button className={styles.modelSelectBtn} onClick={() => setShowModelDropdown(s => !s)}>+ <div className={styles.modelIconSelect}><PictureOutlined style={{ fontSize: '24px' }} /></div>+ <div className={styles.modelMain}>+ <div className={styles.modelHeader}>+ <span className={styles.modelName}>{imageEditModel || t('aiGenerate.selectModelPlaceholder')}</span>+ </div>+ <div className={styles.modelDesc} style={{ marginTop: 4 }}>+ {(() => {+ const m: any = imageEditModels.find((x: any) => x.name === imageEditModel)+ return m?.description || ''+ })()}+ </div></div>- {imageProgress>0 && imageProgress<100 && (<Progress percent={imageProgress} status="active" />)}- </div>- )}- {result && (- <Row gutter={[16,16]} justify={'center'}>- {result.map((img, idx)=>(- <Col key={idx} xs={24} sm={12} md={12} lg={12}>- <div className={styles.imageCard}>- <img src={getOssUrl(img)} alt={`${t('aiGenerate.textToImage')} ${idx+1}`} />- <div className={styles.imageActions}>- <Button size="small" icon={<DownloadOutlined />} onClick={()=>handleDownloadUrl(img)} />- {/* <Button size="small" type="primary" icon={<UploadOutlined />} onClick={()=>handleUploadToMediaGroup('img', img)} /> */}+ <span className={styles.modelCaret}>▾</span>+ </button>+ {showModelDropdown && (+ <div className={styles.modelDropdown}>+ <div className={styles.modelListScrollable}>+ {imageEditModels.map((m: any) => {+ const isActive = imageEditModel === m.name+ return (+ <div+ key={m.name}+ className={`${styles.modelItem} ${isActive+ ? styles.modelItemActive+ : ''}`}+ onClick={() => {+ setImageEditModel(m.name)+ setShowModelDropdown(false)+ }}+ >++ <div className={styles.modelMain}>+ <div className={styles.modelHeader}>+ <div className={styles.modelIcon}><PictureOutlined /></div>+ <span className={styles.modelName}>{m.name || ''}</span>+ {m.mainTag ? <span className={styles.modelTag}>New</span> : null}+ </div>+ <div className={styles.modelDesc}>{m.description || ''}</div>++ <div className={styles.modelMeta}>+ {+ m?.tags?.length > 0+ ? m?.tags.map((item: string) => <span key={item}>{item}</span>)+ : null+ }+ </div>++ </div>+ </div>+ )+ })}+ </div>+ </div>+ )}+ </div>++ <div className={styles.blockTitle} style={{ marginTop: 1 }}>{t('aiGenerate.promptPlaceholder')}</div>+ <TextArea value={imageEditPrompt} onChange={e => setImageEditPrompt(e.target.value)} rows={4} />++ <div className={styles.blockTitle} style={{ marginTop: 6 }}>{t('aiGenerate.uploadImage')}</div>+ <div className={styles.uploadPanel}>+ {(() => {+ const selectedModel = imageEditModels.find((m: any) => m.name === imageEditModel)+ const maxImages = selectedModel?.maxInputImages || 1+ const isMaxReached = sourceImages.length >= maxImages++ return (+ <div+ className={`${styles.uploadCard} ${isMaxReached ? styles.uploadCardDisabled : ''}`}+ onClick={() => !isMaxReached && firstFrameInputRef.current?.click()}+ style={{+ cursor: isMaxReached ? 'not-allowed' : 'pointer',+ opacity: isMaxReached ? 0.5 : 1,+ }}+ >+ <div className={styles.uploadPlaceholder}>+ <span className={styles.uploadIcon}>+</span>+ <span className={styles.uploadText}>+ {isMaxReached+ ? t('aiGenerate.maxUploadReached' as any, { count: maxImages })+ : t('aiGenerate.imageUrlPlaceholder')}+ </span>+ </div>+ <input+ type="file"+ accept="image/*"+ multiple+ ref={firstFrameInputRef}+ onChange={handleSourceImageChange}+ style={{ display: 'none' }}+ disabled={isMaxReached}+ />+ </div>+ )+ })()}++ {sourceImages.length > 0 && (+ <div className={styles.imageGrid}>+ {sourceImages.map((img, index) => (+ <div key={index} className={styles.imageItem}>+ <img src={img} alt={`${t('aiGenerate.sourceImage' as any)} ${index + 1}`} />+ <button+ className={styles.removeBtn}+ onClick={() => handleRemoveSourceImage(index)}+ title={t('aiGenerate.deleteImage' as any)}+ >+ ×+ </button>+ </div>+ ))}+ </div>+ )}++ {sourceImages.length > 0 && (+ <button+ className={styles.clearAllBtn}+ onClick={handleClearAllSourceImages}+ style={{ marginTop: 8, fontSize: '12px', color: '#ff4d4f' }}+ >+ {t('aiGenerate.clearAllImages' as any)}+ </button>+ )}++ {imageEditModel && (() => {+ const selectedModel = imageEditModels.find((m: any) => m.name === imageEditModel)+ console.log(selectedModel, 'selectedModel')+ const maxImages = selectedModel?.maxInputImages || 1+ return (+ <div className={styles.maxImagesInfo}>+ <span style={{ color: '#1890ff', fontSize: '12px' }}>++ {t('aiGenerate.maxImages' as any) }+ {' '}+ { maxImages}+ </span>+ </div>+ )+ })()}+ </div>++ <div className={styles.blockTitle} style={{ marginTop: 6 }}>{t('aiGenerate.advancedOptions' as any)}</div>+ <div className={styles.dimensions}>+ <Select value={imageEditSize} onChange={setImageEditSize} style={{ width: '100%' }}>+ {(() => {+ const selectedModel = imageEditModels.find((m: any) => m.name === imageEditModel)+ const sizes = selectedModel?.sizes || ['1024x1024']+ return sizes.map((size: string) => (+ <Option key={size} value={size}>{size}</Option>+ ))+ })()}+ </Select>+ </div>+ {/* <div className={styles.pillRow}>+ <div className={styles.blockTitle} style={{ marginBottom: 6 }}>{t('aiGenerate.outputImageCount' as any)}</div>+ <div className={styles.pillGroupBox}>+ <div className={styles.pillGroup}>+ {[1,2,3,4].map((num)=> (+ <button key={num} className={`${styles.pill} ${imageEditN===num?styles.pillActive:''}`} onClick={()=>setImageEditN(num)}>{num}</button>+ ))}+ </div>+ </div>+ </div> */}+ {imageEditModel && (() => {+ const selected = imageEditModels.find((m: any) => m.name === imageEditModel)+ const credit = selected?.pricing ? Number.parseFloat(selected.pricing) : 0+ return credit > 0+ ? (+ <div className={styles.creditCostInfo}>+ <span style={{ color: '#1890ff', fontSize: '14px' }}>+ 💰+ {t('aiGenerate.estimatedCreditCost' as any)}+ :+ {credit}+ {' '}+ {t('aiGenerate.credits' as any)}+ </span>+ </div>+ )+ : null+ })()}+ <Button type="primary" onClick={handleImageEdit} loading={imageEditLoading} disabled={!imageEditPrompt || !imageEditModel || !sourceImages.length} icon={<PictureOutlined />}>{t('aiGenerate.generate')}</Button>+ </div>+ <div className={styles.rightPanel}>+ {(imageEditStatus || imageEditResult)+ ? (+ <div className={styles.result}>+ {imageEditStatus && (+ <div style={{ marginBottom: 16 }}>+ <div style={{ marginBottom: 8 }}>+ <strong>+ {t('aiGenerate.taskStatus')}+ :+ {' '}+ </strong>+ {imageEditStatus === 'submitted' && t('aiGenerate.taskSubmitted')}+ {imageEditStatus === 'processing' && t('aiGenerate.taskProcessing')}+ {imageEditStatus === 'completed' && t('aiGenerate.taskCompleted')}+ {imageEditStatus === 'failed' && t('aiGenerate.taskFailed')}+ </div>+ {imageEditProgress > 0 && imageEditProgress < 100 && (<Progress percent={imageEditProgress} status="active" />)}</div>+ )}+ {imageEditResult && (+ <Row gutter={[16, 16]} justify="center">+ {imageEditResult.map((img, idx) => (+ <Col key={idx} xs={24} sm={12} md={12} lg={12}>+ <div className={styles.imageCard}>+ <img src={getOssUrl(img)} alt={`${t('aiGenerate.imageToImage' as any)} ${idx + 1}`} />+ <div className={styles.imageActions}>+ <Button size="small" icon={<DownloadOutlined />} onClick={() => handleDownloadUrl(img)} />+ {/* <Button size="small" type="primary" icon={<UploadOutlined />} onClick={()=>handleUploadToMediaGroup('img', img)} /> */}+ </div>+ </div>+ </Col>+ ))}+ </Row>+ )}+ </div>+ )+ : (+ <div className={styles.sampleCarousel}>+ <div className={styles.sampleStage}>+ <img src={sampleImages[sampleIdx]} alt="sample" />+ <button className={styles.samplePrev} onClick={handlePrevSample}>‹</button>+ <button className={styles.sampleNext} onClick={handleNextSample}>›</button></div>- </Col>- ))}- </Row>- )}+ <div className={styles.sampleDots}>+ {sampleImages.map((_, i) => (+ <span key={i} className={`${styles.sampleDot} ${i === sampleIdx ? styles.sampleDotActive : ''}`} onClick={() => setSampleIdx(i)}></span>+ ))}+ </div>+ </div>+ )}</div>- ) : (- <div className={styles.sampleCarousel}>- <div className={styles.sampleStage}>- <img src={sampleImages[sampleIdx]} alt="sample" />- <button className={styles.samplePrev} onClick={handlePrevSample}>‹</button>- <button className={styles.sampleNext} onClick={handleNextSample}>›</button>+ </div>+ </div>+ )}++ {activeImageTab === 'textToFireflyCard' && (+ <div className={styles.section}>+ <div className={styles.twoColumn}>+ <div className={styles.leftPanel}>+ <div className={styles.blockTitle}>{t('aiGenerate.fireflyCard')}</div>+ <Input placeholder={t('aiGenerate.titlePlaceholder')} value={title} onChange={e => setTitle(e.target.value)} prefix={<FileTextOutlined />} />+ <TextArea placeholder={t('aiGenerate.contentPlaceholder')} value={content} onChange={e => setContent(e.target.value)} rows={4} />+ <div className={styles.templateGrid}>+ {templateList.map(item => (+ <div key={item.key} className={`${styles.templateCard} ${temp === item.key ? styles.templateCardActive : ''}`} onClick={() => setTemp(item.key)}>+ <div className={styles.templateThumb}><img src={`${TEMPLATE_BASE}/${item.key}.png`} alt={`${t('aiGenerate.template')} ${item.name}`} /></div>+ <div className={styles.templateLabel}>{item.name}</div>+ </div>+ ))}</div>- <div className={styles.sampleDots}>- {sampleImages.map((_,i)=>(- <span key={i} className={`${styles.sampleDot} ${i===sampleIdx?styles.sampleDotActive:''}`} onClick={()=>setSampleIdx(i)}></span>+ <Button type="primary" onClick={handleTextToFireflyCard} loading={loadingFirefly} disabled={!content || !title} icon={<FireOutlined />}>{t('aiGenerate.generate')}</Button>+ </div>+ <div className={styles.rightPanel}>+ <div className={styles.result}>+ <div className={styles.imageCard}>+ {fireflyResult+ ? (+ <img src={getOssUrl(fireflyResult)} alt={t('aiGenerate.fireflyCard')} />+ )+ : (+ <img src={`${TEMPLATE_BASE}/${temp}.png`} alt={t('aiGenerate.fireflyCard')} />+ )}+ {fireflyResult && (+ <div className={styles.imageActions}>+ <Button size="small" icon={<DownloadOutlined />} onClick={() => handleDownloadUrl(fireflyResult)} />+ {/* <Button size="small" type="primary" icon={<UploadOutlined />} onClick={()=>handleUploadToMediaGroup('img', fireflyResult)} /> */}+ </div>+ )}+ </div>+ </div>+ </div>+ </div>+ </div>+ )}++ {activeImageTab === 'md2card' && (+ <div className={styles.section}>+ <div className={styles.twoColumn}>+ <div className={styles.leftPanel}>+ <div className={styles.blockTitle}>{t('aiGenerate.markdownToCard')}</div>+ <TextArea style={{ height: 100 }} placeholder={t('aiGenerate.markdownPlaceholder')} value={markdownContent} onChange={e => setMarkdownContent(e.target.value)} rows={8} />+ <div className={styles.dimensions}>+ <Select value={themeMode} onChange={setThemeMode} style={{ width: '100%' }}>+ <Option value="light">{t('aiGenerate.lightMode')}</Option>+ <Option value="dark">{t('aiGenerate.darkMode')}</Option>+ </Select>+ </div>+ <div className={styles.templateGrid}>+ {md2CardTemplates.map(theme => (+ <div+ key={theme.id}+ className={`${styles.templateCard} ${selectedTheme === theme.id+ ? styles.templateCardActive+ : ''}`}+ onClick={() => setSelectedTheme(theme.id)}+ >+ <div className={styles.templateThumb}><img src={theme.preview} alt={isEnglishLang ? theme.nameEn : theme.nameCn} /></div>+ <div className={styles.templateLabel}>{isEnglishLang ? theme.nameEn : theme.nameCn}</div>+ </div>))}</div>+ <div className={styles.options}>+ <Input placeholder={t('aiGenerate.cardWidthPlaceholder')} type="number" value={cardWidth} onChange={e => setCardWidth(Number(e.target.value))} style={{ width: '100%' }} />+ <Input placeholder={t('aiGenerate.cardHeightPlaceholder')} type="number" value={cardHeight} onChange={e => setCardHeight(Number(e.target.value))} style={{ width: '100%' }} />+ </div>+ <div className={styles.options}>+ <Select value={splitMode} onChange={setSplitMode} style={{ width: '100%' }}>+ <Option value="noSplit">{t('aiGenerate.noSplit')}</Option>+ <Option value="split">{t('aiGenerate.split')}</Option>+ </Select>+ <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>+ <label>+ <input type="checkbox" checked={mdxMode} onChange={e => setMdxMode(e.target.checked)} />+ {' '}+ {t('aiGenerate.mdxMode')}+ </label>+ <label>+ <input type="checkbox" checked={overHiddenMode} onChange={e => setOverHiddenMode(e.target.checked)} />+ {' '}+ {t('aiGenerate.overHiddenMode')}+ </label>+ </div>+ </div>+ <Button type="primary" onClick={handleMd2CardGeneration} loading={loadingMd2Card} disabled={!markdownContent} icon={<FileTextOutlined />}>{t('aiGenerate.generateCard')}</Button></div>- )}+ <div className={styles.rightPanel}>+ <div className={styles.result}>+ <div className={styles.imageCard}>+ {md2CardResult+ ? (+ <img src={getOssUrl(md2CardResult)} alt={t('aiGenerate.markdownCard')} />+ )+ : (+ (() => {+ const theme = md2CardTemplates.find(t => t.id === selectedTheme)+ return (+ <img src={theme?.preview} alt={isEnglishLang ? theme?.nameEn : theme?.nameCn} />+ )+ })()+ )}+ {md2CardResult && (+ <div className={styles.imageActions}>+ <Button size="small" icon={<DownloadOutlined />} onClick={() => handleDownloadUrl(md2CardResult)} />+ {/* <Button size="small" type="primary" icon={<UploadOutlined />} onClick={()=>handleUploadToMediaGroup('img', md2CardResult)} /> */}+ </div>+ )}+ </div>+ </div>+ </div>+ </div></div>- </div>- </div>- )}+ )}- {activeImageTab === 'imageToImage' && (+ {activeImageTab === 'chat' && (+ <div className={styles.chatSection}>+ <div className={styles.chatContainer}>+ <Chat defaultMask="100000" />+ </div>+ </div>+ )}+ </>+ )+ : (<div className={styles.section}><div className={styles.twoColumn}><div className={styles.leftPanel}>- <div className={styles.blockTitle}>{t('aiGenerate.imageToImage' as any)}</div>+ <div className={styles.blockTitle}>+ {activeVideoTab === 'text2video'+ ? t('aiGenerate.textToVideo')+ : activeVideoTab === 'image2video'+ ? t('aiGenerate.imageToVideo')+ : t('aiGenerate.textToVideo')}+ </div>+ {(() => {+ if (videoMode !== activeVideoTab)+ setVideoMode(activeVideoTab)+ return null+ })()}<div className={styles.blockTitle} style={{ marginTop: 12 }}>{t('aiGenerate.selectModelPlaceholder')}</div><div className={styles.modelSelect}>- <button className={styles.modelSelectBtn} onClick={()=>setShowModelDropdown((s)=>!s)}>- <div className={styles.modelIconSelect}><PictureOutlined style={{fontSize:'24px'}}/></div>+ <button className={styles.modelSelectBtn} onClick={() => setShowVideoModelDropdown(s => !s)}>+ <div className={styles.modelIconSelect}><VideoCameraOutlined style={{ fontSize: '24px' }} /></div><div className={styles.modelMain}><div className={styles.modelHeader}>- <span className={styles.modelName}>{imageEditModel || t('aiGenerate.selectModelPlaceholder')}</span>+ <span className={styles.modelName}>{videoModel || t('aiGenerate.selectModelPlaceholder')}</span>+ </div>+ <div className={styles.modelDesc} style={{ marginTop: 4 }}>+ {(() => {+ const m: any = (filteredVideoModels as any[]).find((x: any) => x.name === videoModel)+ return m?.description || ''+ })()}</div>- <div className={styles.modelDesc} style={{ marginTop: 4 }}>{(() => { const m:any = imageEditModels.find((x:any)=>x.name===imageEditModel); return m?.description || ''; })()}</div></div><span className={styles.modelCaret}>▾</span></button>- {showModelDropdown && (+ {showVideoModelDropdown && (<div className={styles.modelDropdown}><div className={styles.modelListScrollable}>- {imageEditModels.map((m:any)=>{- const isActive = imageEditModel === m.name;+ {(filteredVideoModels as any[]).map((m: any) => {+ const isActive = videoModel === m.namereturn (- <div key={m.name} className={`${styles.modelItem} ${isActive?styles.modelItemActive:''}`} onClick={()=>{ setImageEditModel(m.name); setShowModelDropdown(false); }}>-+ <div+ key={m.name}+ className={`${styles.modelItem} ${isActive+ ? styles.modelItemActive+ : ''}`}+ onClick={() => {+ setVideoModel(m.name)+ setShowVideoModelDropdown(false)+ }}+ >+<div className={styles.modelMain}><div className={styles.modelHeader}>- <div className={styles.modelIcon}><PictureOutlined /></div>+ <div className={styles.modelIcon}><VideoCameraOutlined /></div><span className={styles.modelName}>{m.name || ''}</span>- {m.mainTag ? <span className={styles.modelTag}>New</span> : null}+ {m.mainTag || m.name.includes('sora') ? <span className={styles.modelTag}>New</span> : null}</div><div className={styles.modelDesc}>{m.description || ''}</div><div className={styles.modelMeta}>- {- m?.tags?.length > 0- ?- m?.tags.map((item:string)=> <span key={item}>{item}</span>)- : null- }+ {+ m?.tags?.length > 0+ ? m?.tags.map((item: string) => <span key={item}>{item}</span>)+ : null+ }</div>-+</div></div>- );+ )})}</div></div>)}</div>- <div className={styles.blockTitle} style={{ marginTop: 1 }}>{t('aiGenerate.promptPlaceholder')}</div>- <TextArea value={imageEditPrompt} onChange={(e)=>setImageEditPrompt(e.target.value)} rows={4} />+ <TextArea placeholder={t('aiGenerate.videoPromptPlaceholder')} value={videoPrompt} onChange={e => setVideoPrompt(e.target.value)} rows={4} />- <div className={styles.blockTitle} style={{ marginTop: 6 }}>{t('aiGenerate.uploadImage')}</div>- <div className={styles.uploadPanel}>- {(() => {- const selectedModel = imageEditModels.find((m: any) => m.name === imageEditModel);- const maxImages = selectedModel?.maxInputImages || 1;- const isMaxReached = sourceImages.length >= maxImages;-- return (- <div- className={`${styles.uploadCard} ${isMaxReached ? styles.uploadCardDisabled : ''}`}- onClick={() => !isMaxReached && firstFrameInputRef.current?.click()}- style={{- cursor: isMaxReached ? 'not-allowed' : 'pointer',- opacity: isMaxReached ? 0.5 : 1- }}- >- <div className={styles.uploadPlaceholder}>- <span className={styles.uploadIcon}>+</span>- <span className={styles.uploadText}>- {isMaxReached- ? t('aiGenerate.maxUploadReached' as any, { count: maxImages })- : t('aiGenerate.imageUrlPlaceholder')- }- </span>- </div>- <input- type="file"- accept="image/*"- multiple- ref={firstFrameInputRef}- onChange={handleSourceImageChange}- style={{ display:'none' }}- disabled={isMaxReached}- />- </div>- );- })()}-- {sourceImages.length > 0 && (- <div className={styles.imageGrid}>- {sourceImages.map((img, index) => (- <div key={index} className={styles.imageItem}>- <img src={img} alt={`${t('aiGenerate.sourceImage' as any)} ${index + 1}`} />- <button- className={styles.removeBtn}- onClick={() => handleRemoveSourceImage(index)}- title={t('aiGenerate.deleteImage' as any)}- >- ×- </button>- </div>- ))}- </div>- )}-- {sourceImages.length > 0 && (- <button- className={styles.clearAllBtn}- onClick={handleClearAllSourceImages}- style={{ marginTop: 8, fontSize: '12px', color: '#ff4d4f' }}- >- {t('aiGenerate.clearAllImages' as any)}- </button>- )}-- {imageEditModel && (() => {- const selectedModel = imageEditModels.find((m: any) => m.name === imageEditModel);- console.log(selectedModel, 'selectedModel');- const maxImages = selectedModel?.maxInputImages || 1;- return (- <div className={styles.maxImagesInfo}>- <span style={{color:'#1890ff',fontSize:'12px'}}>-- {t('aiGenerate.maxImages' as any) } { maxImages}- </span>- </div>- );- })()}- </div>-- <div className={styles.blockTitle} style={{ marginTop: 6 }}>{t('aiGenerate.advancedOptions' as any)}</div><div className={styles.dimensions}>- <Select value={imageEditSize} onChange={setImageEditSize} style={{ width: '100%' }}>+ <Select value={videoSize} onChange={setVideoSize} style={{ width: '100%' }}>{(() => {- const selectedModel = imageEditModels.find((m: any) => m.name === imageEditModel);- const sizes = selectedModel?.sizes || ['1024x1024'];- return sizes.map((size: string) => (- <Option key={size} value={size}>{size}</Option>- ));+ const selected: any = (filteredVideoModels as any[]).find((m: any) => m.name === videoModel) || {}++ // If kling model, get resolution options from pricing mode field+ if (selected?.channel === 'kling' && selected?.pricing) {+ const modes = [...new Set(selected.pricing.map((p: any) => p.mode))] as string[]+ return modes.map((mode: string) => (+ <Option key={mode} value={mode}>{mode}</Option>+ ))+ }++ // Other models get from resolutions field+ const sizes: string[] = selected?.resolutions || []+ return sizes.map(s => (<Option key={s} value={s}>{s}</Option>))})()}</Select>- </div>- {/* <div className={styles.pillRow}>- <div className={styles.blockTitle} style={{ marginBottom: 6 }}>{t('aiGenerate.outputImageCount' as any)}</div>- <div className={styles.pillGroupBox}>- <div className={styles.pillGroup}>- {[1,2,3,4].map((num)=> (- <button key={num} className={`${styles.pill} ${imageEditN===num?styles.pillActive:''}`} onClick={()=>setImageEditN(num)}>{num}</button>- ))}- </div>- </div>- </div> */}- {imageEditModel && (()=>{ const selected = imageEditModels.find((m:any)=>m.name===imageEditModel); const credit = selected?.pricing ? parseFloat(selected.pricing) : 0; return credit>0 ? (<div className={styles.creditCostInfo}><span style={{color:'#1890ff',fontSize:'14px'}}>💰 {t('aiGenerate.estimatedCreditCost' as any)}: {credit} {t('aiGenerate.credits' as any)}</span></div>) : null; })()}- <Button type="primary" onClick={handleImageEdit} loading={imageEditLoading} disabled={!imageEditPrompt || !imageEditModel || !sourceImages.length} icon={<PictureOutlined />}>{t('aiGenerate.generate')}</Button>- </div>- <div className={styles.rightPanel}>- {(imageEditStatus || imageEditResult) ? (- <div className={styles.result}>- {imageEditStatus && (- <div style={{ marginBottom:16 }}>- <div style={{ marginBottom:8 }}>- <strong>{t('aiGenerate.taskStatus')}: </strong>- {imageEditStatus === 'submitted' && t('aiGenerate.taskSubmitted')}- {imageEditStatus === 'processing' && t('aiGenerate.taskProcessing')}- {imageEditStatus === 'completed' && t('aiGenerate.taskCompleted')}- {imageEditStatus === 'failed' && t('aiGenerate.taskFailed')}- </div>- {imageEditProgress>0 && imageEditProgress<100 && (<Progress percent={imageEditProgress} status="active" />)}- </div>- )}- {imageEditResult && (- <Row gutter={[16,16]} justify={'center'}>- {imageEditResult.map((img, idx)=>(- <Col key={idx} xs={24} sm={12} md={12} lg={12}>- <div className={styles.imageCard}>- <img src={getOssUrl(img)} alt={`${t('aiGenerate.imageToImage' as any)} ${idx+1}`} />- <div className={styles.imageActions}>- <Button size="small" icon={<DownloadOutlined />} onClick={()=>handleDownloadUrl(img)} />- {/* <Button size="small" type="primary" icon={<UploadOutlined />} onClick={()=>handleUploadToMediaGroup('img', img)} /> */}- </div>- </div>- </Col>- ))}- </Row>- )}- </div>- ) : (- <div className={styles.sampleCarousel}>- <div className={styles.sampleStage}>- <img src={sampleImages[sampleIdx]} alt="sample" />- <button className={styles.samplePrev} onClick={handlePrevSample}>‹</button>- <button className={styles.sampleNext} onClick={handleNextSample}>›</button>- </div>- <div className={styles.sampleDots}>- {sampleImages.map((_,i)=>(- <span key={i} className={`${styles.sampleDot} ${i===sampleIdx?styles.sampleDotActive:''}`} onClick={()=>setSampleIdx(i)}></span>- ))}- </div>- </div>- )}- </div>- </div>- </div>- )}- {activeImageTab === 'textToFireflyCard' && (- <div className={styles.section}>- <div className={styles.twoColumn}>- <div className={styles.leftPanel}>- <div className={styles.blockTitle}>{t('aiGenerate.fireflyCard')}</div>- <Input placeholder={t("aiGenerate.titlePlaceholder")} value={title} onChange={(e)=>setTitle(e.target.value)} prefix={<FileTextOutlined />} />- <TextArea placeholder={t("aiGenerate.contentPlaceholder")} value={content} onChange={(e)=>setContent(e.target.value)} rows={4} />- <div className={styles.templateGrid}>- {templateList.map((item)=> (- <div key={item.key} className={`${styles.templateCard} ${temp===item.key?styles.templateCardActive:""}`} onClick={()=>setTemp(item.key)}>- <div className={styles.templateThumb}><img src={`${TEMPLATE_BASE}/${item.key}.png`} alt={`${t('aiGenerate.template')} ${item.name}`} /></div>- <div className={styles.templateLabel}>{item.name}</div>- </div>- ))}- </div>- <Button type="primary" onClick={handleTextToFireflyCard} loading={loadingFirefly} disabled={!content||!title} icon={<FireOutlined />}>{t("aiGenerate.generate")}</Button>- </div>- <div className={styles.rightPanel}>- <div className={styles.result}>- <div className={styles.imageCard}>- {fireflyResult ? (- <img src={getOssUrl(fireflyResult)} alt={t('aiGenerate.fireflyCard')} />- ) : (- <img src={`${TEMPLATE_BASE}/${temp}.png`} alt={t('aiGenerate.fireflyCard')} />- )}- {fireflyResult && (- <div className={styles.imageActions}>- <Button size="small" icon={<DownloadOutlined />} onClick={()=>handleDownloadUrl(fireflyResult)} />- {/* <Button size="small" type="primary" icon={<UploadOutlined />} onClick={()=>handleUploadToMediaGroup('img', fireflyResult)} /> */}- </div>- )}- </div>- </div>- </div>- </div>- </div>- )}-- {activeImageTab === 'md2card' && (- <div className={styles.section}>- <div className={styles.twoColumn}>- <div className={styles.leftPanel}>- <div className={styles.blockTitle}>{t('aiGenerate.markdownToCard')}</div>- <TextArea style={{ height: 100 }} placeholder={t("aiGenerate.markdownPlaceholder")} value={markdownContent} onChange={(e)=>setMarkdownContent(e.target.value)} rows={8} />- <div className={styles.dimensions}>- <Select value={themeMode} onChange={setThemeMode} style={{ width: "100%" }}>- <Option value="light">{t("aiGenerate.lightMode")}</Option>- <Option value="dark">{t("aiGenerate.darkMode")}</Option>+ <Select value={videoDuration} onChange={setVideoDuration} style={{ width: '100%' }}>+ {(() => {+ const selected: any = (filteredVideoModels as any[]).find((m: any) => m.name === videoModel) || {}++ // If kling model, get duration options from pricing duration field+ if (selected?.channel === 'kling' && selected?.pricing) {+ const durations = [...new Set(selected.pricing.map((p: any) => p.duration))] as number[]+ return durations.map((d: number) => (+ <Option key={d} value={d}>+ {d}+ {t('aiGenerate.seconds')}+ </Option>+ ))+ }++ // Other models get from durations field+ const durs: number[] = selected?.durations || []+ return durs.map(d => (+ <Option key={d} value={d}>+ {d}+ {t('aiGenerate.seconds')}+ </Option>+ ))+ })()}</Select></div>- <div className={styles.templateGrid}>- {md2CardTemplates.map((theme)=> (- <div key={theme.id} className={`${styles.templateCard} ${selectedTheme===theme.id?styles.templateCardActive:""}`} onClick={()=>setSelectedTheme(theme.id)}>- <div className={styles.templateThumb}><img src={theme.preview} alt={isEnglishLang ? theme.nameEn : theme.nameCn} /></div>- <div className={styles.templateLabel}>{isEnglishLang ? theme.nameEn : theme.nameCn}</div>- </div>- ))}- </div>- <div className={styles.options}>- <Input placeholder={t("aiGenerate.cardWidthPlaceholder")} type="number" value={cardWidth} onChange={(e)=>setCardWidth(Number(e.target.value))} style={{ width: "100%" }} />- <Input placeholder={t("aiGenerate.cardHeightPlaceholder")} type="number" value={cardHeight} onChange={(e)=>setCardHeight(Number(e.target.value))} style={{ width: "100%" }} />- </div><div className={styles.options}>- <Select value={splitMode} onChange={setSplitMode} style={{ width: "100%" }}>- <Option value="noSplit">{t("aiGenerate.noSplit")}</Option>- <Option value="split">{t("aiGenerate.split")}</Option>- </Select>- <div style={{ display:"flex", gap:8, alignItems:"center" }}>- <label><input type="checkbox" checked={mdxMode} onChange={(e)=>setMdxMode(e.target.checked)} /> {t("aiGenerate.mdxMode")}</label>- <label><input type="checkbox" checked={overHiddenMode} onChange={(e)=>setOverHiddenMode(e.target.checked)} /> {t("aiGenerate.overHiddenMode")}</label>- </div>- </div>- <Button type="primary" onClick={handleMd2CardGeneration} loading={loadingMd2Card} disabled={!markdownContent} icon={<FileTextOutlined />}>{t("aiGenerate.generateCard")}</Button>- </div>- <div className={styles.rightPanel}>- <div className={styles.result}>- <div className={styles.imageCard}>- {md2CardResult ? (- <img src={getOssUrl(md2CardResult)} alt={t('aiGenerate.markdownCard')} />- ) : (- (() => { const theme = md2CardTemplates.find((t)=>t.id===selectedTheme); return (- <img src={theme?.preview} alt={isEnglishLang ? theme?.nameEn : theme?.nameCn} />- ); })()- )}- {md2CardResult && (- <div className={styles.imageActions}>- <Button size="small" icon={<DownloadOutlined />} onClick={()=>handleDownloadUrl(md2CardResult)} />- {/* <Button size="small" type="primary" icon={<UploadOutlined />} onClick={()=>handleUploadToMediaGroup('img', md2CardResult)} /> */}- </div>- )}- </div>- </div>- </div>- </div>- </div>- )}+ {(() => {+ const selected: any = (filteredVideoModels as any[]).find((m: any) => m.name === videoModel) || {}+ const supported: string[] = selected?.supportedParameters || []+ const modes: string[] = selected?.modes || []- {activeImageTab === 'chat' && (- <div className={styles.chatSection}>- <div className={styles.chatContainer}>- <Chat defaultMask='100000' />- </div>- </div>- )}- </>- ) : (- <div className={styles.section}>- <div className={styles.twoColumn}>- <div className={styles.leftPanel}>- <div className={styles.blockTitle}>- {activeVideoTab==='text2video' ? t('aiGenerate.textToVideo') :- activeVideoTab==='image2video' ? t('aiGenerate.imageToVideo') : t('aiGenerate.textToVideo')}- </div>- {(() => { if (videoMode !== activeVideoTab) setVideoMode(activeVideoTab); return null; })()}-- <div className={styles.blockTitle} style={{ marginTop: 12 }}>{t('aiGenerate.selectModelPlaceholder')}</div>- <div className={styles.modelSelect}>- <button className={styles.modelSelectBtn} onClick={()=>setShowVideoModelDropdown((s)=>!s)}>- <div className={styles.modelIconSelect}><VideoCameraOutlined style={{fontSize:'24px'}}/></div>- <div className={styles.modelMain}>- <div className={styles.modelHeader}>- <span className={styles.modelName}>{videoModel || t('aiGenerate.selectModelPlaceholder')}</span>- </div>- <div className={styles.modelDesc} style={{ marginTop: 4 }}>- {(() => { const m:any = (filteredVideoModels as any[]).find((x:any)=>x.name===videoModel); return m?.description || ''; })()}</div>- </div>- <span className={styles.modelCaret}>▾</span>- </button>- {showVideoModelDropdown && (- <div className={styles.modelDropdown}>- <div className={styles.modelListScrollable}>- {(filteredVideoModels as any[]).map((m:any)=>{- const isActive = videoModel === m.name;- return (- <div key={m.name} className={`${styles.modelItem} ${isActive?styles.modelItemActive:''}`} onClick={()=>{ setVideoModel(m.name); setShowVideoModelDropdown(false); }}>-- <div className={styles.modelMain}>- <div className={styles.modelHeader}>- <div className={styles.modelIcon}><VideoCameraOutlined /></div>- <span className={styles.modelName}>{m.name || ''}</span>- {m.mainTag || m.name.includes('sora') ? <span className={styles.modelTag}>New</span> : null}- </div>- <div className={styles.modelDesc}>{m.description || ''}</div>-- <div className={styles.modelMeta}>- {- m?.tags?.length > 0- ?- m?.tags.map((item:string)=> <span key={item}>{item}</span>)- : null- }- </div>-- </div>- </div>- );- })}- </div>- </div>- )}- </div>+ // Determine video generation type based on modes+ const isImage2Video = modes.includes('image2video')+ const isFlf2Video = modes.includes('flf2video')+ const isLf2Video = modes.includes('lf2video')+ const isMultiImage2Video = modes.includes('multi-image2video')- <TextArea placeholder={t('aiGenerate.videoPromptPlaceholder')} value={videoPrompt} onChange={(e)=>setVideoPrompt(e.target.value)} rows={4} />-- <div className={styles.dimensions}>- <Select value={videoSize} onChange={setVideoSize} style={{ width: "100%" }}>{(()=>{- const selected:any=(filteredVideoModels as any[]).find((m:any)=>m.name===videoModel)||{};-- // If kling model, get resolution options from pricing mode field- if (selected?.channel === 'kling' && selected?.pricing) {- const modes = [...new Set(selected.pricing.map((p: any) => p.mode))] as string[];- return modes.map((mode: string) => (- <Option key={mode} value={mode}>{mode}</Option>- ));- }-- // Other models get from resolutions field- const sizes:string[]=selected?.resolutions||[];- return sizes.map((s)=> (<Option key={s} value={s}>{s}</Option>));- })()}</Select>-- <Select value={videoDuration} onChange={setVideoDuration} style={{ width: "100%" }}>{(()=>{- const selected:any=(filteredVideoModels as any[]).find((m:any)=>m.name===videoModel)||{};-- // If kling model, get duration options from pricing duration field- if (selected?.channel === 'kling' && selected?.pricing) {- const durations = [...new Set(selected.pricing.map((p: any) => p.duration))] as number[];- return durations.map((d: number) => (- <Option key={d} value={d}>{d}{t('aiGenerate.seconds')}</Option>- ));- }-- // Other models get from durations field- const durs:number[]=selected?.durations||[];- return durs.map((d)=> (<Option key={d} value={d}>{d}{t('aiGenerate.seconds')}</Option>));- })()}</Select>- </div>- <div className={styles.options}>- {(()=>{- const selected:any=(filteredVideoModels as any[]).find((m:any)=>m.name===videoModel)||{};- const supported:string[]=selected?.supportedParameters||[];- const modes:string[]=selected?.modes||[];-- // Determine video generation type based on modes- const isImage2Video = modes.includes('image2video');- const isFlf2Video = modes.includes('flf2video');- const isLf2Video = modes.includes('lf2video');- const isMultiImage2Video = modes.includes('multi-image2video');-- return (<>- {videoMode==='image2video' && (- <div className={styles.uploadPanel}>- {/* Single image to video - only needs first frame */}- {isImage2Video && supported.includes('image') && !supported.includes('image_tail') && (- <div className={styles.uploadCard} onClick={handlePickFirstFrame}>- {videoImage ? (- <img src={videoImage || ''} alt={t('aiGenerate.firstFrame')} />- ) : (- <div className={styles.uploadPlaceholder}>- <span className={styles.uploadIcon}>+</span>- <span className={styles.uploadText}>{t('aiGenerate.uploadImage')}</span>- </div>- )}- <input type="file" accept="image/*" ref={firstFrameInputRef} onChange={handleFirstFrameChange} style={{ display:'none' }} />- </div>- )}-- {/* Multi-image video - needs multiple images */}- {isMultiImage2Video && supported.includes('image') && (- <div className={styles.multiImageUpload}>- <div className={styles.uploadCard} onClick={() => firstFrameInputRef.current?.click()}>- <div className={styles.uploadPlaceholder}>- <span className={styles.uploadIcon}>+</span>- <span className={styles.uploadText}>{t('aiGenerate.addImage' as any)}</span>- </div>- <input- type="file"- accept="image/*"- multiple- ref={firstFrameInputRef}- onChange={handleMultiImageChange}- style={{ display:'none' }}- />- </div>-- {videoImages.length > 0 && (- <div className={styles.imageGrid}>- {videoImages.map((img, index) => (- <div key={index} className={styles.imageItem}>- <img src={img} alt={`${t('aiGenerate.image' as any)} ${index + 1}`} />- <button- className={styles.removeBtn}- onClick={() => handleRemoveImage(index)}- title={t('aiGenerate.deleteImage' as any)}+ return (+ <>+ {videoMode === 'image2video' && (+ <div className={styles.uploadPanel}>+ {/* Single image to video - only needs first frame */}+ {isImage2Video && supported.includes('image') && !supported.includes('image_tail') && (+ <div className={styles.uploadCard} onClick={handlePickFirstFrame}>+ {videoImage+ ? (+ <img src={videoImage || ''} alt={t('aiGenerate.firstFrame')} />+ )+ : (+ <div className={styles.uploadPlaceholder}>+ <span className={styles.uploadIcon}>+</span>+ <span className={styles.uploadText}>{t('aiGenerate.uploadImage')}</span>+ </div>+ )}+ <input type="file" accept="image/*" ref={firstFrameInputRef} onChange={handleFirstFrameChange} style={{ display: 'none' }} />+ </div>+ )}++ {/* Multi-image video - needs multiple images */}+ {isMultiImage2Video && supported.includes('image') && (+ <div className={styles.multiImageUpload}>+ <div className={styles.uploadCard} onClick={() => firstFrameInputRef.current?.click()}>+ <div className={styles.uploadPlaceholder}>+ <span className={styles.uploadIcon}>+</span>+ <span className={styles.uploadText}>{t('aiGenerate.addImage' as any)}</span>+ </div>+ <input+ type="file"+ accept="image/*"+ multiple+ ref={firstFrameInputRef}+ onChange={handleMultiImageChange}+ style={{ display: 'none' }}+ />+ </div>++ {videoImages.length > 0 && (+ <div className={styles.imageGrid}>+ {videoImages.map((img, index) => (+ <div key={index} className={styles.imageItem}>+ <img src={img} alt={`${t('aiGenerate.image' as any)} ${index + 1}`} />+ <button+ className={styles.removeBtn}+ onClick={() => handleRemoveImage(index)}+ title={t('aiGenerate.deleteImage' as any)}+ >+ ×+ </button>+ </div>+ ))}+ </div>+ )}++ {videoImages.length > 0 && (+ <button+ className={styles.clearAllBtn}+ onClick={handleClearAllImages}+ style={{ marginTop: 8, fontSize: '12px', color: '#ff4d4f' }}>- ×+ {t('aiGenerate.clearAllImages' as any)}</button>- </div>- ))}- </div>- )}-- {videoImages.length > 0 && (- <button- className={styles.clearAllBtn}- onClick={handleClearAllImages}- style={{ marginTop: 8, fontSize: '12px', color: '#ff4d4f' }}- >- {t('aiGenerate.clearAllImages' as any)}- </button>- )}- </div>- )}-- {/* First and tail frame video - needs first and tail frames */}- {isFlf2Video && supported.includes('image') && supported.includes('image_tail') && (- <>- <div className={styles.uploadCard} onClick={handlePickFirstFrame}>- {videoImage ? (- <img src={videoImage || ''} alt={t('aiGenerate.firstFrame')} />- ) : (- <div className={styles.uploadPlaceholder}>- <span className={styles.uploadIcon}>+</span>- <span className={styles.uploadText}>{t('aiGenerate.firstFrame')}</span>+ )}</div>)}- <input type="file" accept="image/*" ref={firstFrameInputRef} onChange={handleFirstFrameChange} style={{ display:'none' }} />- </div>- <div className={styles.swapIcon}>↔</div>- <div className={styles.uploadCard} onClick={handlePickTailFrame}>- {videoImageTail ? (- <img src={videoImageTail || ''} alt={t('aiGenerate.tailFrame')} />- ) : (- <div className={styles.uploadPlaceholder}>- <span className={styles.uploadIcon}>+</span>- <span className={styles.uploadText}>{t('aiGenerate.tailFrame')}</span>++ {/* First and tail frame video - needs first and tail frames */}+ {isFlf2Video && supported.includes('image') && supported.includes('image_tail') && (+ <>+ <div className={styles.uploadCard} onClick={handlePickFirstFrame}>+ {videoImage+ ? (+ <img src={videoImage || ''} alt={t('aiGenerate.firstFrame')} />+ )+ : (+ <div className={styles.uploadPlaceholder}>+ <span className={styles.uploadIcon}>+</span>+ <span className={styles.uploadText}>{t('aiGenerate.firstFrame')}</span>+ </div>+ )}+ <input type="file" accept="image/*" ref={firstFrameInputRef} onChange={handleFirstFrameChange} style={{ display: 'none' }} />+ </div>+ <div className={styles.swapIcon}>↔</div>+ <div className={styles.uploadCard} onClick={handlePickTailFrame}>+ {videoImageTail+ ? (+ <img src={videoImageTail || ''} alt={t('aiGenerate.tailFrame')} />+ )+ : (+ <div className={styles.uploadPlaceholder}>+ <span className={styles.uploadIcon}>+</span>+ <span className={styles.uploadText}>{t('aiGenerate.tailFrame')}</span>+ </div>+ )}+ <input type="file" accept="image/*" ref={tailFrameInputRef} onChange={handleTailFrameChange} style={{ display: 'none' }} />+ </div>+ </>+ )}++ {/* Tail frame only video - only needs tail frame */}+ {isLf2Video && supported.includes('image_tail') && !supported.includes('image') && (+ <div className={styles.uploadCard} onClick={handlePickTailFrame}>+ {videoImageTail+ ? (+ <img src={videoImageTail || ''} alt={t('aiGenerate.tailFrame')} />+ )+ : (+ <div className={styles.uploadPlaceholder}>+ <span className={styles.uploadIcon}>+</span>+ <span className={styles.uploadText}>{t('aiGenerate.tailFrame')}</span>+ </div>+ )}+ <input type="file" accept="image/*" ref={tailFrameInputRef} onChange={handleTailFrameChange} style={{ display: 'none' }} /></div>)}- <input type="file" accept="image/*" ref={tailFrameInputRef} onChange={handleTailFrameChange} style={{ display:'none' }} /></div>- </>- )}-- {/* Tail frame only video - only needs tail frame */}- {isLf2Video && supported.includes('image_tail') && !supported.includes('image') && (- <div className={styles.uploadCard} onClick={handlePickTailFrame}>- {videoImageTail ? (- <img src={videoImageTail || ''} alt={t('aiGenerate.tailFrame')} />- ) : (- <div className={styles.uploadPlaceholder}>- <span className={styles.uploadIcon}>+</span>- <span className={styles.uploadText}>{t('aiGenerate.tailFrame')}</span>- </div>- )}- <input type="file" accept="image/*" ref={tailFrameInputRef} onChange={handleTailFrameChange} style={{ display:'none' }} />- </div>- )}- </div>- )}- </>);- })()}- </div>- {videoModel && videoDuration && videoSize && (- <div className={styles.creditCostInfo}><span style={{ color:'#1890ff', fontSize:14 }}>💰 {t('aiGenerate.estimatedCreditCost' as any)}: {getVideoModelCreditCost(videoModel, videoDuration, videoSize)} {t('aiGenerate.credits' as any)}</span></div>- )}- <Button type="primary" onClick={handleVideoGeneration} loading={loadingVideo} disabled={!videoPrompt || !videoModel} icon={<VideoCameraOutlined />}>{t('aiGenerate.generate')}</Button>- </div>-- <div className={styles.rightPanel}>- {(videoStatus || videoResult) ? (- <div className={styles.result}>- {videoStatus && (- <div style={{ marginBottom:16 }}>- <div style={{ marginBottom:8 }}>- <strong>{t('aiGenerate.taskStatus')}: </strong>- {videoStatus === 'submitted' && t('aiGenerate.taskSubmitted')}- {videoStatus === 'processing' && t('aiGenerate.taskProcessing')}- {videoStatus === 'completed' && t('aiGenerate.taskCompleted')}- {videoStatus === 'failed' && t('aiGenerate.taskFailed')}- </div>- {videoProgress>0 && videoProgress<100 && (<Progress percent={videoProgress} status="active" />)}+ )}+ </>+ )+ })()}+ </div>+ {videoModel && videoDuration && videoSize && (+ <div className={styles.creditCostInfo}>+ <span style={{ color: '#1890ff', fontSize: 14 }}>+ 💰+ {t('aiGenerate.estimatedCreditCost' as any)}+ :+ {getVideoModelCreditCost(videoModel, videoDuration, videoSize)}+ {' '}+ {t('aiGenerate.credits' as any)}+ </span></div>)}- {/* {videoResult && (+ <Button type="primary" onClick={handleVideoGeneration} loading={loadingVideo} disabled={!videoPrompt || !videoModel} icon={<VideoCameraOutlined />}>{t('aiGenerate.generate')}</Button>+ </div>++ <div className={styles.rightPanel}>+ {(videoStatus || videoResult)+ ? (+ <div className={styles.result}>+ {videoStatus && (+ <div style={{ marginBottom: 16 }}>+ <div style={{ marginBottom: 8 }}>+ <strong>+ {t('aiGenerate.taskStatus')}+ :+ {' '}+ </strong>+ {videoStatus === 'submitted' && t('aiGenerate.taskSubmitted')}+ {videoStatus === 'processing' && t('aiGenerate.taskProcessing')}+ {videoStatus === 'completed' && t('aiGenerate.taskCompleted')}+ {videoStatus === 'failed' && t('aiGenerate.taskFailed')}+ </div>+ {videoProgress > 0 && videoProgress < 100 && (<Progress percent={videoProgress} status="active" />)}+ </div>+ )}+ {/* {videoResult && (<div style={{ display:'flex', flexDirection:'column', gap:10 }}><video src={getOssUrl(videoResult)} controls style={{ maxWidth:'100%', borderRadius:8 }} /><Button type="primary" onClick={()=>handleUploadToMediaGroup('video')} icon={<UploadOutlined />} style={{ padding:'1px' }}>{t('aiGenerate.uploadToMediaGroup')}</Button></div>)} */}+ </div>+ )+ : (+ <div className={styles.result}>+ <video src="https://aitoearn.s3.ap-southeast-1.amazonaws.com/68abbe6af812ccb3e1a53d68/8470f98a0733248851cd84cc0d9fb319aitoearn-demo.mp4" controls style={{ width: '100%', maxWidth: '1200px', borderRadius: 8 }} />+ </div>+ )}</div>- ) : (- <div className={styles.result}>- <video src={`https://aitoearn.s3.ap-southeast-1.amazonaws.com/68abbe6af812ccb3e1a53d68/8470f98a0733248851cd84cc0d9fb319aitoearn-demo.mp4`} controls style={{ width:'100%', maxWidth:'1200px', borderRadius:8 }} />- </div>- )}+ </div></div>- </div>- </div>- )}+ )}{/* Video history section */}- {activeModule === "video" && (+ {activeModule === 'video' && (<div className={styles.historySection}><div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}><h3 style={{ margin: 0, fontSize: '18px', fontWeight: 'bold' }}>{t('aiGenerate.videoGenerationHistory' as any)}</h3>- <Button- onClick={fetchVideoHistory}+ <Button+ onClick={fetchVideoHistory}loading={loadingHistory}size="small"type="primary"@@ -1751,128 +2100,155 @@ export default function AIGeneratePage() {{t('aiGenerate.refresh' as any)}</Button></div>-- {loadingHistory ? (- <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>- {t('aiGenerate.loading' as any)}- </div>- ) : videoHistory.length === 0 ? (- <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>- {t('aiGenerate.noHistoryRecords' as any)}- </div>- ) : (- <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: '16px' }}>- {videoHistory.map((item, index) => (- <div- key={item.task_id || index}- style={{- border: '1px solid #e8e8e8',- borderRadius: 12,- padding: 16,- cursor: 'pointer',- // backgroundColor: item.status === 'SUCCESS' ? '#f6ffed' : item.status === 'FAILED' ? '#fff2f0' : '#fafafa',- transition: 'all 0.2s ease',- boxShadow: '0 2px 4px rgba(0,0,0,0.1)'- }}- onClick={() => handleHistoryItemClick(item)}- onMouseEnter={(e) => {- e.currentTarget.style.transform = 'translateY(-2px)';- e.currentTarget.style.boxShadow = '0 4px 8px rgba(0,0,0,0.15)';- }}- onMouseLeave={(e) => {- e.currentTarget.style.transform = 'translateY(0)';- e.currentTarget.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)';- }}- >- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>- <span style={{ fontWeight: 'bold', fontSize: '16px', color: '#1890ff' }}>- {item.task_id ? `#${item.task_id.slice(-8)}` : `#${index + 1}`}- </span>- <span style={{- fontSize: '12px',- padding: '4px 8px',- borderRadius: '6px',- backgroundColor: item.status === 'SUCCESS' ? '#52c41a' : item.status === 'FAILED' ? '#ff4d4f' : '#1890ff',- color: 'white',- fontWeight: 'bold'- }}>- {getStatusText(item.status)}- </span>- </div>- {item.data?.model && (- <div style={{ fontSize: '13px', color: '#666', marginLeft: 'auto', marginBottom: 8 }}>- <strong>Model:</strong> {item.data.model}- </div>- )}-- <div style={{ fontSize: '13px', color: '#666', marginBottom: 8 }}>- <div style={{ marginBottom: 4 }}>- <strong>{t('aiGenerate.submitTime' as any)}:</strong> {formatTime(item.submit_time)}- </div>- {item.finish_time && (- <div style={{ marginBottom: 4 }}>- <strong>{t('aiGenerate.completeTime' as any)}:</strong> {formatTime(item.finish_time)}- </div>- )}-+ {loadingHistory+ ? (+ <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>+ {t('aiGenerate.loading' as any)}+ </div>+ )+ : videoHistory.length === 0+ ? (+ <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>+ {t('aiGenerate.noHistoryRecords' as any)}</div>---- {item.progress && (- <div style={{ fontSize: '13px', color: '#1890ff', marginBottom: 8 }}>- <strong>{t('aiGenerate.progress' as any)}:</strong> {item.progress}- </div>- )}+ )+ : (+ <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', gap: '16px' }}>+ {videoHistory.map((item, index) => (+ <div+ key={item.task_id || index}+ style={{+ border: '1px solid #e8e8e8',+ borderRadius: 12,+ padding: 16,+ cursor: 'pointer',+ // backgroundColor: item.status === 'SUCCESS' ? '#f6ffed' : item.status === 'FAILED' ? '#fff2f0' : '#fafafa',+ transition: 'all 0.2s ease',+ boxShadow: '0 2px 4px rgba(0,0,0,0.1)',+ }}+ onClick={() => handleHistoryItemClick(item)}+ onMouseEnter={(e) => {+ e.currentTarget.style.transform = 'translateY(-2px)'+ e.currentTarget.style.boxShadow = '0 4px 8px rgba(0,0,0,0.15)'+ }}+ onMouseLeave={(e) => {+ e.currentTarget.style.transform = 'translateY(0)'+ e.currentTarget.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)'+ }}+ >+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>+ <span style={{ fontWeight: 'bold', fontSize: '16px', color: '#1890ff' }}>+ {item.task_id ? `#${item.task_id.slice(-8)}` : `#${index + 1}`}+ </span>+ <span style={{+ fontSize: '12px',+ padding: '4px 8px',+ borderRadius: '6px',+ backgroundColor: item.status === 'SUCCESS' ? '#52c41a' : item.status === 'FAILED' ? '#ff4d4f' : '#1890ff',+ color: 'white',+ fontWeight: 'bold',+ }}+ >+ {getStatusText(item.status)}+ </span>+ </div>+ {item.data?.model && (+ <div style={{ fontSize: '13px', color: '#666', marginLeft: 'auto', marginBottom: 8 }}>+ <strong>Model:</strong>+ {' '}+ {item.data.model}+ </div>+ )}-- {item.fail_reason && item.status === 'FAILED' && (- <div style={{ fontSize: '13px', color: '#ff4d4f', marginBottom: 8 }}>- <strong>{t('aiGenerate.failReason' as any)}:</strong> {item.fail_reason}- </div>- )}-- {item.data?.video_url && item.status === 'SUCCESS' && (- <div style={{ marginTop: 12 }}>- <video- src={getOssUrl(item.data.video_url)}- controls- style={{- width: '100%',- borderRadius: 8,- maxHeight: '200px',- objectFit: 'cover'- }}- />- </div>- )}+ <div style={{ fontSize: '13px', color: '#666', marginBottom: 8 }}>+ <div style={{ marginBottom: 4 }}>+ <strong>+ {t('aiGenerate.submitTime' as any)}+ :+ </strong>+ {' '}+ {formatTime(item.submit_time)}+ </div>+ {item.finish_time && (+ <div style={{ marginBottom: 4 }}>+ <strong>+ {t('aiGenerate.completeTime' as any)}+ :+ </strong>+ {' '}+ {formatTime(item.finish_time)}+ </div>+ )}-- </div>- ))}- </div>- )}+ </div>++ {item.progress && (+ <div style={{ fontSize: '13px', color: '#1890ff', marginBottom: 8 }}>+ <strong>+ {t('aiGenerate.progress' as any)}+ :+ </strong>+ {' '}+ {item.progress}+ </div>+ )}++ {item.fail_reason && item.status === 'FAILED' && (+ <div style={{ fontSize: '13px', color: '#ff4d4f', marginBottom: 8 }}>+ <strong>+ {t('aiGenerate.failReason' as any)}+ :+ </strong>+ {' '}+ {item.fail_reason}+ </div>+ )}++ {item.data?.video_url && item.status === 'SUCCESS' && (+ <div style={{ marginTop: 12 }}>+ <video+ src={getOssUrl(item.data.video_url)}+ controls+ style={{+ width: '100%',+ borderRadius: 8,+ maxHeight: '200px',+ objectFit: 'cover',+ }}+ />+ </div>+ )}++ </div>+ ))}+ </div>+ )}</div>)}- </div>+ </div></div>{/* VIP modal */}- <VipContentModal- open={vipModalOpen}- onClose={() => setVipModalOpen(false)}- />-- <Modal title={t("aiGenerate.selectMediaGroup")} open={uploadModalVisible} onOk={handleUploadConfirm} onCancel={()=>setUploadModalVisible(false)} confirmLoading={uploading}>- <Select placeholder={t("aiGenerate.selectMediaGroupPlaceholder")} value={selectedMediaGroup} onChange={setSelectedMediaGroup} style={{ width: "100%" }} loading={loadingMediaGroups}>- {mediaGroups.map((g:any)=> (<Option key={g._id} value={g._id}>{g.title} - {g.type}</Option>))}+ <VipContentModal+ open={vipModalOpen}+ onClose={() => setVipModalOpen(false)}+ />++ <Modal title={t('aiGenerate.selectMediaGroup')} open={uploadModalVisible} onOk={handleUploadConfirm} onCancel={() => setUploadModalVisible(false)} confirmLoading={uploading}>+ <Select placeholder={t('aiGenerate.selectMediaGroupPlaceholder')} value={selectedMediaGroup} onChange={setSelectedMediaGroup} style={{ width: '100%' }} loading={loadingMediaGroups}>+ {mediaGroups.map((g: any) => (+ <Option key={g._id} value={g._id}>+ {g.title}+ {' '}+ -+ {' '}+ {g.type}+ </Option>+ ))}</Select></Modal></div>- );+ )}---diff --git a/project/web/src/app/[lng]/material/album/[id]/album.module.scss b/project/web/src/app/[lng]/material/album/[id]/album.module.scssindex fd8b3d02..64a15832 100644--- a/project/web/src/app/[lng]/material/album/[id]/album.module.scss+++ b/project/web/src/app/[lng]/material/album/[id]/album.module.scss@@ -50,7 +50,9 @@border-radius: 8px;box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);overflow: hidden;- transition: transform 0.3s, box-shadow 0.3s;+ transition:+ transform 0.3s,+ box-shadow 0.3s;&:hover {transform: translateY(-4px);@@ -64,7 +66,9 @@background: #f5f5f5;cursor: pointer;- img, video, audio {+ img,+ video,+ audio {position: absolute;top: 0;left: 0;@@ -88,7 +92,7 @@opacity: 1;}-.headerActions{+.headerActions {display: flex;flex-direction: row;align-items: center;@@ -224,7 +228,9 @@min-height: 0;overflow: hidden;- img, video, audio {+ img,+ video,+ audio {max-width: 100%;max-height: calc(90vh - 100px);object-fit: contain;@@ -256,7 +262,8 @@color: #333;}- input, textarea {+ input,+ textarea {padding: 8px 12px;border: 1px solid #d9d9d9;border-radius: 4px;@@ -291,4 +298,4 @@&:active {background: var(--theColor7);}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/material/album/[id]/albumDetailCore.tsx b/project/web/src/app/[lng]/material/album/[id]/albumDetailCore.tsxindex 5baea5f4..29ea42cb 100644--- a/project/web/src/app/[lng]/material/album/[id]/albumDetailCore.tsx+++ b/project/web/src/app/[lng]/material/album/[id]/albumDetailCore.tsx@@ -1,67 +1,67 @@-"use client";+'use client'-import { useEffect, useState } from "react";-import { Card, Row, Col, Typography, Button, Upload, message } from "antd";-import { useRouter } from "next/navigation";-import { PlusOutlined, PlayCircleOutlined, PictureOutlined, SoundOutlined } from "@ant-design/icons";-import styles from "./albumDetail.module.scss";+import { PictureOutlined, PlayCircleOutlined, PlusOutlined, SoundOutlined } from '@ant-design/icons'+import { Button, Card, Col, message, Row, Typography, Upload } from 'antd'+import { useRouter } from 'next/navigation'+import { useEffect, useState } from 'react'+import styles from './albumDetail.module.scss'-const { Title } = Typography;+const { Title } = Typographyinterface Material {- id: string;- name: string;- url: string;- type: 'video' | 'img';- createTime: string;+ id: string+ name: string+ url: string+ type: 'video' | 'img'+ createTime: string}interface AlbumDetailCoreProps {- albumId: string;+ albumId: string}-export const AlbumDetailCore = ({ albumId }: AlbumDetailCoreProps) => {- const router = useRouter();- const [materials, setMaterials] = useState<Material[]>([]);+export function AlbumDetailCore({ albumId }: AlbumDetailCoreProps) {+ const router = useRouter()+ const [materials, setMaterials] = useState<Material[]>([])const [albumInfo, setAlbumInfo] = useState({- name: "视频素材",- type: "video" as 'video' | 'img',- count: 0- });+ name: '视频素材',+ type: 'video' as 'video' | 'img',+ count: 0,+ })useEffect(() => {// 这里应该调用API获取素材库信息和素材列表// 暂时使用模拟数据setMaterials([{- id: "1",- name: "示例视频1",- url: "https://example.com/video1.mp4",- type: "video",- createTime: "2024-01-01"+ id: '1',+ name: '示例视频1',+ url: 'https://example.com/video1.mp4',+ type: 'video',+ createTime: '2024-01-01',},// 更多素材...- ]);- }, [albumId]);+ ])+ }, [albumId])const handleUpload = (file: File) => {// 这里应该调用API上传素材- message.success('上传成功');- return false;- };+ message.success('上传成功')+ return false+ }const getTypeIcon = (type: string) => {switch (type) {case 'video':- return <PlayCircleOutlined />;+ return <PlayCircleOutlined />case 'img':- return <PictureOutlined />;+ return <PictureOutlined />case 'audio':- return <SoundOutlined />;+ return <SoundOutlined />default:- return null;+ return null}- };+ }return (<div className={styles.albumDetailContainer}>@@ -84,11 +84,11 @@ export const AlbumDetailCore = ({ albumId }: AlbumDetailCoreProps) => {</div><Row gutter={[24, 24]}>- {materials.map((material) => (+ {materials.map(material => (<Col xs={24} sm={12} md={8} lg={6} key={material.id}><Cardhoverable- cover={+ cover={(<div className={styles.coverWrapper}><img alt={material.name} src={material.url} />{material.type === 'video' && (@@ -97,23 +97,23 @@ export const AlbumDetailCore = ({ albumId }: AlbumDetailCoreProps) => {</div>)}</div>- }+ )}><Card.Metatitle={material.name}- description={+ description={(<div className={styles.materialInfo}><span>{material.createTime}</span><span className={styles.typeIcon}>{getTypeIcon(material.type)}</span></div>- }+ )}/></Card></Col>))}</Row></div>- );-};\ No newline at end of file+ )+}diff --git a/project/web/src/app/[lng]/material/album/[id]/page.tsx b/project/web/src/app/[lng]/material/album/[id]/page.tsxindex 0095d059..22643804 100644--- a/project/web/src/app/[lng]/material/album/[id]/page.tsx+++ b/project/web/src/app/[lng]/material/album/[id]/page.tsx@@ -1,180 +1,190 @@-"use client";+'use client'-import { useEffect, useState } from "react";-import { useParams, useRouter, useSearchParams } from "next/navigation";-import { message, Popconfirm } from "antd";-import styles from "./album.module.scss";-import { createMedia, deleteMedia, getMediaList } from "@/api/media";-import { uploadToOss } from "@/api/oss";-import { getOssUrl } from "@/utils/oss";-import { formatImg, VideoGrabFrame } from "@/components/PublishDialog/PublishDialog.util";+import { message, Popconfirm } from 'antd'+import { useParams, useRouter, useSearchParams } from 'next/navigation'+import { useEffect, useState } from 'react'+import { createMedia, deleteMedia, getMediaList } from '@/api/media'+import { uploadToOss } from '@/api/oss'+import { formatImg, VideoGrabFrame } from '@/components/PublishDialog/PublishDialog.util'+import { getOssUrl } from '@/utils/oss'+import styles from './album.module.scss'interface Media {- _id: string;- name: string;- url: string;- type: 'video' | 'img';- description?: string;- title: string;- desc: string;+ _id: string+ name: string+ url: string+ type: 'video' | 'img'+ description?: string+ title: string+ desc: string}interface MediaGroup {- _id: string;- title: string;- desc: string;- type: 'video' | 'img';+ _id: string+ title: string+ desc: string+ type: 'video' | 'img'}export default function AlbumPage() {- const params = useParams();- const router = useRouter();- const searchParams = useSearchParams();- const albumId = params.id as string;-- const [mediaList, setMediaList] = useState<Media[]>([]);- const [groupInfo, setGroupInfo] = useState<MediaGroup | null>(null);- const [loading, setLoading] = useState(false);- const [currentPage, setCurrentPage] = useState(1);- const pageSize = 12;+ const params = useParams()+ const router = useRouter()+ const searchParams = useSearchParams()+ const albumId = params.id as string- const [previewMedia, setPreviewMedia] = useState<Media | null>(null);+ const [mediaList, setMediaList] = useState<Media[]>([])+ const [groupInfo, setGroupInfo] = useState<MediaGroup | null>(null)+ const [loading, setLoading] = useState(false)+ const [currentPage, setCurrentPage] = useState(1)+ const pageSize = 12++ const [previewMedia, setPreviewMedia] = useState<Media | null>(null)useEffect(() => {// 从 URL 参数获取组信息- const title = searchParams.get('title') || '';- const type = searchParams.get('type') as 'video' | 'img' || 'video';- const desc = searchParams.get('desc') || '';-+ const title = searchParams.get('title') || ''+ const type = searchParams.get('type') as 'video' | 'img' || 'video'+ const desc = searchParams.get('desc') || ''+if (title) {setGroupInfo({_id: albumId,title,type,- desc- });+ desc,+ })}-- fetchMediaList();- }, [currentPage, albumId, searchParams]);++ fetchMediaList()+ }, [currentPage, albumId, searchParams])const fetchMediaList = async () => {try {- setLoading(true);- const response:any = await getMediaList(albumId, currentPage, pageSize);+ setLoading(true)+ const response: any = await getMediaList(albumId, currentPage, pageSize)if (response?.data?.list) {- setMediaList(response.data.list);- } else {- setMediaList([]);+ setMediaList(response.data.list)}- } catch (error) {- message.error('获取媒体资源列表失败');- setMediaList([]);- } finally {- setLoading(false);+ else {+ setMediaList([])+ }+ }+ catch (error) {+ message.error('获取媒体资源列表失败')+ setMediaList([])}- };+ finally {+ setLoading(false)+ }+ }// 根据资源组类型获取允许的文件类型const getAcceptTypes = () => {- if (!groupInfo) return "image/*,video/*,audio/*";-+ if (!groupInfo)+ return 'image/*,video/*,audio/*'+switch (groupInfo.type) {case 'video':- return "video/*";+ return 'video/*'case 'img':- return "image/*";+ return 'image/*'default:- return "image/*,video/*";+ return 'image/*,video/*'}- };+ }// 验证文件类型是否匹配资源组类型const validateFileType = (file: File): boolean => {- if (!groupInfo) return true;-- const fileType = file.type;+ if (!groupInfo)+ return true++ const fileType = file.typeswitch (groupInfo.type) {case 'video':- return fileType.startsWith('video/');+ return fileType.startsWith('video/')case 'img':- return fileType.startsWith('image/');+ return fileType.startsWith('image/')default:- return true;+ return true}- };+ }const handleUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {- const file = event.target.files?.[0];- if (!file) return;+ const file = event.target.files?.[0]+ if (!file)+ return// 验证文件类型if (!validateFileType(file)) {- const typeMap = {- 'video': '视频',- 'img': '图片'- };- message.error(`此资源组只允许上传${typeMap[groupInfo!.type]}文件`);- event.target.value = ''; // 清空文件选择- return;+ const typeMap = {+ video: '视频',+ img: '图片',+ }+ message.error(`此资源组只允许上传${typeMap[groupInfo!.type]}文件`)+ event.target.value = '' // 清空文件选择+ return}try {- const url = await uploadToOss(file);- let thumbUrl: string;+ const url = await uploadToOss(file)+ let thumbUrl: stringif (file.type.startsWith('video/')) {- const res = await VideoGrabFrame(URL.createObjectURL(file), 0);- const blob = res.cover.file;- const fileName = file.name.replace(/\.[^/.]+$/, "") + "_cover.png";+ const res = await VideoGrabFrame(URL.createObjectURL(file), 0)+ const blob = res.cover.file+ const fileName = `${file.name.replace(/\.[^/.]+$/, '')}_cover.png`const coverFile = new File([blob], fileName, {- type: blob.type || "image/png",- });- thumbUrl = await uploadToOss(coverFile);- } else {+ type: blob.type || 'image/png',+ })+ thumbUrl = await uploadToOss(coverFile)+ }+ else {// 对于图片文件,使用原图作为缩略图- thumbUrl = url;+ thumbUrl = url}await createMedia({groupId: albumId,- type: file.type.startsWith('video/') ? 'video' : file.type.startsWith('image/') ? 'img' : 'img', // 音频暂时不支持+ type: file.type.startsWith('video/') ? 'video' : file.type.startsWith('image/') ? 'img' : 'img', // 音频暂时不支持url,title: file.name,desc: '',- thumbUrl- });+ thumbUrl,+ })- message.success('上传成功');- fetchMediaList();- } catch (error) {- message.error('上传失败');+ message.success('上传成功')+ fetchMediaList()}- };+ catch (error) {+ message.error('上传失败')+ }+ }const handleDelete = async (mediaId: string) => {try {- await deleteMedia(mediaId);- message.success('删除成功');- fetchMediaList();- } catch (error) {- message.error('删除失败');+ await deleteMedia(mediaId)+ message.success('删除成功')+ fetchMediaList()+ }+ catch (error) {+ message.error('删除失败')}- };+ }const handleAIGenerate = () => {- router.push(`/material/ai-generate`);- };+ router.push(`/material/ai-generate`)+ }// 获取资源类型显示文本const getTypeText = () => {- if (!groupInfo) return '媒体资源';-+ if (!groupInfo)+ return '媒体资源'+const typeMap = {- 'video': '视频资源',- 'img': '图片资源'- };- return typeMap[groupInfo.type];- };+ video: '视频资源',+ img: '图片资源',+ }+ return typeMap[groupInfo.type]+ }return (<div className={styles.container}>@@ -182,9 +192,9 @@ export default function AlbumPage() {<h2>{groupInfo ? `${groupInfo.title} - ${getTypeText()}` : '媒体资源'}</h2><div className={styles.headerActions}><label className={styles.uploadButton} onClick={handleAIGenerate}>- AI生成素材+ AI生成素材</label>-+<label className={styles.uploadButton}><inputtype="file"@@ -192,58 +202,66 @@ export default function AlbumPage() {onChange={handleUpload}style={{ display: 'none' }}/>- <span>上传{groupInfo ? getTypeText().replace('资源', '') : '资源'}</span>+ <span>+ 上传+ {groupInfo ? getTypeText().replace('资源', '') : '资源'}+ </span></label>-+</div>-</div><div className={styles.mediaGrid}>- {mediaList.length > 0 ? (- mediaList.map((media) => (- <div key={media._id} className={styles.mediaCard}>- <div className={styles.mediaWrapper} onClick={() => setPreviewMedia(media)}>- {media.type === 'video' ? (- <video src={getOssUrl(media.url)} />- ) : media.type === 'img' ? (- <img alt={media.title} src={getOssUrl(media.url)} />- ) : (- <audio src={getOssUrl(media.url)} />- )}- <div className={styles.mediaActions}>- <Popconfirm- title="确定要删除这个媒体资源吗?"- onConfirm={(e) => {- e?.stopPropagation();- handleDelete(media._id);- }}- onCancel={(e) => e?.stopPropagation()}- okText="确定"- cancelText="取消"- >- <button- className={`${styles.actionButton} ${styles.delete}`}- onClick={(e) => e.stopPropagation()}- >- 删除- </button>- </Popconfirm>+ {mediaList.length > 0+ ? (+ mediaList.map(media => (+ <div key={media._id} className={styles.mediaCard}>+ <div className={styles.mediaWrapper} onClick={() => setPreviewMedia(media)}>+ {media.type === 'video'+ ? (+ <video src={getOssUrl(media.url)} />+ )+ : media.type === 'img'+ ? (+ <img alt={media.title} src={getOssUrl(media.url)} />+ )+ : (+ <audio src={getOssUrl(media.url)} />+ )}+ <div className={styles.mediaActions}>+ <Popconfirm+ title="确定要删除这个媒体资源吗?"+ onConfirm={(e) => {+ e?.stopPropagation()+ handleDelete(media._id)+ }}+ onCancel={e => e?.stopPropagation()}+ okText="确定"+ cancelText="取消"+ >+ <button+ className={`${styles.actionButton} ${styles.delete}`}+ onClick={e => e.stopPropagation()}+ >+ 删除+ </button>+ </Popconfirm>+ </div>+ </div>+ <div className={styles.mediaInfo}>+ <h3>{media.title}</h3>+ <p>{media.desc}</p>+ </div></div>+ ))+ )+ : (+ <div className={styles.emptyState}>+ <h3>暂无媒体资源</h3>+ <p>点击上方按钮上传资源</p></div>- <div className={styles.mediaInfo}>- <h3>{media.title}</h3>- <p>{media.desc}</p>- </div>- </div>- ))- ) : (- <div className={styles.emptyState}>- <h3>暂无媒体资源</h3>- <p>点击上方按钮上传资源</p>- </div>- )}+ )}</div>{previewMedia && (@@ -254,17 +272,21 @@ export default function AlbumPage() {<button onClick={() => setPreviewMedia(null)}>×</button></div><div className={styles.previewContent}>- {previewMedia.type === 'video' ? (- <video src={getOssUrl(previewMedia.url)} controls autoPlay />- ) : previewMedia.type === 'img' ? (- <img alt={previewMedia.title} src={getOssUrl(previewMedia.url)} />- ) : (- <audio src={getOssUrl(previewMedia.url)} controls autoPlay />- )}+ {previewMedia.type === 'video'+ ? (+ <video src={getOssUrl(previewMedia.url)} controls autoPlay />+ )+ : previewMedia.type === 'img'+ ? (+ <img alt={previewMedia.title} src={getOssUrl(previewMedia.url)} />+ )+ : (+ <audio src={getOssUrl(previewMedia.url)} controls autoPlay />+ )}</div></div></div>)}</div>- );+ )}diff --git a/project/web/src/app/[lng]/material/materialPageCore.tsx b/project/web/src/app/[lng]/material/materialPageCore.tsxindex 2304407f..ef1044f3 100644--- a/project/web/src/app/[lng]/material/materialPageCore.tsx+++ b/project/web/src/app/[lng]/material/materialPageCore.tsx@@ -1,52 +1,52 @@-"use client";+'use client'-import { useState, useEffect, useRef } from "react";-import { useRouter } from "next/navigation";-import { Input, Modal, Popconfirm, Select, message } from "antd";-import { useTransClient } from "@/app/i18n/client";-import {- PlusOutlined,- VideoCameraOutlined,- PictureOutlined,- FolderOutlined,- EditOutlined,+import {DeleteOutlined,- RobotOutlined-} from "@ant-design/icons";-import styles from "./styles/material.module.scss";-import { createMediaGroup, getMediaGroupList, deleteMediaGroup, updateMediaGroupInfo } from "@/api/media";-import { getOssUrl } from "@/utils/oss";+ EditOutlined,+ FolderOutlined,+ PictureOutlined,+ PlusOutlined,+ RobotOutlined,+ VideoCameraOutlined,+} from '@ant-design/icons'+import { Input, message, Modal, Popconfirm, Select } from 'antd'+import { useRouter } from 'next/navigation'+import { useEffect, useRef, useState } from 'react'+import { createMediaGroup, deleteMediaGroup, getMediaGroupList, updateMediaGroupInfo } from '@/api/media'+import { useTransClient } from '@/app/i18n/client'+import { getOssUrl } from '@/utils/oss'+import styles from './styles/material.module.scss'-const { Option } = Select;-const { TextArea } = Input;+const { Option } = Select+const { TextArea } = Inputinterface MediaGroup {- _id: string;- title: string;- desc: string;- cover: string;- count: number;- type: 'video' | 'img';+ _id: string+ title: string+ desc: string+ cover: string+ count: number+ type: 'video' | 'img'mediaList?: {list: Array<{- _id: string;- url: string;- type: 'video' | 'img';- }>;- total: number;- };+ _id: string+ url: string+ type: 'video' | 'img'+ }>+ total: number+ }previewMedia?: {- type: 'video' | 'img';- url: string;- } | null;+ type: 'video' | 'img'+ url: string+ } | null}// 视频预览组件 - 由于 CORS 问题,直接显示预览框-const VideoThumbnail = ({ videoUrl, className, onLoad }: {- videoUrl: string;- className?: string;- onLoad?: (thumbnail: string) => void;-}) => {+function VideoThumbnail({ videoUrl, className, onLoad }: {+ videoUrl: string+ className?: string+ onLoad?: (thumbnail: string) => void+}) {// 直接显示视频预览框,不尝试加载视频(避免 CORS 问题)return (<div className={`${className} ${styles.videoPreview}`}>@@ -55,51 +55,51 @@ const VideoThumbnail = ({ videoUrl, className, onLoad }: {<div className={styles.videoPreviewText}>视频预览</div><div className={styles.videoPreviewPlayButton}><svg width="24" height="24" viewBox="0 0 24 24" fill="none">- <path d="M8 5v14l11-7z" fill="currentColor"/>+ <path d="M8 5v14l11-7z" fill="currentColor" /></svg></div></div></div>- );-};+ )+}-export const MaterialPageCore = () => {- const router = useRouter();- const { t } = useTransClient("material");- const [groups, setGroups] = useState<MediaGroup[]>([]);- const [loading, setLoading] = useState(false);- const [currentPage, setCurrentPage] = useState(1);- const [total, setTotal] = useState(0);- const pageSize = 12;+export function MaterialPageCore() {+ const router = useRouter()+ const { t } = useTransClient('material')+ const [groups, setGroups] = useState<MediaGroup[]>([])+ const [loading, setLoading] = useState(false)+ const [currentPage, setCurrentPage] = useState(1)+ const [total, setTotal] = useState(0)+ const pageSize = 12- const [isModalVisible, setIsModalVisible] = useState(false);- const [isEditModalVisible, setIsEditModalVisible] = useState(false);- const [newGroupTitle, setNewGroupTitle] = useState("");- const [newGroupDesc, setNewGroupDesc] = useState("");- const [newGroupType, setNewGroupType] = useState<'video' | 'img'>('video');- const [editingGroup, setEditingGroup] = useState<MediaGroup | null>(null);+ const [isModalVisible, setIsModalVisible] = useState(false)+ const [isEditModalVisible, setIsEditModalVisible] = useState(false)+ const [newGroupTitle, setNewGroupTitle] = useState('')+ const [newGroupDesc, setNewGroupDesc] = useState('')+ const [newGroupType, setNewGroupType] = useState<'video' | 'img'>('video')+ const [editingGroup, setEditingGroup] = useState<MediaGroup | null>(null)useEffect(() => {- fetchGroups();- }, [currentPage]);+ fetchGroups()+ }, [currentPage])const fetchGroups = async () => {try {- setLoading(true);- const response:any = await getMediaGroupList(currentPage, pageSize);+ setLoading(true)+ const response: any = await getMediaGroupList(currentPage, pageSize)if (response?.data) {// 处理每个组的封面和资源数量const processedGroups = response.data.list.map((group: MediaGroup) => {- const mediaList = group.mediaList;-+ const mediaList = group.mediaList+// 查找第一个视频或图片作为预览- let previewMedia = null;+ let previewMedia = nullif (mediaList && mediaList.list.length > 0) {// 优先查找视频,如果没有视频则使用图片- previewMedia = mediaList.list.find(media => media.type === 'video') || mediaList.list[0];- console.log('Found preview media for group:', group.title, previewMedia);+ previewMedia = mediaList.list.find(media => media.type === 'video') || mediaList.list[0]+ console.log('Found preview media for group:', group.title, previewMedia)}-+const processedGroup = {...group,// 使用找到的预览媒体作为封面@@ -107,102 +107,111 @@ export const MaterialPageCore = () => {// 使用 mediaList 的 total 作为资源数量count: mediaList ? mediaList.total : group.count,// 保存预览媒体的类型和URL信息- previewMedia: previewMedia ? {- type: previewMedia.type,- url: previewMedia.url- } : null- };-- return processedGroup;- });- setGroups(processedGroups);- setTotal(response.data.total);+ previewMedia: previewMedia+ ? {+ type: previewMedia.type,+ url: previewMedia.url,+ }+ : null,+ }++ return processedGroup+ })+ setGroups(processedGroups)+ setTotal(response.data.total)}- } catch (error) {- message.error(t('mediaManagement.getListFailed'));- } finally {- setLoading(false);}- };+ catch (error) {+ message.error(t('mediaManagement.getListFailed'))+ }+ finally {+ setLoading(false)+ }+ }const handleGroupClick = (group: MediaGroup) => {// 通过 URL 参数传递组信息const params = new URLSearchParams({title: group.title,type: group.type,- desc: group.desc- });- router.push(`/material/album/${group._id}?${params.toString()}`);- };+ desc: group.desc,+ })+ router.push(`/material/album/${group._id}?${params.toString()}`)+ }const handleCreateGroup = async () => {- if (!newGroupTitle) return;-+ if (!newGroupTitle)+ return+try {- await createMediaGroup({+ await createMediaGroup({title: newGroupTitle,desc: newGroupDesc,- type: newGroupType- });- message.success(t('mediaManagement.createSuccess'));- fetchGroups();- setIsModalVisible(false);- setNewGroupTitle("");- setNewGroupDesc("");- } catch (error) {- message.error(t('mediaManagement.createFailed'));+ type: newGroupType,+ })+ message.success(t('mediaManagement.createSuccess'))+ fetchGroups()+ setIsModalVisible(false)+ setNewGroupTitle('')+ setNewGroupDesc('')+ }+ catch (error) {+ message.error(t('mediaManagement.createFailed'))}- };+ }const handleDeleteGroup = async (groupId: string) => {try {- await deleteMediaGroup(groupId);- message.success(t('mediaManagement.deleteSuccess'));- fetchGroups();- } catch (error) {- message.error(t('mediaManagement.deleteFailed'));+ await deleteMediaGroup(groupId)+ message.success(t('mediaManagement.deleteSuccess'))+ fetchGroups()+ }+ catch (error) {+ message.error(t('mediaManagement.deleteFailed'))}- };+ }const handleUpdateGroup = async () => {- if (!editingGroup || !newGroupTitle) return;-+ if (!editingGroup || !newGroupTitle)+ return+try {- await updateMediaGroupInfo(editingGroup._id, {+ await updateMediaGroupInfo(editingGroup._id, {title: newGroupTitle,desc: newGroupDesc,- type: newGroupType- });- message.success(t('mediaManagement.updateSuccess'));- fetchGroups();- setIsEditModalVisible(false);- setEditingGroup(null);- setNewGroupTitle("");- setNewGroupDesc("");- } catch (error) {- message.error(t('mediaManagement.updateFailed'));+ type: newGroupType,+ })+ message.success(t('mediaManagement.updateSuccess'))+ fetchGroups()+ setIsEditModalVisible(false)+ setEditingGroup(null)+ setNewGroupTitle('')+ setNewGroupDesc('')+ }+ catch (error) {+ message.error(t('mediaManagement.updateFailed'))}- };+ }const showEditModal = (group: MediaGroup) => {- setEditingGroup(group);- setNewGroupTitle(group.title);- setNewGroupDesc(group.desc);- setNewGroupType(group.type);- setIsEditModalVisible(true);- };+ setEditingGroup(group)+ setNewGroupTitle(group.title)+ setNewGroupDesc(group.desc)+ setNewGroupType(group.type)+ setIsEditModalVisible(true)+ }// 获取封面图片或图标const getCoverDisplay = (group: MediaGroup) => {// 如果有预览媒体,优先显示预览媒体if (group.previewMedia) {- console.log('Using preview media:', group.previewMedia);+ console.log('Using preview media:', group.previewMedia)if (group.previewMedia.type === 'video') {- const videoUrl = getOssUrl(group.previewMedia.url);- console.log('Video URL:', videoUrl);+ const videoUrl = getOssUrl(group.previewMedia.url)+ console.log('Video URL:', videoUrl)return (<div className={styles.coverContent}>- <VideoThumbnail+ <VideoThumbnailvideoUrl={videoUrl}className={styles.coverImage}/>@@ -210,34 +219,35 @@ export const MaterialPageCore = () => {<VideoCameraOutlined /></div></div>- );- } else {+ )+ }+ else {return (<div className={styles.coverContent}>- <img- alt={group.title}- src={getOssUrl(group.previewMedia.url)}+ <img+ alt={group.title}+ src={getOssUrl(group.previewMedia.url)}className={styles.coverImage}/><div className={styles.imageTypeIcon}><PictureOutlined /></div></div>- );+ )}}// 如果没有预览媒体但有 mediaList,尝试使用第一个媒体if (group.mediaList?.list && group.mediaList.list.length > 0) {- const firstMedia = group.mediaList.list[0];- console.log('Using first media from mediaList:', firstMedia);-+ const firstMedia = group.mediaList.list[0]+ console.log('Using first media from mediaList:', firstMedia)+if (firstMedia.type === 'video') {- const videoUrl = getOssUrl(firstMedia.url);- console.log('Video URL from mediaList:', videoUrl);+ const videoUrl = getOssUrl(firstMedia.url)+ console.log('Video URL from mediaList:', videoUrl)return (<div className={styles.coverContent}>- <VideoThumbnail+ <VideoThumbnailvideoUrl={videoUrl}className={styles.coverImage}/>@@ -245,54 +255,57 @@ export const MaterialPageCore = () => {<VideoCameraOutlined /></div></div>- );- } else {+ )+ }+ else {return (<div className={styles.coverContent}>- <img- alt={group.title}- src={getOssUrl(firstMedia.url)}+ <img+ alt={group.title}+ src={getOssUrl(firstMedia.url)}className={styles.coverImage}/><div className={styles.imageTypeIcon}><PictureOutlined /></div></div>- );+ )}}-+// 如果有封面图片,显示图片if (group.cover && group.cover !== '') {return (<div className={styles.coverContent}>- {group.type === 'video' ? (- <div className={styles.videoTypeIcon}>- <VideoCameraOutlined />- <VideoThumbnail- videoUrl={group.cover}- className={styles.coverImage}- />- </div>- ) : (- <img- alt={group.title}- src={group.cover}- className={styles.coverImage}- />- )}+ {group.type === 'video'+ ? (+ <div className={styles.videoTypeIcon}>+ <VideoCameraOutlined />+ <VideoThumbnail+ videoUrl={group.cover}+ className={styles.coverImage}+ />+ </div>+ )+ : (+ <img+ alt={group.title}+ src={group.cover}+ className={styles.coverImage}+ />+ )}</div>- );+ )}-+// 如果mediaList存在且有内容,显示第一个媒体if (group.mediaList?.list && group.mediaList.list.length > 0) {- const firstMedia = group.mediaList.list[0];-+ const firstMedia = group.mediaList.list[0]+if (firstMedia.type === 'video') {return (<div className={styles.coverContent}>- <VideoThumbnail+ <VideoThumbnailvideoUrl={getOssUrl(firstMedia.url)}className={styles.coverImage}/>@@ -300,48 +313,51 @@ export const MaterialPageCore = () => {<VideoCameraOutlined /></div></div>- );- } else {+ )+ }+ else {return (<div className={styles.coverContent}>- <img- alt={group.title}- src={getOssUrl(firstMedia.url)}+ <img+ alt={group.title}+ src={getOssUrl(firstMedia.url)}className={styles.coverImage}/><div className={styles.imageTypeIcon}><PictureOutlined /></div></div>- );+ )}}-+// 否则显示类型图标return (<div className={styles.iconCover}>- {group.type === 'video' ? (- <VideoCameraOutlined className={styles.typeIcon} />- ) : (- <PictureOutlined className={styles.typeIcon} />- )}+ {group.type === 'video'+ ? (+ <VideoCameraOutlined className={styles.typeIcon} />+ )+ : (+ <PictureOutlined className={styles.typeIcon} />+ )}</div>- );- };+ )+ }return (<div className={styles.materialContainer}><div className={styles.header}><h3>{t('mediaManagement.title')}</h3><div className={styles.headerActions}>- <button+ <buttonclassName={styles.aiGenerateButton}onClick={() => router.push('/material/ai-generate?tab=videoGeneration')}><RobotOutlined /><span>{t('mediaManagement.aiVideoGenerate')}</span></button>- <button+ <buttonclassName={styles.createButton}onClick={() => setIsModalVisible(true)}>@@ -351,84 +367,89 @@ export const MaterialPageCore = () => {</div></div>- {groups.length > 0 ? (- <div className={styles.mediaGrid}>- {groups.map((group) => (- <div key={group._id} className={styles.mediaCard} onClick={() => handleGroupClick(group)}>- <div className={styles.coverWrapper}>- {getCoverDisplay(group)}- <div className={styles.cardActions}>- <button- className={styles.actionButton}- onClick={(e) => {- e.stopPropagation();- showEditModal(group);- }}- >- <EditOutlined />- </button>- <Popconfirm- title={t('mediaManagement.deleteConfirm')}- onConfirm={(e) => {- e?.stopPropagation();- handleDeleteGroup(group._id);- }}- onCancel={(e) => e?.stopPropagation()}- okText={t('mediaManagement.delete')}- cancelText={t('mediaManagement.cancel')}- >- <button- className={`${styles.actionButton} ${styles.delete}`}- onClick={(e) => e.stopPropagation()}- >- <DeleteOutlined />- </button>- </Popconfirm>- </div>- <div className={styles.resourceBadge}>- <span className={styles.badgeText}>- {group.count}{t('mediaManagement.resources')}- </span>- </div>- </div>- <div className={styles.cardContent}>- <h3 className={styles.cardTitle}>{group.title}</h3>- <div className={styles.albumInfo}>- <p className={styles.description}>{group.desc || t('mediaManagement.noDescription')}</p>- <div className={styles.typeTag}>- {group.type === 'video' ? (- <>- <VideoCameraOutlined />- <span>{t('mediaManagement.video')}</span>- </>- ) : (- <>- <PictureOutlined />- <span>{t('mediaManagement.image')}</span>- </>- )}+ {groups.length > 0+ ? (+ <div className={styles.mediaGrid}>+ {groups.map(group => (+ <div key={group._id} className={styles.mediaCard} onClick={() => handleGroupClick(group)}>+ <div className={styles.coverWrapper}>+ {getCoverDisplay(group)}+ <div className={styles.cardActions}>+ <button+ className={styles.actionButton}+ onClick={(e) => {+ e.stopPropagation()+ showEditModal(group)+ }}+ >+ <EditOutlined />+ </button>+ <Popconfirm+ title={t('mediaManagement.deleteConfirm')}+ onConfirm={(e) => {+ e?.stopPropagation()+ handleDeleteGroup(group._id)+ }}+ onCancel={e => e?.stopPropagation()}+ okText={t('mediaManagement.delete')}+ cancelText={t('mediaManagement.cancel')}+ >+ <button+ className={`${styles.actionButton} ${styles.delete}`}+ onClick={e => e.stopPropagation()}+ >+ <DeleteOutlined />+ </button>+ </Popconfirm>+ </div>+ <div className={styles.resourceBadge}>+ <span className={styles.badgeText}>+ {group.count}+ {t('mediaManagement.resources')}+ </span>+ </div>+ </div>+ <div className={styles.cardContent}>+ <h3 className={styles.cardTitle}>{group.title}</h3>+ <div className={styles.albumInfo}>+ <p className={styles.description}>{group.desc || t('mediaManagement.noDescription')}</p>+ <div className={styles.typeTag}>+ {group.type === 'video'+ ? (+ <>+ <VideoCameraOutlined />+ <span>{t('mediaManagement.video')}</span>+ </>+ )+ : (+ <>+ <PictureOutlined />+ <span>{t('mediaManagement.image')}</span>+ </>+ )}+ </div>+ </div></div></div>+ ))}+ </div>+ )+ : (+ <div className={styles.emptyContainer}>+ <div className={styles.emptyIcon}>+ <FolderOutlined /></div>+ <h3>{t('mediaManagement.noGroups')}</h3>+ <p>{t('mediaManagement.noGroupsDesc')}</p>+ <button+ className={styles.emptyCreateButton}+ onClick={() => setIsModalVisible(true)}+ >+ <PlusOutlined />+ {t('mediaManagement.createNow')}+ </button></div>- ))}- </div>- ) : (- <div className={styles.emptyContainer}>- <div className={styles.emptyIcon}>- <FolderOutlined />- </div>- <h3>{t('mediaManagement.noGroups')}</h3>- <p>{t('mediaManagement.noGroupsDesc')}</p>- <button- className={styles.emptyCreateButton}- onClick={() => setIsModalVisible(true)}- >- <PlusOutlined />- {t('mediaManagement.createNow')}- </button>- </div>- )}+ )}{/* Modal components */}<Modal@@ -436,10 +457,10 @@ export const MaterialPageCore = () => {open={isModalVisible}onOk={handleCreateGroup}onCancel={() => {- setIsModalVisible(false);- setNewGroupTitle("");- setNewGroupDesc("");- setNewGroupType('video');+ setIsModalVisible(false)+ setNewGroupTitle('')+ setNewGroupDesc('')+ setNewGroupType('video')}}okText={t('mediaManagement.create')}cancelText={t('mediaManagement.cancel')}@@ -450,7 +471,7 @@ export const MaterialPageCore = () => {<label>{t('mediaManagement.groupName')}</label><Inputvalue={newGroupTitle}- onChange={(e) => setNewGroupTitle(e.target.value)}+ onChange={e => setNewGroupTitle(e.target.value)}placeholder={t('mediaManagement.groupNamePlaceholder')}/></div>@@ -458,7 +479,7 @@ export const MaterialPageCore = () => {<label>{t('mediaManagement.description')}</label><Input.TextAreavalue={newGroupDesc}- onChange={(e) => setNewGroupDesc(e.target.value)}+ onChange={e => setNewGroupDesc(e.target.value)}placeholder={t('mediaManagement.descriptionPlaceholder')}rows={3}/>@@ -467,7 +488,7 @@ export const MaterialPageCore = () => {<label>{t('mediaManagement.type')}</label><Selectvalue={newGroupType}- onChange={(value) => setNewGroupType(value)}+ onChange={value => setNewGroupType(value)}style={{ width: '100%' }}><Select.Option value="video">{t('mediaManagement.video')}</Select.Option>@@ -482,8 +503,8 @@ export const MaterialPageCore = () => {open={isEditModalVisible}onOk={handleUpdateGroup}onCancel={() => {- setIsEditModalVisible(false);- setEditingGroup(null);+ setIsEditModalVisible(false)+ setEditingGroup(null)}}okText={t('mediaManagement.save')}cancelText={t('mediaManagement.cancel')}@@ -495,9 +516,9 @@ export const MaterialPageCore = () => {<label>{t('mediaManagement.groupName')}</label><Inputvalue={editingGroup.title}- onChange={(e) => setEditingGroup({+ onChange={e => setEditingGroup({...editingGroup,- title: e.target.value+ title: e.target.value,})}placeholder={t('mediaManagement.groupNamePlaceholder')}/>@@ -506,9 +527,9 @@ export const MaterialPageCore = () => {<label>{t('mediaManagement.description')}</label><Input.TextAreavalue={editingGroup.desc}- onChange={(e) => setEditingGroup({+ onChange={e => setEditingGroup({...editingGroup,- desc: e.target.value+ desc: e.target.value,})}placeholder={t('mediaManagement.descriptionPlaceholder')}rows={3}@@ -518,9 +539,9 @@ export const MaterialPageCore = () => {<label>{t('mediaManagement.type')}</label><Selectvalue={editingGroup.type}- onChange={(value) => setEditingGroup({+ onChange={value => setEditingGroup({...editingGroup,- type: value+ type: value,})}style={{ width: '100%' }}>@@ -532,5 +553,5 @@ export const MaterialPageCore = () => {)}</Modal></div>- );-};\ No newline at end of file+ )+}diff --git a/project/web/src/app/[lng]/material/page.tsx b/project/web/src/app/[lng]/material/page.tsxindex 87fcf593..ea9bf7fa 100644--- a/project/web/src/app/[lng]/material/page.tsx+++ b/project/web/src/app/[lng]/material/page.tsx@@ -1,27 +1,27 @@-import { useTranslation } from "@/app/i18n";-import { PageParams } from "@/app/globals";-import * as React from "react";-import { getMetadata } from "@/utils/general";-import { MaterialPageCore } from "@/app/[lng]/material/materialPageCore";+import type { PageParams } from '@/app/globals'+import * as React from 'react'+import { MaterialPageCore } from '@/app/[lng]/material/materialPageCore'+import { useTranslation } from '@/app/i18n'+import { getMetadata } from '@/utils/general'export async function generateMetadata({ params }: PageParams) {- const { lng } = await params;- const { t } = await useTranslation(lng, "material");+ const { lng } = await params+ const { t } = await useTranslation(lng, 'material')return await getMetadata({- title: "素材库",+ title: '素材库',},lng,- );+ )}export default async function Page({ params }: PageParams) {- const { lng } = await params;- const { t } = await useTranslation(lng, "material");+ const { lng } = await params+ const { t } = await useTranslation(lng, 'material')return (<><MaterialPageCore /></>- );+ )}diff --git a/project/web/src/app/[lng]/material/styles/material.module.scss b/project/web/src/app/[lng]/material/styles/material.module.scssindex e4c21b77..6596de9d 100644--- a/project/web/src/app/[lng]/material/styles/material.module.scss+++ b/project/web/src/app/[lng]/material/styles/material.module.scss@@ -1,7 +1,7 @@.materialContainer {padding: 32px;min-height: 100vh;-+font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;}@@ -302,7 +302,7 @@color: white;backdrop-filter: blur(10px);transition: all 0.3s ease;-+&:hover {background: rgba(255, 255, 255, 0.3);transform: scale(1.1);@@ -463,10 +463,10 @@font-size: 100px;color: #bdc3c7;margin-bottom: 32px;-+:global(.anticon) {transition: all 0.3s ease;-+&:hover {color: #667eea;transform: scale(1.1);@@ -599,7 +599,9 @@}}- input, textarea, select {+ input,+ textarea,+ select {padding: 14px 18px;border: 2px solid #e9ecef;border-radius: 12px;@@ -641,18 +643,18 @@:global {.ant-modal-footer {padding: 24px 32px 32px;-+.ant-btn {height: 44px;padding: 0 24px;font-size: 16px;font-weight: 600;border-radius: 8px;-+&.ant-btn-primary {background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);border: none;-+&:hover {background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);transform: translateY(-1px);@@ -670,11 +672,11 @@font-size: 14px;font-weight: 500;border-radius: 6px;-+&.ant-btn-primary {background: #ff4757;border-color: #ff4757;-+&:hover {background: #ff3742;border-color: #ff3742;@@ -699,7 +701,8 @@}@keyframes pulse {- 0%, 100% {+ 0%,+ 100% {transform: scale(1);}50% {@@ -720,55 +723,55 @@.materialContainer {padding: 20px 16px;}-+.header {flex-direction: column;gap: 20px;text-align: center;-+h2 {font-size: 32px;}}-+.createButton {width: 100%;justify-content: center;font-size: 16px;padding: 14px 28px;}-+.cardContent {padding: 24px;}-+.cardTitle {font-size: 20px;}-+.description {font-size: 15px;}-+.typeTag {font-size: 15px;}-+.emptyContainer {padding: 60px 24px;margin: 20px;-+h3 {font-size: 24px;}-+p {font-size: 16px;}}-+.emptyCreateButton {font-size: 16px;padding: 16px 32px;}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/not-found.tsx b/project/web/src/app/[lng]/not-found.tsxindex da7ba1eb..64a0b4a6 100644--- a/project/web/src/app/[lng]/not-found.tsx+++ b/project/web/src/app/[lng]/not-found.tsx@@ -1,46 +1,46 @@-"use client";+'use client'-import Link from "next/link";-import { useGetClientLng } from "@/hooks/useSystem";+import Link from 'next/link'+import { useGetClientLng } from '@/hooks/useSystem'export default function NotFound() {- const lng = useGetClientLng();+ const lng = useGetClientLng()return (<divstyle={{- display: "flex",- justifyContent: "center",- alignItems: "center",- flexDirection: "column",- minHeight: "100vh",- background: "var(--background-color)",- color: "var(--text-color)",+ display: 'flex',+ justifyContent: 'center',+ alignItems: 'center',+ flexDirection: 'column',+ minHeight: '100vh',+ background: 'var(--background-color)',+ color: 'var(--text-color)',}}>- <span style={{ fontSize: "60px", color: "var(--theColor5)" }}>404</span>- <Link- href={`/${lng}`}- style={{- marginTop: "20px",- color: "var(--theColor5)",- textDecoration: "none",- padding: "8px 16px",- border: "1px solid var(--theColor5)",- borderRadius: "8px",- transition: "all 0.3s"+ <span style={{ fontSize: '60px', color: 'var(--theColor5)' }}>404</span>+ <Link+ href={`/${lng}`}+ style={{+ marginTop: '20px',+ color: 'var(--theColor5)',+ textDecoration: 'none',+ padding: '8px 16px',+ border: '1px solid var(--theColor5)',+ borderRadius: '8px',+ transition: 'all 0.3s',}}onMouseOver={(e) => {- e.currentTarget.style.background = "var(--theColor5)";- e.currentTarget.style.color = "white";+ e.currentTarget.style.background = 'var(--theColor5)'+ e.currentTarget.style.color = 'white'}}onMouseOut={(e) => {- e.currentTarget.style.background = "transparent";- e.currentTarget.style.color = "var(--theColor5)";+ e.currentTarget.style.background = 'transparent'+ e.currentTarget.style.color = 'var(--theColor5)'}}>返回首页</Link></div>- );+ )}diff --git a/project/web/src/app/[lng]/page.tsx b/project/web/src/app/[lng]/page.tsxindex 9e59877a..d0bf8a50 100644--- a/project/web/src/app/[lng]/page.tsx+++ b/project/web/src/app/[lng]/page.tsx@@ -1,28 +1,35 @@-"use client";+'use client'-import { useEffect, useRef, useState } from "react";-import styles from "./styles/difyHome.module.scss";-import { useTransClient } from "../i18n/client";-import { getMainAppDownloadUrlSync } from "../config/appDownloadConfig";+import { AndroidOutlined } from '@ant-design/icons'+import Image from 'next/image'+import { useParams, useRouter } from 'next/navigation'+import { useEffect, useRef, useState } from 'react'+// Mobile app download section+import { QRCode } from 'react-qrcode-logo'// Import SVG icons-import gongzhonghao from '@/assets/images/gongzhonghao.jpg';-import bilibiliIcon from '@/assets/svgs/plat/bilibili.svg';-import douyinIcon from '@/assets/svgs/plat/douyin.svg';-import tiktokIcon from '@/assets/svgs/plat/tiktok.svg';-import ksIcon from '@/assets/svgs/plat/ks.svg';-import wxSphIcon from '@/assets/svgs/plat/wx-sph.svg';-import gongzhonghaoIcon from '@/assets/svgs/plat/gongzhonghao.png';-import xhsIcon from '@/assets/svgs/plat/xhs.svg';-import youtubeIcon from '@/assets/svgs/plat/youtube.png';-import TwitterIcon from '@/assets/svgs/plat/twitter.png';-import FacebookIcon from '@/assets/svgs/plat/facebook.png';-import InstagramIcon from '@/assets/svgs/plat/instagram.png';-import LinkedInIcon from '@/assets/svgs/plat/linkedin.png';-import PinterestIcon from '@/assets/svgs/plat/pinterest.png';-import ThreadsIcon from '@/assets/svgs/plat/threads.png';-import publish1 from '@/assets/images/publish1.png';-+import gongzhonghao from '@/assets/images/gongzhonghao.jpg'+import publish1 from '@/assets/images/publish1.png'+import bilibiliIcon from '@/assets/svgs/plat/bilibili.svg'+import douyinIcon from '@/assets/svgs/plat/douyin.svg'+import FacebookIcon from '@/assets/svgs/plat/facebook.png'+import gongzhonghaoIcon from '@/assets/svgs/plat/gongzhonghao.png'+import InstagramIcon from '@/assets/svgs/plat/instagram.png'+import ksIcon from '@/assets/svgs/plat/ks.svg'+import LinkedInIcon from '@/assets/svgs/plat/linkedin.png'+import PinterestIcon from '@/assets/svgs/plat/pinterest.png'+import ThreadsIcon from '@/assets/svgs/plat/threads.png'+import tiktokIcon from '@/assets/svgs/plat/tiktok.svg'+import TwitterIcon from '@/assets/svgs/plat/twitter.png'+import wxSphIcon from '@/assets/svgs/plat/wx-sph.svg'+import xhsIcon from '@/assets/svgs/plat/xhs.svg'++import youtubeIcon from '@/assets/svgs/plat/youtube.png'+import { getMainAppDownloadUrlSync } from '../config/appDownloadConfig'++import { useTransClient } from '../i18n/client'++import styles from './styles/difyHome.module.scss'// External image URL constantsconst IMAGE_URLS = {@@ -38,23 +45,20 @@ const IMAGE_URLS = {contentSearch4: 'https://aitoearn.s3.ap-southeast-1.amazonaws.com/common/web/app-screenshot/3.%20content%20search/contentsearch4.jpeg',commentFilter: 'https://aitoearn.s3.ap-southeast-1.amazonaws.com/common/web/app-screenshot/4.%20comments%20search/commentfilter.jpeg',commentFilter2: 'https://aitoearn.s3.ap-southeast-1.amazonaws.com/common/web/app-screenshot/5.%20content%20engagement/commentfilter2.jpeg',-};---import Image from "next/image";-import { useRouter } from "next/navigation";-import { useParams } from "next/navigation";-import { AndroidOutlined } from '@ant-design/icons';+}// Release bannerfunction ReleaseBanner() {- const { t } = useTransClient('home');+ const { t } = useTransClient('home')return (<div className={styles.releaseBanner}>- <div className={styles.bannerContent} onClick={() => {- window.location.href = '/accounts?showVip=true';- }}>+ <div+ className={styles.bannerContent}+ onClick={() => {+ window.location.href = '/accounts?showVip=true'+ }}+ >{/* <span className={styles.releaseTag}>{t('releaseBanner.tag')}</span> */}<span className={styles.releaseText}>Join Plus — Enjoy Unlimited Free Sora-2, Nano Banana!</span>{/* <svg className={styles.arrowIcon} width="16" height="16" viewBox="0 0 16 16" fill="none">@@ -62,66 +66,69 @@ function ReleaseBanner() {</svg> */}</div></div>- );+ )}-// Hero main title sectionfunction Hero() {- const { t } = useTransClient('home');- const [displayedText, setDisplayedText] = useState('');- const [currentIndex, setCurrentIndex] = useState(0);- const [isTypingComplete, setIsTypingComplete] = useState(false);- const [hideCursor, setHideCursor] = useState(false);- const [startTyping, setStartTyping] = useState(false);- const router = useRouter();+ const { t } = useTransClient('home')+ const [displayedText, setDisplayedText] = useState('')+ const [currentIndex, setCurrentIndex] = useState(0)+ const [isTypingComplete, setIsTypingComplete] = useState(false)+ const [hideCursor, setHideCursor] = useState(false)+ const [startTyping, setStartTyping] = useState(false)+ const router = useRouter()// Full text to display- const fullText = t('hero.title');- const typingSpeed = 120; // Typing speed (milliseconds)- const initialDelay = 800; // Initial delay (milliseconds)- const cursorHideDelay = 2000; // Delay before hiding cursor after typing completes+ const fullText = t('hero.title')+ const typingSpeed = 120 // Typing speed (milliseconds)+ const initialDelay = 800 // Initial delay (milliseconds)+ const cursorHideDelay = 2000 // Delay before hiding cursor after typing completesuseEffect(() => {// Start typing after initial delayconst startTimer = setTimeout(() => {- setStartTyping(true);- }, initialDelay);+ setStartTyping(true)+ }, initialDelay)- return () => clearTimeout(startTimer);- }, []);+ return () => clearTimeout(startTimer)+ }, [])useEffect(() => {if (startTyping && currentIndex < fullText.length) {- const currentChar = fullText[currentIndex];+ const currentChar = fullText[currentIndex]// Adjust typing speed based on character type- let currentSpeed = typingSpeed;+ let currentSpeed = typingSpeedif (currentChar === '\n') {- currentSpeed = typingSpeed * 2; // Pause slightly on line break- } else if (currentChar === ' ') {- currentSpeed = typingSpeed * 0.5; // Space is faster- } else if (/[,。!?;:]/.test(currentChar)) {- currentSpeed = typingSpeed * 1.5; // Pause slightly on punctuation- } else {+ currentSpeed = typingSpeed * 2 // Pause slightly on line break+ }+ else if (currentChar === ' ') {+ currentSpeed = typingSpeed * 0.5 // Space is faster+ }+ else if (/[,。!?;:]/.test(currentChar)) {+ currentSpeed = typingSpeed * 1.5 // Pause slightly on punctuation+ }+ else {// Add some randomness to make typing more natural- currentSpeed = typingSpeed + Math.random() * 50 - 25;+ currentSpeed = typingSpeed + Math.random() * 50 - 25}const timer = setTimeout(() => {- setDisplayedText(prev => prev + fullText[currentIndex]);- setCurrentIndex(prev => prev + 1);- }, currentSpeed);+ setDisplayedText(prev => prev + fullText[currentIndex])+ setCurrentIndex(prev => prev + 1)+ }, currentSpeed)- return () => clearTimeout(timer);- } else if (currentIndex >= fullText.length && !isTypingComplete) {- setIsTypingComplete(true);+ return () => clearTimeout(timer)+ }+ else if (currentIndex >= fullText.length && !isTypingComplete) {+ setIsTypingComplete(true)// Delay hiding cursor after typing completessetTimeout(() => {- setHideCursor(true);- }, cursorHideDelay);+ setHideCursor(true)+ }, cursorHideDelay)}- }, [startTyping, currentIndex, fullText, typingSpeed, isTypingComplete, cursorHideDelay]);+ }, [startTyping, currentIndex, fullText, typingSpeed, isTypingComplete, cursorHideDelay])// Convert text to JSX, handle line breaksconst renderText = () => {@@ -130,30 +137,35 @@ function Hero() {{line}{index < array.length - 1 && <br />}</span>- ));- };+ ))+ }return (<section className={styles.hero}><div className={styles.heroContainer}>- <div className={styles.githubStars} onClick={() => {- window.open('https://github.com/yikart/AiToEarn/releases', '_blank');- }}>- <img src={'https://img.shields.io/github/stars/yikart/AiToEarn.svg'} alt="logo" className={styles.logo} />+ <div+ className={styles.githubStars}+ onClick={() => {+ window.open('https://github.com/yikart/AiToEarn/releases', '_blank')+ }}+ >+ <img src="https://img.shields.io/github/stars/yikart/AiToEarn.svg" alt="logo" className={styles.logo} /><span className={styles.starText}>{t('hero.starsText')}</span><span className={styles.githubText}>{t('hero.github')}</span></div>-<h1 className={styles.heroTitle}>{renderText()}<span className={`${styles.cursor} ${hideCursor ? styles.cursorHidden : styles.cursorVisible}`}>|</span></h1>{/* Mobile button */}- <button onClick={() => {- router.push("/accounts");- }} className={`${styles.heroBtn} ${styles.heroBtnMobile}`}>+ <button+ onClick={() => {+ router.push('/accounts')+ }}+ className={`${styles.heroBtn} ${styles.heroBtnMobile}`}+ >{t('hero.getStarted')}<svg className={styles.btnArrow} width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="m6 12 4-4-4-4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />@@ -165,9 +177,12 @@ function Hero() {</p>{/* Desktop button */}- <button onClick={() => {- router.push("/accounts");- }} className={`${styles.heroBtn} ${styles.heroBtnDesktop}`}>+ <button+ onClick={() => {+ router.push('/accounts')+ }}+ className={`${styles.heroBtn} ${styles.heroBtnDesktop}`}+ >{t('hero.getStarted')}<svg className={styles.btnArrow} width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="m6 12 4-4-4-4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />@@ -178,9 +193,9 @@ function Hero() {className={styles.heroMobileLink}style={{ marginTop: '10px' }}onClick={() => {- const el = document.getElementById('download');+ const el = document.getElementById('download')if (el) {- el.scrollIntoView({ behavior: 'smooth' });+ el.scrollIntoView({ behavior: 'smooth' })}}}>@@ -188,13 +203,13 @@ function Hero() {</p></div></section>- );+ )}// Brand partner logo section - social media platforms (infinite scroll)function BrandBar() {- const { t } = useTransClient('home');- const { lng } = useParams();+ const { t } = useTransClient('home')+ const { lng } = useParams()// Platform data configurationconst platforms = [@@ -212,18 +227,18 @@ function BrandBar() {{ name: 'Pinterest', key: 'Pinterest', hasIcon: true, iconPath: PinterestIcon.src },{ name: 'Threads', key: 'Threads', hasIcon: true, iconPath: ThreadsIcon.src },{ name: 'X (Twitter)', key: 'X (Twitter)', hasIcon: true, iconPath: TwitterIcon.src },- ];+ ]// Duplicate data to achieve seamless scrolling- const duplicatedPlatforms = [...platforms, ...platforms];+ const duplicatedPlatforms = [...platforms, ...platforms]// Get platform display nameconst getPlatformDisplayName = (platform: any) => {if (lng === 'en') {- return platform.key;+ return platform.key}- return platform.name;- };+ return platform.name+ }return (<section className={styles.brandBar}>@@ -234,15 +249,17 @@ function BrandBar() {{duplicatedPlatforms.map((platform, index) => (<div key={index} className={styles.platformItem}><div className={styles.platformIcon}>- {platform.hasIcon ? (- <img- src={platform.iconPath}- alt={`${getPlatformDisplayName(platform)} logo`}- className={styles.platformSvg}- />- ) : (- <span className={styles.platformEmoji}>{getPlatformDisplayName(platform)}</span>- )}+ {platform.hasIcon+ ? (+ <img+ src={platform.iconPath}+ alt={`${getPlatformDisplayName(platform)} logo`}+ className={styles.platformSvg}+ />+ )+ : (+ <span className={styles.platformEmoji}>{getPlatformDisplayName(platform)}</span>+ )}</div><span className={styles.platformName}>{getPlatformDisplayName(platform)}</span></div>@@ -251,74 +268,77 @@ function BrandBar() {</div></div></section>- );+ )}// 1. Content Publishing — One-click publishing · Multi-platform reachfunction ContentPublishingSection() {- const { t } = useTransClient('home');- const [currentImageIndex, setCurrentImageIndex] = useState(0);- const [autoRotate, setAutoRotate] = useState(true);- const images = [IMAGE_URLS.calendar, IMAGE_URLS.supportChannels];- const autoRotateRef = useRef<NodeJS.Timeout | null>(null);- const carouselRef = useRef<HTMLDivElement>(null);+ const { t } = useTransClient('home')+ const [currentImageIndex, setCurrentImageIndex] = useState(0)+ const [autoRotate, setAutoRotate] = useState(true)+ const images = [IMAGE_URLS.calendar, IMAGE_URLS.supportChannels]+ const autoRotateRef = useRef<NodeJS.Timeout | null>(null)+ const carouselRef = useRef<HTMLDivElement>(null)// Auto rotationuseEffect(() => {if (autoRotate) {autoRotateRef.current = setInterval(() => {- setCurrentImageIndex(prev => (prev + 1) % images.length);- }, 3000);- } else {+ setCurrentImageIndex(prev => (prev + 1) % images.length)+ }, 3000)+ }+ else {if (autoRotateRef.current) {- clearInterval(autoRotateRef.current);- autoRotateRef.current = null;+ clearInterval(autoRotateRef.current)+ autoRotateRef.current = null}}return () => {if (autoRotateRef.current) {- clearInterval(autoRotateRef.current);+ clearInterval(autoRotateRef.current)}- };- }, [autoRotate, images.length]);+ }+ }, [autoRotate, images.length])// Wheel controluseEffect(() => {const handleWheel = (e: WheelEvent) => {if (carouselRef.current && carouselRef.current.contains(e.target as Node)) {- e.preventDefault();+ e.preventDefault()if (e.deltaY > 0) {if (currentImageIndex < images.length - 1) {- setCurrentImageIndex(prev => prev + 1);- setAutoRotate(false);- } else {- setAutoRotate(true);- return;+ setCurrentImageIndex(prev => prev + 1)+ setAutoRotate(false)+ }+ else {+ setAutoRotate(true)+ return}- } else {+ }+ else {if (currentImageIndex > 0) {- setCurrentImageIndex(prev => prev - 1);- setAutoRotate(false);+ setCurrentImageIndex(prev => prev - 1)+ setAutoRotate(false)}}setTimeout(() => {- setAutoRotate(true);- }, 3000);+ setAutoRotate(true)+ }, 3000)}- };+ }- const carousel = carouselRef.current;+ const carousel = carouselRef.currentif (carousel) {- carousel.addEventListener('wheel', handleWheel, { passive: false });+ carousel.addEventListener('wheel', handleWheel, { passive: false })return () => {- carousel.removeEventListener('wheel', handleWheel);- };+ carousel.removeEventListener('wheel', handleWheel)+ }}- }, [currentImageIndex, images.length]);+ }, [currentImageIndex, images.length])return (<section className={styles.buildSection}>@@ -374,9 +394,9 @@ function ContentPublishingSection() {key={index}className={`${styles.indicator} ${index === currentImageIndex ? styles.active : ''}`}onClick={() => {- setCurrentImageIndex(index);- setAutoRotate(false);- setTimeout(() => setAutoRotate(true), 3000);+ setCurrentImageIndex(index)+ setAutoRotate(false)+ setTimeout(() => setAutoRotate(true), 3000)}}/>))}@@ -390,74 +410,77 @@ function ContentPublishingSection() {</div></div></section>- );+ )}// 2. Content Hotspot — Viral inspiration enginefunction ContentHotspotSection() {- const { t } = useTransClient('home');- const [currentImageIndex, setCurrentImageIndex] = useState(0);- const [autoRotate, setAutoRotate] = useState(true);- const images = [IMAGE_URLS.hotspot, IMAGE_URLS.hotspot2, IMAGE_URLS.hotspot3, IMAGE_URLS.hotspot4];- const autoRotateRef = useRef<NodeJS.Timeout | null>(null);- const carouselRef = useRef<HTMLDivElement>(null);+ const { t } = useTransClient('home')+ const [currentImageIndex, setCurrentImageIndex] = useState(0)+ const [autoRotate, setAutoRotate] = useState(true)+ const images = [IMAGE_URLS.hotspot, IMAGE_URLS.hotspot2, IMAGE_URLS.hotspot3, IMAGE_URLS.hotspot4]+ const autoRotateRef = useRef<NodeJS.Timeout | null>(null)+ const carouselRef = useRef<HTMLDivElement>(null)// Auto rotationuseEffect(() => {if (autoRotate) {autoRotateRef.current = setInterval(() => {- setCurrentImageIndex(prev => (prev + 1) % images.length);- }, 3000);- } else {+ setCurrentImageIndex(prev => (prev + 1) % images.length)+ }, 3000)+ }+ else {if (autoRotateRef.current) {- clearInterval(autoRotateRef.current);- autoRotateRef.current = null;+ clearInterval(autoRotateRef.current)+ autoRotateRef.current = null}}return () => {if (autoRotateRef.current) {- clearInterval(autoRotateRef.current);+ clearInterval(autoRotateRef.current)}- };- }, [autoRotate, images.length]);+ }+ }, [autoRotate, images.length])// Wheel controluseEffect(() => {const handleWheel = (e: WheelEvent) => {if (carouselRef.current && carouselRef.current.contains(e.target as Node)) {- e.preventDefault();+ e.preventDefault()if (e.deltaY > 0) {if (currentImageIndex < images.length - 1) {- setCurrentImageIndex(prev => prev + 1);- setAutoRotate(false);- } else {- setAutoRotate(true);- return;+ setCurrentImageIndex(prev => prev + 1)+ setAutoRotate(false)+ }+ else {+ setAutoRotate(true)+ return}- } else {+ }+ else {if (currentImageIndex > 0) {- setCurrentImageIndex(prev => prev - 1);- setAutoRotate(false);+ setCurrentImageIndex(prev => prev - 1)+ setAutoRotate(false)}}setTimeout(() => {- setAutoRotate(true);- }, 3000);+ setAutoRotate(true)+ }, 3000)}- };+ }- const carousel = carouselRef.current;+ const carousel = carouselRef.currentif (carousel) {- carousel.addEventListener('wheel', handleWheel, { passive: false });+ carousel.addEventListener('wheel', handleWheel, { passive: false })return () => {- carousel.removeEventListener('wheel', handleWheel);- };+ carousel.removeEventListener('wheel', handleWheel)+ }}- }, [currentImageIndex, images.length]);+ }, [currentImageIndex, images.length])return (<section className={styles.buildSection}>@@ -513,9 +536,9 @@ function ContentHotspotSection() {key={index}className={`${styles.indicator} ${index === currentImageIndex ? styles.active : ''}`}onClick={() => {- setCurrentImageIndex(index);- setAutoRotate(false);- setTimeout(() => setAutoRotate(true), 3000);+ setCurrentImageIndex(index)+ setAutoRotate(false)+ setTimeout(() => setAutoRotate(true), 3000)}}/>))}@@ -529,74 +552,77 @@ function ContentHotspotSection() {</div></div></section>- );+ )}// 3. Content Search — Brand and market insightsfunction ContentSearchSection() {- const { t } = useTransClient('home');- const [currentImageIndex, setCurrentImageIndex] = useState(0);- const [autoRotate, setAutoRotate] = useState(true);- const images = [IMAGE_URLS.contentSearch, IMAGE_URLS.contentSearch1, IMAGE_URLS.contentSearch2, IMAGE_URLS.contentSearch4];- const autoRotateRef = useRef<NodeJS.Timeout | null>(null);- const carouselRef = useRef<HTMLDivElement>(null);+ const { t } = useTransClient('home')+ const [currentImageIndex, setCurrentImageIndex] = useState(0)+ const [autoRotate, setAutoRotate] = useState(true)+ const images = [IMAGE_URLS.contentSearch, IMAGE_URLS.contentSearch1, IMAGE_URLS.contentSearch2, IMAGE_URLS.contentSearch4]+ const autoRotateRef = useRef<NodeJS.Timeout | null>(null)+ const carouselRef = useRef<HTMLDivElement>(null)// Auto rotationuseEffect(() => {if (autoRotate) {autoRotateRef.current = setInterval(() => {- setCurrentImageIndex(prev => (prev + 1) % images.length);- }, 3000);- } else {+ setCurrentImageIndex(prev => (prev + 1) % images.length)+ }, 3000)+ }+ else {if (autoRotateRef.current) {- clearInterval(autoRotateRef.current);- autoRotateRef.current = null;+ clearInterval(autoRotateRef.current)+ autoRotateRef.current = null}}return () => {if (autoRotateRef.current) {- clearInterval(autoRotateRef.current);+ clearInterval(autoRotateRef.current)}- };- }, [autoRotate, images.length]);+ }+ }, [autoRotate, images.length])// Wheel controluseEffect(() => {const handleWheel = (e: WheelEvent) => {if (carouselRef.current && carouselRef.current.contains(e.target as Node)) {- e.preventDefault();+ e.preventDefault()if (e.deltaY > 0) {if (currentImageIndex < images.length - 1) {- setCurrentImageIndex(prev => prev + 1);- setAutoRotate(false);- } else {- setAutoRotate(true);- return;+ setCurrentImageIndex(prev => prev + 1)+ setAutoRotate(false)}- } else {+ else {+ setAutoRotate(true)+ return+ }+ }+ else {if (currentImageIndex > 0) {- setCurrentImageIndex(prev => prev - 1);- setAutoRotate(false);+ setCurrentImageIndex(prev => prev - 1)+ setAutoRotate(false)}}setTimeout(() => {- setAutoRotate(true);- }, 3000);+ setAutoRotate(true)+ }, 3000)}- };+ }- const carousel = carouselRef.current;+ const carousel = carouselRef.currentif (carousel) {- carousel.addEventListener('wheel', handleWheel, { passive: false });+ carousel.addEventListener('wheel', handleWheel, { passive: false })return () => {- carousel.removeEventListener('wheel', handleWheel);- };+ carousel.removeEventListener('wheel', handleWheel)+ }}- }, [currentImageIndex, images.length]);+ }, [currentImageIndex, images.length])return (<section className={styles.buildSection}>@@ -652,9 +678,9 @@ function ContentSearchSection() {key={index}className={`${styles.indicator} ${index === currentImageIndex ? styles.active : ''}`}onClick={() => {- setCurrentImageIndex(index);- setAutoRotate(false);- setTimeout(() => setAutoRotate(true), 3000);+ setCurrentImageIndex(index)+ setAutoRotate(false)+ setTimeout(() => setAutoRotate(true), 3000)}}/>))}@@ -668,74 +694,77 @@ function ContentSearchSection() {</div></div></section>- );+ )}// 4. Comments Search — Precise user miningfunction CommentsSearchSection() {- const { t } = useTransClient('home');- const [currentImageIndex, setCurrentImageIndex] = useState(0);- const [autoRotate, setAutoRotate] = useState(true);- const images = [IMAGE_URLS.commentFilter];- const autoRotateRef = useRef<NodeJS.Timeout | null>(null);- const carouselRef = useRef<HTMLDivElement>(null);+ const { t } = useTransClient('home')+ const [currentImageIndex, setCurrentImageIndex] = useState(0)+ const [autoRotate, setAutoRotate] = useState(true)+ const images = [IMAGE_URLS.commentFilter]+ const autoRotateRef = useRef<NodeJS.Timeout | null>(null)+ const carouselRef = useRef<HTMLDivElement>(null)// Auto rotationuseEffect(() => {if (autoRotate) {autoRotateRef.current = setInterval(() => {- setCurrentImageIndex(prev => (prev + 1) % images.length);- }, 3000);- } else {+ setCurrentImageIndex(prev => (prev + 1) % images.length)+ }, 3000)+ }+ else {if (autoRotateRef.current) {- clearInterval(autoRotateRef.current);- autoRotateRef.current = null;+ clearInterval(autoRotateRef.current)+ autoRotateRef.current = null}}return () => {if (autoRotateRef.current) {- clearInterval(autoRotateRef.current);+ clearInterval(autoRotateRef.current)}- };- }, [autoRotate, images.length]);+ }+ }, [autoRotate, images.length])// Wheel controluseEffect(() => {const handleWheel = (e: WheelEvent) => {if (carouselRef.current && carouselRef.current.contains(e.target as Node)) {- e.preventDefault();+ e.preventDefault()if (e.deltaY > 0) {if (currentImageIndex < images.length - 1) {- setCurrentImageIndex(prev => prev + 1);- setAutoRotate(false);- } else {- setAutoRotate(true);- return;+ setCurrentImageIndex(prev => prev + 1)+ setAutoRotate(false)}- } else {+ else {+ setAutoRotate(true)+ return+ }+ }+ else {if (currentImageIndex > 0) {- setCurrentImageIndex(prev => prev - 1);- setAutoRotate(false);+ setCurrentImageIndex(prev => prev - 1)+ setAutoRotate(false)}}setTimeout(() => {- setAutoRotate(true);- }, 3000);+ setAutoRotate(true)+ }, 3000)}- };+ }- const carousel = carouselRef.current;+ const carousel = carouselRef.currentif (carousel) {- carousel.addEventListener('wheel', handleWheel, { passive: false });+ carousel.addEventListener('wheel', handleWheel, { passive: false })return () => {- carousel.removeEventListener('wheel', handleWheel);- };+ carousel.removeEventListener('wheel', handleWheel)+ }}- }, [currentImageIndex, images.length]);+ }, [currentImageIndex, images.length])return (<section className={styles.buildSection}>@@ -791,9 +820,9 @@ function CommentsSearchSection() {key={index}className={`${styles.indicator} ${index === currentImageIndex ? styles.active : ''}`}onClick={() => {- setCurrentImageIndex(index);- setAutoRotate(false);- setTimeout(() => setAutoRotate(true), 3000);+ setCurrentImageIndex(index)+ setAutoRotate(false)+ setTimeout(() => setAutoRotate(true), 3000)}}/>))}@@ -807,74 +836,77 @@ function CommentsSearchSection() {</div></div></section>- );+ )}// 5. Content Engagement — Interaction and growth enginefunction ContentEngagementSection() {- const { t } = useTransClient('home');- const [currentImageIndex, setCurrentImageIndex] = useState(0);- const [autoRotate, setAutoRotate] = useState(true);- const images = [IMAGE_URLS.commentFilter2];- const autoRotateRef = useRef<NodeJS.Timeout | null>(null);- const carouselRef = useRef<HTMLDivElement>(null);+ const { t } = useTransClient('home')+ const [currentImageIndex, setCurrentImageIndex] = useState(0)+ const [autoRotate, setAutoRotate] = useState(true)+ const images = [IMAGE_URLS.commentFilter2]+ const autoRotateRef = useRef<NodeJS.Timeout | null>(null)+ const carouselRef = useRef<HTMLDivElement>(null)// Auto rotationuseEffect(() => {if (autoRotate) {autoRotateRef.current = setInterval(() => {- setCurrentImageIndex(prev => (prev + 1) % images.length);- }, 3000);- } else {+ setCurrentImageIndex(prev => (prev + 1) % images.length)+ }, 3000)+ }+ else {if (autoRotateRef.current) {- clearInterval(autoRotateRef.current);- autoRotateRef.current = null;+ clearInterval(autoRotateRef.current)+ autoRotateRef.current = null}}return () => {if (autoRotateRef.current) {- clearInterval(autoRotateRef.current);+ clearInterval(autoRotateRef.current)}- };- }, [autoRotate, images.length]);+ }+ }, [autoRotate, images.length])// Wheel controluseEffect(() => {const handleWheel = (e: WheelEvent) => {if (carouselRef.current && carouselRef.current.contains(e.target as Node)) {- e.preventDefault();+ e.preventDefault()if (e.deltaY > 0) {if (currentImageIndex < images.length - 1) {- setCurrentImageIndex(prev => prev + 1);- setAutoRotate(false);- } else {- setAutoRotate(true);- return;+ setCurrentImageIndex(prev => prev + 1)+ setAutoRotate(false)}- } else {+ else {+ setAutoRotate(true)+ return+ }+ }+ else {if (currentImageIndex > 0) {- setCurrentImageIndex(prev => prev - 1);- setAutoRotate(false);+ setCurrentImageIndex(prev => prev - 1)+ setAutoRotate(false)}}setTimeout(() => {- setAutoRotate(true);- }, 3000);+ setAutoRotate(true)+ }, 3000)}- };+ }- const carousel = carouselRef.current;+ const carousel = carouselRef.currentif (carousel) {- carousel.addEventListener('wheel', handleWheel, { passive: false });+ carousel.addEventListener('wheel', handleWheel, { passive: false })return () => {- carousel.removeEventListener('wheel', handleWheel);- };+ carousel.removeEventListener('wheel', handleWheel)+ }}- }, [currentImageIndex, images.length]);+ }, [currentImageIndex, images.length])return (<section className={styles.buildSection}>@@ -930,9 +962,9 @@ function ContentEngagementSection() {key={index}className={`${styles.indicator} ${index === currentImageIndex ? styles.active : ''}`}onClick={() => {- setCurrentImageIndex(index);- setAutoRotate(false);- setTimeout(() => setAutoRotate(true), 3000);+ setCurrentImageIndex(index)+ setAutoRotate(false)+ setTimeout(() => setAutoRotate(true), 3000)}}/>))}@@ -946,12 +978,12 @@ function ContentEngagementSection() {</div></div></section>- );+ )}// 6-8. Upcoming features integration modulefunction UpcomingFeaturesSection() {- const { t } = useTransClient('home');+ const { t } = useTransClient('home')return (<section className={styles.buildSection}>@@ -996,7 +1028,7 @@ function UpcomingFeaturesSection() {<div className={styles.carouselContainer}><div className={`${styles.carouselSlide} ${styles.active}`}><video- src={'https://aitoearn.s3.ap-southeast-1.amazonaws.com/production/temp/uploads/890044ad-c3a3-4a4c-8981-0eb72abff538.mp4'}+ src="https://aitoearn.s3.ap-southeast-1.amazonaws.com/production/temp/uploads/890044ad-c3a3-4a4c-8981-0eb72abff538.mp4"controlsclassName={styles.desktopCarouselImage}style={{ borderRadius: '16px', boxShadow: '0 20px 60px rgba(0, 0, 0, 0.2)' }}@@ -1008,13 +1040,11 @@ function UpcomingFeaturesSection() {</div></div></section>- );+ )}-// Mobile app download section-import { QRCode } from 'react-qrcode-logo';function DownloadSection() {- const { t } = useTransClient('home');+ const { t } = useTransClient('home')return (<section className={styles.downloadSection} id="download">@@ -1022,7 +1052,8 @@ function DownloadSection() {<div className={styles.downloadContent}><div className={styles.downloadLeft}><h2 className={styles.downloadTitle}>- {t('downloadSection.title')}<br />+ {t('downloadSection.title')}+ <br /><span className={styles.titleBlue}>{t('downloadSection.titleBlue')}</span></h2>@@ -1065,7 +1096,6 @@ function DownloadSection() {<p className={styles.qrCodeText}>{t('downloadSection.qrCodeText' as any)}</p></div>-<div className={styles.phoneFrame}><div className={styles.phoneScreen}><div className={styles.phoneStatusBar}>@@ -1101,20 +1131,17 @@ function DownloadSection() {</div></div>-</div></div></div></div></section>- );+ )}--// Enterprise sectionfunction EnterpriseSection() {- const { t } = useTransClient('home');+ const { t } = useTransClient('home')return (<section className={styles.enterpriseSection}>@@ -1125,7 +1152,8 @@ function EnterpriseSection() {</div><h2 className={styles.enterpriseTitle}>- {t('enterpriseSection.title')}<br />+ {t('enterpriseSection.title')}+ <br /><span className={styles.titleBlue}>{t('enterpriseSection.titleBlue')}</span></h2>@@ -1134,12 +1162,12 @@ function EnterpriseSection() {</p></div></section>- );+ )}// Statistics sectionfunction StatsSection() {- const { t } = useTransClient('home');+ const { t } = useTransClient('home')return (<section className={styles.statsSection}>@@ -1165,7 +1193,11 @@ function StatsSection() {<div className={styles.testimonialCard}><div className={styles.testimonialContent}>- <p>"{t('statsSection.testimonial.quote')}"</p>+ <p>+ "+ {t('statsSection.testimonial.quote')}+ "+ </p><div className={styles.testimonialAuthor}><div className={styles.authorName}>{t('statsSection.testimonial.author')}</div><div className={styles.authorTitle}>{t('statsSection.testimonial.title')}</div>@@ -1184,13 +1216,13 @@ function StatsSection() {</div></div></section>- );+ )}// Community sectionfunction CommunitySection() {- const { t } = useTransClient('home');- const [hoveredButton, setHoveredButton] = useState<string | null>(null);+ const { t } = useTransClient('home')+ const [hoveredButton, setHoveredButton] = useState<string | null>(null)return (<section className={styles.communitySection}>@@ -1201,7 +1233,8 @@ function CommunitySection() {</div><h2 className={styles.communityTitle}>- {t('communitySection.title')}<br />+ {t('communitySection.title')}+ <br /><span className={styles.titleBlue}>{t('communitySection.titleBlue')}</span></h2>@@ -1269,43 +1302,44 @@ function CommunitySection() {</div></div></section>- );+ )}// Footerfunction Footer() {- const { t } = useTransClient('home');- const [isHovered, setIsHovered] = useState(false);- const [currentImageIndex, setCurrentImageIndex] = useState(0);- const intervalRef = useRef<NodeJS.Timeout | null>(null);- const router = useRouter();+ const { t } = useTransClient('home')+ const [isHovered, setIsHovered] = useState(false)+ const [currentImageIndex, setCurrentImageIndex] = useState(0)+ const intervalRef = useRef<NodeJS.Timeout | null>(null)+ const router = useRouter()// Background image arrayconst backgroundImages = [IMAGE_URLS.hotspot,IMAGE_URLS.hotspot2,IMAGE_URLS.hotspot3,IMAGE_URLS.hotspot4,- ];+ ]useEffect(() => {if (isHovered) {intervalRef.current = setInterval(() => {- setCurrentImageIndex(prev => (prev + 1) % backgroundImages.length);- }, 1000);- } else {+ setCurrentImageIndex(prev => (prev + 1) % backgroundImages.length)+ }, 1000)+ }+ else {if (intervalRef.current) {- clearInterval(intervalRef.current);- intervalRef.current = null;+ clearInterval(intervalRef.current)+ intervalRef.current = null}- setCurrentImageIndex(0);+ setCurrentImageIndex(0)}return () => {if (intervalRef.current) {- clearInterval(intervalRef.current);+ clearInterval(intervalRef.current)}- };- }, [isHovered, backgroundImages.length]);+ }+ }, [isHovered, backgroundImages.length])return (<footer className={styles.footer}>@@ -1326,14 +1360,23 @@ function Footer() {<div className={styles.footerColumn}><h4>{t('footer.company.title')}</h4><a onClick={() => {- router.push("/websit/terms-of-service");- }}>{t('footer.company.links.terms')}</a>+ router.push('/websit/terms-of-service')+ }}+ >+ {t('footer.company.links.terms')}+ </a><a onClick={() => {- router.push("/websit/privacy-policy");- }}>{t('footer.company.links.privacy')}</a>+ router.push('/websit/privacy-policy')+ }}+ >+ {t('footer.company.links.privacy')}+ </a><a onClick={() => {- router.push("/websit/data-deletion");- }}>{t('footer.company.links.data')}</a>+ router.push('/websit/data-deletion')+ }}+ >+ {t('footer.company.links.data')}+ </a></div></div>@@ -1370,7 +1413,7 @@ function Footer() {backgroundClip: 'text',WebkitBackgroundClip: 'text',color: isHovered ? 'transparent' : '#733DEC',- textShadow: '0 2px 4px rgba(0, 0, 0, 0.2)'+ textShadow: '0 2px 4px rgba(0, 0, 0, 0.2)',}}>Earn@@ -1404,7 +1447,7 @@ function Footer() {</div></div></footer>- );+ )}export default function Home() {@@ -1420,10 +1463,10 @@ export default function Home() {<ContentEngagementSection /><UpcomingFeaturesSection /><DownloadSection />- {/*<EnterpriseSection />+ {/* <EnterpriseSection /><StatsSection /> */}{/* <CommunitySection /> */}<Footer /></div>- );+ )}diff --git a/project/web/src/app/[lng]/pinterest/page.tsx b/project/web/src/app/[lng]/pinterest/page.tsxindex 57d88c06..b0a36d6d 100644--- a/project/web/src/app/[lng]/pinterest/page.tsx+++ b/project/web/src/app/[lng]/pinterest/page.tsx@@ -1,438 +1,461 @@-"use client";--import { useState, useEffect, useRef } from "react";-import {- Button,- Tabs,- Modal,- Form,- Input,- Select,- Upload,- message,- Pagination,- Spin,- Popconfirm,- Badge,- Card,- Row,- Col,- Statistic,- Typography,- Empty,- Divider-} from "antd";-import {- PlusOutlined,- DeleteOutlined,- EditOutlined,+'use client'++import {+ BarChartOutlined,+ BarsOutlined,+ DeleteOutlined,+ EditOutlined,+ EyeOutlined,+ LinkOutlined,PictureOutlined,+ PlusOutlined,+ PushpinOutlined,ReloadOutlined,SearchOutlined,UploadOutlined,- EyeOutlined,- LinkOutlined,- BarsOutlined,- PushpinOutlined,UserOutlined,- BarChartOutlined-} from "@ant-design/icons";-import styles from "./pinterest.module.scss";+} from '@ant-design/icons'+import {+ Badge,+ Button,+ Card,+ Col,+ Divider,+ Empty,+ Form,+ Input,+ message,+ Modal,+ Pagination,+ Popconfirm,+ Row,+ Select,+ Spin,+ Statistic,+ Tabs,+ Typography,+ Upload,+} from 'antd'+import { useEffect, useRef, useState } from 'react'+import { getAccountListApi } from '@/api/account'+import { uploadToOss } from '@/api/oss'import {- getPinterestBoardListApi,createPinterestBoardApi,- deletePinterestBoardApi,- getPinterestPinListApi,createPinterestPinApi,+ deletePinterestBoardApi,deletePinterestPinApi,getPinterestAccountApi,getPinterestBoardApi,- getPinterestPinApi-} from "@/api/pinterest";-import { getAccountListApi } from "@/api/account";-import { PlatType } from "@/app/config/platConfig";-import { uploadToOss } from "@/api/oss";-import { getOssUrl } from "@/utils/oss";-import { useTransClient } from "@/app/i18n/client";--const { Search } = Input;-const { TextArea } = Input;-const { Text, Title } = Typography;+ getPinterestBoardListApi,+ getPinterestPinApi,+ getPinterestPinListApi,+} from '@/api/pinterest'+import { PlatType } from '@/app/config/platConfig'+import { useTransClient } from '@/app/i18n/client'+import { getOssUrl } from '@/utils/oss'+import styles from './pinterest.module.scss'++const { Search } = Input+const { TextArea } = Input+const { Text, Title } = Typography// 自定义颜色选择器组件-const CustomColorPicker = ({ value, onChange }: { value?: string; onChange?: (value: string) => void }) => {- const { t } = useTransClient('pinterest');-+function CustomColorPicker({ value, onChange }: { value?: string, onChange?: (value: string) => void }) {+ const { t } = useTransClient('pinterest')+return (<div className={styles.colorPickerContainer}><inputtype="color"className={styles.colorPicker}- value={value || "#e60023"}- onChange={(e) => onChange?.(e.target.value)}+ value={value || '#e60023'}+ onChange={e => onChange?.(e.target.value)}/><Text type="secondary" className={styles.colorPickerTip}>{t('pin.dominantColorTip')}</Text></div>- );-};+ )+}export default function PinterestPage() {// 翻译函数- const { t } = useTransClient('pinterest');+ const { t } = useTransClient('pinterest')// 状态管理- const [activeTab, setActiveTab] = useState("boards");- const [loading, setLoading] = useState(false);- const [accounts, setAccounts] = useState<any[]>([]);- const [boards, setBoards] = useState<any[]>([]);- const [pins, setPins] = useState<any[]>([]);- const [selectedAccount, setSelectedAccount] = useState<any>(null);-+ const [activeTab, setActiveTab] = useState('boards')+ const [loading, setLoading] = useState(false)+ const [accounts, setAccounts] = useState<any[]>([])+ const [boards, setBoards] = useState<any[]>([])+ const [pins, setPins] = useState<any[]>([])+ const [selectedAccount, setSelectedAccount] = useState<any>(null)+// 模态框状态- const [boardModalVisible, setBoardModalVisible] = useState(false);- const [pinModalVisible, setPinModalVisible] = useState(false);- const [boardDetailModalVisible, setBoardDetailModalVisible] = useState(false);- const [pinDetailModalVisible, setPinDetailModalVisible] = useState(false);-+ const [boardModalVisible, setBoardModalVisible] = useState(false)+ const [pinModalVisible, setPinModalVisible] = useState(false)+ const [boardDetailModalVisible, setBoardDetailModalVisible] = useState(false)+ const [pinDetailModalVisible, setPinDetailModalVisible] = useState(false)+// 表单- const [boardForm] = Form.useForm();- const [pinForm] = Form.useForm();-+ const [boardForm] = Form.useForm()+ const [pinForm] = Form.useForm()+// 分页- const [currentPage, setCurrentPage] = useState(1);- const [pageSize, setPageSize] = useState(10);- const [total, setTotal] = useState(0);-+ const [currentPage, setCurrentPage] = useState(1)+ const [pageSize, setPageSize] = useState(10)+ const [total, setTotal] = useState(0)+// 搜索- const [searchKeyword, setSearchKeyword] = useState("");-+ const [searchKeyword, setSearchKeyword] = useState('')+// 选中的项目- const [selectedBoard, setSelectedBoard] = useState<any>(null);- const [selectedPin, setSelectedPin] = useState<any>(null);-+ const [selectedBoard, setSelectedBoard] = useState<any>(null)+ const [selectedPin, setSelectedPin] = useState<any>(null)+// 图片上传- const [imageFile, setImageFile] = useState<File | null>(null);- const [imagePreview, setImagePreview] = useState<string>("");- const [imageUrl, setImageUrl] = useState<string>("");- const [uploading, setUploading] = useState(false);- const fileInputRef = useRef<HTMLInputElement>(null);+ const [imageFile, setImageFile] = useState<File | null>(null)+ const [imagePreview, setImagePreview] = useState<string>('')+ const [imageUrl, setImageUrl] = useState<string>('')+ const [uploading, setUploading] = useState(false)+ const fileInputRef = useRef<HTMLInputElement>(null)// 初始化数据useEffect(() => {- loadAccountList();- }, []);+ loadAccountList()+ }, [])// 当selectedAccount变化时重新加载数据useEffect(() => {if (selectedAccount?.id) {- if (activeTab === "boards") {- loadBoards(1, 20);- } else {- loadPins(1, 10);+ if (activeTab === 'boards') {+ loadBoards(1, 20)+ }+ else {+ loadPins(1, 10)}}- }, [selectedAccount, activeTab]);-+ }, [selectedAccount, activeTab])// 加载账户列表const loadAccountList = async () => {try {- setLoading(true);- const response = await getAccountListApi();+ setLoading(true)+ const response = await getAccountListApi()if (response?.code === 0) {// 过滤出Pinterest账户- const pinterestAccounts = response.data.filter((account: any) => account.type === PlatType.Pinterest);- setAccounts(pinterestAccounts);+ const pinterestAccounts = response.data.filter((account: any) => account.type === PlatType.Pinterest)+ setAccounts(pinterestAccounts)if (pinterestAccounts.length > 0) {- setSelectedAccount(pinterestAccounts[0]);+ setSelectedAccount(pinterestAccounts[0])}}- } catch (error) {- message.error(t('messages.loadAccountsFailed'));- } finally {- setLoading(false);}- };-- // 加载boards- const loadBoards = async (page = 1, size = 20) => {- if (!selectedAccount?.id) return;-- try {- setLoading(true);- const response = await getPinterestBoardListApi({ page, size }, selectedAccount.id);- if (response?.code === 0) {- setBoards(response.data?.list || []);- setTotal(response.data?.count || 0);- }- } catch (error) {- message.error(t('messages.loadBoardsFailed'));- } finally {- setLoading(false);+ catch (error) {+ message.error(t('messages.loadAccountsFailed'))+ }+ finally {+ setLoading(false)+ }+ }++ // 加载boards+ const loadBoards = async (page = 1, size = 20) => {+ if (!selectedAccount?.id)+ return++ try {+ setLoading(true)+ const response = await getPinterestBoardListApi({ page, size }, selectedAccount.id)+ if (response?.code === 0) {+ setBoards(response.data?.list || [])+ setTotal(response.data?.count || 0)}- };-- // 加载pins- const loadPins = async (page = 1, size = 10) => {- if (!selectedAccount?.id) return;-- try {- setLoading(true);- const response = await getPinterestPinListApi({ page: page, size }, selectedAccount.id);- if (response?.code === 0) {- setPins(response.data?.list || []);- setTotal(response.data?.count || 0);- setCurrentPage(page);- setPageSize(size);- }- } catch (error) {- message.error(t('messages.loadPinsFailed'));- } finally {- setLoading(false);+ }+ catch (error) {+ message.error(t('messages.loadBoardsFailed'))+ }+ finally {+ setLoading(false)+ }+ }++ // 加载pins+ const loadPins = async (page = 1, size = 10) => {+ if (!selectedAccount?.id)+ return++ try {+ setLoading(true)+ const response = await getPinterestPinListApi({ page, size }, selectedAccount.id)+ if (response?.code === 0) {+ setPins(response.data?.list || [])+ setTotal(response.data?.count || 0)+ setCurrentPage(page)+ setPageSize(size)}- };+ }+ catch (error) {+ message.error(t('messages.loadPinsFailed'))+ }+ finally {+ setLoading(false)+ }+ }// 创建Boardconst handleCreateBoard = async (values: any) => {if (!selectedAccount?.id) {- message.error(t('messages.loadAccountsFailed'));- return;+ message.error(t('messages.loadAccountsFailed'))+ return}try {- setLoading(true);- const response = await createPinterestBoardApi(values, selectedAccount.id);+ setLoading(true)+ const response = await createPinterestBoardApi(values, selectedAccount.id)if (response?.code === 0) {- message.success(t('messages.boardCreateSuccess'));- setBoardModalVisible(false);- boardForm.resetFields();- loadBoards(1, 20);+ message.success(t('messages.boardCreateSuccess'))+ setBoardModalVisible(false)+ boardForm.resetFields()+ loadBoards(1, 20)}- } catch (error) {- message.error(t('messages.boardCreateFailed'));- } finally {- setLoading(false);}- };+ catch (error) {+ message.error(t('messages.boardCreateFailed'))+ }+ finally {+ setLoading(false)+ }+ }// 删除Boardconst handleDeleteBoard = async (boardId: string) => {if (!selectedAccount?.id) {- message.error(t('messages.loadAccountsFailed'));- return;+ message.error(t('messages.loadAccountsFailed'))+ return}try {- setLoading(true);- const response = await deletePinterestBoardApi(boardId, selectedAccount.id);+ setLoading(true)+ const response = await deletePinterestBoardApi(boardId, selectedAccount.id)if (response?.code === 0) {- message.success(t('messages.boardDeleteSuccess'));- loadBoards(1, 20);+ message.success(t('messages.boardDeleteSuccess'))+ loadBoards(1, 20)}- } catch (error) {- message.error(t('messages.boardDeleteFailed'));- } finally {- setLoading(false);}- };+ catch (error) {+ message.error(t('messages.boardDeleteFailed'))+ }+ finally {+ setLoading(false)+ }+ }// 创建Pinconst handleCreatePin = async (values: any) => {if (!imageUrl) {- message.error(t('messages.uploadImageFirst'));- return;+ message.error(t('messages.uploadImageFirst'))+ return}if (!selectedAccount?.id) {- message.error(t('messages.loadAccountsFailed'));- return;+ message.error(t('messages.loadAccountsFailed'))+ return}try {- setLoading(true);+ setLoading(true)const pinData = {board_id: values.board_id,link: values.link,title: values.title,description: values.description,- dominant_color: values.dominant_color || "#e60023",+ dominant_color: values.dominant_color || '#e60023',alt_text: values.alt_text,media_source: {- source_type: "image_url",- url: imageUrl- }- };+ source_type: 'image_url',+ url: imageUrl,+ },+ }- const response = await createPinterestPinApi(pinData, selectedAccount.id);+ const response = await createPinterestPinApi(pinData, selectedAccount.id)if (response?.code === 0) {- message.success(t('messages.pinCreateSuccess'));- setPinModalVisible(false);- pinForm.resetFields();- resetImageUpload();- loadPins(currentPage, pageSize);+ message.success(t('messages.pinCreateSuccess'))+ setPinModalVisible(false)+ pinForm.resetFields()+ resetImageUpload()+ loadPins(currentPage, pageSize)}- } catch (error) {- message.error(t('messages.pinCreateFailed'));- } finally {- setLoading(false);}- };+ catch (error) {+ message.error(t('messages.pinCreateFailed'))+ }+ finally {+ setLoading(false)+ }+ }// 删除Pinconst handleDeletePin = async (pinId: string) => {if (!selectedAccount?.id) {- message.error(t('messages.loadAccountsFailed'));- return;+ message.error(t('messages.loadAccountsFailed'))+ return}try {- setLoading(true);- const response = await deletePinterestPinApi(pinId, selectedAccount.id);+ setLoading(true)+ const response = await deletePinterestPinApi(pinId, selectedAccount.id)if (response?.code === 0) {- message.success(t('messages.pinDeleteSuccess'));- loadPins(currentPage, pageSize);+ message.success(t('messages.pinDeleteSuccess'))+ loadPins(currentPage, pageSize)}- } catch (error) {- message.error(t('messages.pinDeleteFailed'));- } finally {- setLoading(false);}- };+ catch (error) {+ message.error(t('messages.pinDeleteFailed'))+ }+ finally {+ setLoading(false)+ }+ }// 重置图片上传状态const resetImageUpload = () => {- setImageFile(null);- setImagePreview("");- setImageUrl("");- setUploading(false);- };+ setImageFile(null)+ setImagePreview('')+ setImageUrl('')+ setUploading(false)+ }// 图片上传处理const handleImageUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {- const file = event.target.files?.[0];- if (!file) return;+ const file = event.target.files?.[0]+ if (!file)+ return- if (!file.type.startsWith("image/")) {- message.error(t('messages.selectImageFile'));- return;+ if (!file.type.startsWith('image/')) {+ message.error(t('messages.selectImageFile'))+ return}// 检查文件大小 (限制10MB)if (file.size > 10 * 1024 * 1024) {- message.error(t('messages.imageSizeLimit'));- return;+ message.error(t('messages.imageSizeLimit'))+ return}try {- setUploading(true);- setImageFile(file);+ setUploading(true)+ setImageFile(file)// 生成预览图- const reader = new FileReader();+ const reader = new FileReader()reader.onload = (e) => {- setImagePreview(e.target?.result as string);- };- reader.readAsDataURL(file);+ setImagePreview(e.target?.result as string)+ }+ reader.readAsDataURL(file)// 上传到OSS- const ossFileName = await uploadToOss(file);- const fullImageUrl = getOssUrl(ossFileName);-- setImageUrl(fullImageUrl);- message.success(t('messages.imageUploadSuccess'));- } catch (error) {- console.error("图片上传失败:", error);- message.error(t('messages.imageUploadFailed'));- resetImageUpload();- } finally {- setUploading(false);+ const ossFileName = await uploadToOss(file)+ const fullImageUrl = getOssUrl(ossFileName)++ setImageUrl(fullImageUrl)+ message.success(t('messages.imageUploadSuccess'))}- };+ catch (error) {+ console.error('图片上传失败:', error)+ message.error(t('messages.imageUploadFailed'))+ resetImageUpload()+ }+ finally {+ setUploading(false)+ }+ }// 查看Board详情const handleViewBoard = async (board: any) => {if (!selectedAccount?.id) {- message.error(t('messages.loadAccountsFailed'));- return;+ message.error(t('messages.loadAccountsFailed'))+ return}try {- setLoading(true);- const response = await getPinterestBoardApi(board.id, selectedAccount.id);+ setLoading(true)+ const response = await getPinterestBoardApi(board.id, selectedAccount.id)if (response?.code === 0) {- setSelectedBoard(response.data);- setBoardDetailModalVisible(true);+ setSelectedBoard(response.data)+ setBoardDetailModalVisible(true)}- } catch (error) {- message.error(t('messages.getBoardDetailFailed'));- } finally {- setLoading(false);}- };+ catch (error) {+ message.error(t('messages.getBoardDetailFailed'))+ }+ finally {+ setLoading(false)+ }+ }// 查看Pin详情const handleViewPin = async (pin: any) => {if (!selectedAccount?.id) {- message.error(t('messages.loadAccountsFailed'));- return;+ message.error(t('messages.loadAccountsFailed'))+ return}try {- setLoading(true);- const response = await getPinterestPinApi(pin.id, selectedAccount.id);+ setLoading(true)+ const response = await getPinterestPinApi(pin.id, selectedAccount.id)if (response?.code === 0) {- setSelectedPin(response.data);- setPinDetailModalVisible(true);+ setSelectedPin(response.data)+ setPinDetailModalVisible(true)}- } catch (error) {- message.error(t('messages.getPinDetailFailed'));- } finally {- setLoading(false);}- };+ catch (error) {+ message.error(t('messages.getPinDetailFailed'))+ }+ finally {+ setLoading(false)+ }+ }// 过滤boards- const filteredBoards = boards.filter(board =>+ const filteredBoards = boards.filter(board =>board && (- board.name?.toLowerCase().includes(searchKeyword.toLowerCase()) ||- (board.description && board.description.toLowerCase().includes(searchKeyword.toLowerCase()))- )- );+ board.name?.toLowerCase().includes(searchKeyword.toLowerCase())+ || (board.description && board.description.toLowerCase().includes(searchKeyword.toLowerCase()))+ ),+ )// 过滤pins- const filteredPins = pins.filter(pin =>+ const filteredPins = pins.filter(pin =>pin && (- pin.title?.toLowerCase().includes(searchKeyword.toLowerCase()) ||- (pin.description && pin.description.toLowerCase().includes(searchKeyword.toLowerCase())) ||- (pin.note && pin.note.toLowerCase().includes(searchKeyword.toLowerCase())) ||- (pin.alt_text && pin.alt_text.toLowerCase().includes(searchKeyword.toLowerCase())) ||- (pin.creative_type && pin.creative_type.toLowerCase().includes(searchKeyword.toLowerCase()))- )- );+ pin.title?.toLowerCase().includes(searchKeyword.toLowerCase())+ || (pin.description && pin.description.toLowerCase().includes(searchKeyword.toLowerCase()))+ || (pin.note && pin.note.toLowerCase().includes(searchKeyword.toLowerCase()))+ || (pin.alt_text && pin.alt_text.toLowerCase().includes(searchKeyword.toLowerCase()))+ || (pin.creative_type && pin.creative_type.toLowerCase().includes(searchKeyword.toLowerCase()))+ ),+ )// Tab标签const tabItems = [{- key: "boards",+ key: 'boards',label: (<span>- <BarsOutlined />- {t('tabs.boards')}+ <BarsOutlined />+ {t('tabs.boards')}</span>- )+ ),},{- key: "pins",+ key: 'pins',label: (<span>- <PushpinOutlined />- {t('tabs.pins')}+ <PushpinOutlined />+ {t('tabs.pins')}</span>- )- }- ];+ ),+ },+ ]return (<div className={styles.container}>@@ -447,8 +470,8 @@ export default function PinterestPage() {placeholder={t('actions.selectAccount')}value={selectedAccount?.id}onChange={(value) => {- const account = accounts.find(acc => acc.id === value);- setSelectedAccount(account || null);+ const account = accounts.find(acc => acc.id === value)+ setSelectedAccount(account || null)}}>{accounts.map(account => (@@ -457,13 +480,14 @@ export default function PinterestPage() {</Select.Option>))}</Select>- <Button- icon={<ReloadOutlined />}+ <Button+ icon={<ReloadOutlined />}onClick={() => {- if (activeTab === "boards") {- loadBoards(1, 20);- } else {- loadPins(currentPage, pageSize);+ if (activeTab === 'boards') {+ loadBoards(1, 20)+ }+ else {+ loadPins(currentPage, pageSize)}}}className={styles.refreshButton}@@ -477,35 +501,35 @@ export default function PinterestPage() {<Card className={styles.statsCard}><Row gutter={[24, 16]}><Col xs={12} sm={6}>- <Statistic- title={t('stats.followers')}+ <Statistic+ title={t('stats.followers')}value={selectedAccount.fansCount || 0}prefix={<UserOutlined />}- formatter={(value) => value?.toLocaleString()}+ formatter={value => value?.toLocaleString()}/></Col><Col xs={12} sm={6}>- <Statistic- title={t('stats.boardCount')}+ <Statistic+ title={t('stats.boardCount')}value={selectedAccount.board_count || 0}prefix={<BarsOutlined />}- formatter={(value) => value?.toLocaleString()}+ formatter={value => value?.toLocaleString()}/></Col><Col xs={12} sm={6}>- <Statistic- title={t('stats.pinCount')}+ <Statistic+ title={t('stats.pinCount')}value={selectedAccount.workCount || 0}prefix={<PushpinOutlined />}- formatter={(value) => value?.toLocaleString()}+ formatter={value => value?.toLocaleString()}/></Col><Col xs={12} sm={6}>- <Statistic- title={t('stats.monthlyViews')}+ <Statistic+ title={t('stats.monthlyViews')}value={selectedAccount.readCount || 0}prefix={<BarChartOutlined />}- formatter={(value) => value?.toLocaleString()}+ formatter={value => value?.toLocaleString()}/></Col></Row>@@ -517,32 +541,33 @@ export default function PinterestPage() {<Searchplaceholder={t('actions.search')}value={searchKeyword}- onChange={(e) => setSearchKeyword(e.target.value)}+ onChange={e => setSearchKeyword(e.target.value)}className={styles.searchBox}prefix={<SearchOutlined />}/>- <Button+ <Buttontype="primary"icon={<PlusOutlined />}onClick={() => {- if (activeTab === "boards") {- setBoardModalVisible(true);- } else {- setPinModalVisible(true);- loadBoards(1, 20); // 为创建Pin加载boards+ if (activeTab === 'boards') {+ setBoardModalVisible(true)+ }+ else {+ setPinModalVisible(true)+ loadBoards(1, 20) // 为创建Pin加载boards}}}>- {activeTab === "boards" ? t('actions.createBoard') : t('actions.createPin')}+ {activeTab === 'boards' ? t('actions.createBoard') : t('actions.createPin')}</Button></div>- <Tabs+ <TabsactiveKey={activeTab}onChange={(key) => {- setActiveTab(key);- if (key === "pins") {- loadPins(1, 10);+ setActiveTab(key)+ if (key === 'pins') {+ loadPins(1, 10)}}}items={tabItems}@@ -550,192 +575,204 @@ export default function PinterestPage() {/><div className={styles.tabContent}>- {activeTab === "boards" && (+ {activeTab === 'boards' && (<div className={styles.boardGrid}>- {loading ? (- <div className={styles.loading}>- <Spin size="large" />- </div>- ) : filteredBoards.length === 0 ? (- <Empty- description={t('empty.noBoards')}- image={Empty.PRESENTED_IMAGE_SIMPLE}- />- ) : (- filteredBoards.map(board =>- board && (- <Card- key={board.id}- className={styles.boardCard}- cover={- <div className={styles.boardImage}>- {board.media?.image_cover_url ? (- <img- src={board.media.image_cover_url}- alt={board.name}- />- ) : (- <BarsOutlined />- )}- </div>- }- actions={[- <Button- key="view"- type="link"- icon={<EyeOutlined />}- onClick={() => handleViewBoard(board)}- size="small"- >- {t('actions.view')}- </Button>,- <Popconfirm- key="delete"- title={t('board.deleteConfirm')}- onConfirm={() => handleDeleteBoard(board.id)}- okText={t('confirm.ok')}- cancelText={t('confirm.cancel')}- >- <Button- type="link"- icon={<DeleteOutlined />}- danger- size="small"- >- {t('actions.delete')}- </Button>- </Popconfirm>- ]}- >- <div className={styles.boardCardMeta}>- <Card.Meta- title={board.name}- description={board.description || t('board.noDescription')}- />- <div className={styles.boardBadges}>- <div>- <span className={styles.badgeText}>{t('badges.pins')}</span>- <Badge- count={board.pin_count || 0}- showZero- style={{ backgroundColor: '#e60023' }}- />- </div>- <div>- <span className={styles.badgeText}>{t('badges.followers')}</span>- <Badge- count={board.follower_count || 0}- showZero- style={{ backgroundColor: '#e60023' }}- />- </div>- </div>- </div>- </Card>+ {loading+ ? (+ <div className={styles.loading}>+ <Spin size="large" />+ </div>)- )- )}+ : filteredBoards.length === 0+ ? (+ <Empty+ description={t('empty.noBoards')}+ image={Empty.PRESENTED_IMAGE_SIMPLE}+ />+ )+ : (+ filteredBoards.map(board =>+ board && (+ <Card+ key={board.id}+ className={styles.boardCard}+ cover={(+ <div className={styles.boardImage}>+ {board.media?.image_cover_url+ ? (+ <img+ src={board.media.image_cover_url}+ alt={board.name}+ />+ )+ : (+ <BarsOutlined />+ )}+ </div>+ )}+ actions={[+ <Button+ key="view"+ type="link"+ icon={<EyeOutlined />}+ onClick={() => handleViewBoard(board)}+ size="small"+ >+ {t('actions.view')}+ </Button>,+ <Popconfirm+ key="delete"+ title={t('board.deleteConfirm')}+ onConfirm={() => handleDeleteBoard(board.id)}+ okText={t('confirm.ok')}+ cancelText={t('confirm.cancel')}+ >+ <Button+ type="link"+ icon={<DeleteOutlined />}+ danger+ size="small"+ >+ {t('actions.delete')}+ </Button>+ </Popconfirm>,+ ]}+ >+ <div className={styles.boardCardMeta}>+ <Card.Meta+ title={board.name}+ description={board.description || t('board.noDescription')}+ />+ <div className={styles.boardBadges}>+ <div>+ <span className={styles.badgeText}>{t('badges.pins')}</span>+ <Badge+ count={board.pin_count || 0}+ showZero+ style={{ backgroundColor: '#e60023' }}+ />+ </div>+ <div>+ <span className={styles.badgeText}>{t('badges.followers')}</span>+ <Badge+ count={board.follower_count || 0}+ showZero+ style={{ backgroundColor: '#e60023' }}+ />+ </div>+ </div>+ </div>+ </Card>+ ),+ )+ )}</div>)}- {activeTab === "pins" && (+ {activeTab === 'pins' && (<><div className={styles.pinGrid}>- {loading ? (- <div className={styles.loading}>- <Spin size="large" />- </div>- ) : filteredPins.length === 0 ? (- <Empty- description={t('empty.noPins')}- image={Empty.PRESENTED_IMAGE_SIMPLE}- />- ) : (- filteredPins.map(pin =>- pin && (- <Card- key={pin.id}- className={styles.pinCard}- cover={- <div className={styles.pinImage}>- {pin.media?.images?.["600x"]?.url ? (- <img- src={pin.media.images["600x"].url}- alt={pin.alt_text || pin.title || t('pin.imageAlt')}- />- ) : (- <PictureOutlined />- )}- </div>- }- actions={[- <Button- key="view"- type="link"- icon={<EyeOutlined />}- onClick={() => handleViewPin(pin)}- size="small"- >- {t('actions.view')}- </Button>,- pin.link && (- <Button- key="link"- type="link"- icon={<LinkOutlined />}- href={pin.link}- target="_blank"- size="small"+ {loading+ ? (+ <div className={styles.loading}>+ <Spin size="large" />+ </div>+ )+ : filteredPins.length === 0+ ? (+ <Empty+ description={t('empty.noPins')}+ image={Empty.PRESENTED_IMAGE_SIMPLE}+ />+ )+ : (+ filteredPins.map(pin =>+ pin && (+ <Card+ key={pin.id}+ className={styles.pinCard}+ cover={(+ <div className={styles.pinImage}>+ {pin.media?.images?.['600x']?.url+ ? (+ <img+ src={pin.media.images['600x'].url}+ alt={pin.alt_text || pin.title || t('pin.imageAlt')}+ />+ )+ : (+ <PictureOutlined />+ )}+ </div>+ )}+ actions={[+ <Button+ key="view"+ type="link"+ icon={<EyeOutlined />}+ onClick={() => handleViewPin(pin)}+ size="small"+ >+ {t('actions.view')}+ </Button>,+ pin.link && (+ <Button+ key="link"+ type="link"+ icon={<LinkOutlined />}+ href={pin.link}+ target="_blank"+ size="small"+ >+ {t('actions.link')}+ </Button>+ ),+ <Popconfirm+ key="delete"+ title={t('pin.deleteConfirm')}+ onConfirm={() => handleDeletePin(pin.id)}+ okText={t('confirm.ok')}+ cancelText={t('confirm.cancel')}+ >+ <Button+ type="link"+ icon={<DeleteOutlined />}+ danger+ size="small"+ >+ {t('actions.delete')}+ </Button>+ </Popconfirm>,+ ].filter(Boolean)}>- {t('actions.link')}- </Button>+ <div className={styles.pinCardMeta}>+ <Card.Meta+ title={pin.title}+ description={pin.description || pin.note || t('pin.noDescription')}+ />+ <div className={styles.pinMetadata}>+ {pin.creative_type && (+ <Badge+ text={pin.creative_type}+ size="small"+ style={{ marginRight: 8 }}+ />+ )}+ {pin.is_owner && (+ <Badge+ text={t('badges.owner')}+ color="green"+ size="small"+ />+ )}+ </div>+ </div>+ </Card>),- <Popconfirm- key="delete"- title={t('pin.deleteConfirm')}- onConfirm={() => handleDeletePin(pin.id)}- okText={t('confirm.ok')}- cancelText={t('confirm.cancel')}- >- <Button- type="link"- icon={<DeleteOutlined />}- danger- size="small"- >- {t('actions.delete')}- </Button>- </Popconfirm>- ].filter(Boolean)}- >- <div className={styles.pinCardMeta}>- <Card.Meta- title={pin.title}- description={pin.description || pin.note || t('pin.noDescription')}- />- <div className={styles.pinMetadata}>- {pin.creative_type && (- <Badge- text={pin.creative_type}- size="small"- style={{ marginRight: 8 }}- />- )}- {pin.is_owner && (- <Badge- text={t('badges.owner')}- color="green"- size="small"- />- )}- </div>- </div>- </Card>- )- )- )}+ )+ )}</div>-+{!loading && filteredPins.length > 0 && (<div className={styles.pagination}><Pagination@@ -745,12 +782,11 @@ export default function PinterestPage() {onChange={(page, size) => loadPins(page, size)}showSizeChangershowQuickJumper- showTotal={(total, range) =>- t('pagination.total', {- range: `${range[0]}-${range[1]}`,- total: total- })- }+ showTotal={(total, range) =>+ t('pagination.total', {+ range: `${range[0]}-${range[1]}`,+ total,+ })}/></div>)}@@ -779,17 +815,17 @@ export default function PinterestPage() {><Input placeholder={t('board.namePlaceholder')} /></Form.Item>-+<Form.Itemlabel={t('board.description')}name="description">- <TextArea- placeholder={t('board.descriptionPlaceholder')}+ <TextArea+ placeholder={t('board.descriptionPlaceholder')}rows={3}/></Form.Item>-+<Form.Itemlabel={t('board.privacy')}name="privacy"@@ -814,8 +850,8 @@ export default function PinterestPage() {title={t('pin.createTitle')}open={pinModalVisible}onCancel={() => {- setPinModalVisible(false);- resetImageUpload();+ setPinModalVisible(false)+ resetImageUpload()}}footer={null}className={styles.modal}@@ -832,12 +868,12 @@ export default function PinterestPage() {rules={[{ required: true, message: t('validation.selectBoardRequired') }]}><Select placeholder={t('pin.selectBoardPlaceholder')}>- {boards?.map(board =>+ {boards?.map(board =>board && (<Select.Option key={board.id} value={board.id}>{board.name}</Select.Option>- )+ ),)}</Select></Form.Item>@@ -847,54 +883,63 @@ export default function PinterestPage() {required><div className={styles.uploadArea} onClick={() => !uploading && fileInputRef.current?.click()}>- {uploading ? (- <div className={styles.uploadLoading}>- <Spin size="large" />- <div className={styles.uploadText}>{t('pin.uploading')}</div>- </div>- ) : imagePreview ? (- <div className={styles.uploadSuccess}>- <img- src={imagePreview}- alt="预览"- className={styles.previewImage}- />- <div className={styles.uploadStatus}>- <span className={styles.successText}>{t('pin.uploadSuccess')}</span>- <Button- size="small"- type="link"- onClick={(e) => {- e.stopPropagation();- resetImageUpload();- }}- >- {t('pin.reupload')}- </Button>- </div>- </div>- ) : (- <div>- <UploadOutlined className={styles.uploadIcon} />- <div className={styles.uploadText}>{t('pin.uploadImagePlaceholder')}</div>- <div className={styles.uploadHint}>{t('pin.uploadHint')}</div>- </div>- )}+ {uploading+ ? (+ <div className={styles.uploadLoading}>+ <Spin size="large" />+ <div className={styles.uploadText}>{t('pin.uploading')}</div>+ </div>+ )+ : imagePreview+ ? (+ <div className={styles.uploadSuccess}>+ <img+ src={imagePreview}+ alt="预览"+ className={styles.previewImage}+ />+ <div className={styles.uploadStatus}>+ <span className={styles.successText}>{t('pin.uploadSuccess')}</span>+ <Button+ size="small"+ type="link"+ onClick={(e) => {+ e.stopPropagation()+ resetImageUpload()+ }}+ >+ {t('pin.reupload')}+ </Button>+ </div>+ </div>+ )+ : (+ <div>+ <UploadOutlined className={styles.uploadIcon} />+ <div className={styles.uploadText}>{t('pin.uploadImagePlaceholder')}</div>+ <div className={styles.uploadHint}>{t('pin.uploadHint')}</div>+ </div>+ )}</div><inputref={fileInputRef}type="file"accept="image/*"onChange={handleImageUpload}- style={{ display: "none" }}+ style={{ display: 'none' }}/>{imageUrl && (<div className={styles.urlDisplay}>- <Text type="secondary" ellipsis>{t('pin.ossUrl')}: {imageUrl}</Text>+ <Text type="secondary" ellipsis>+ {t('pin.ossUrl')}+ :+ {' '}+ {imageUrl}+ </Text></div>)}</Form.Item>-+<Form.Itemlabel={t('pin.title')}name="title"@@ -902,32 +947,32 @@ export default function PinterestPage() {><Input placeholder={t('pin.titlePlaceholder')} /></Form.Item>-+<Form.Itemlabel={t('pin.description')}name="description"rules={[{ required: true, message: t('validation.descriptionRequired') }]}>- <TextArea- placeholder={t('pin.descriptionPlaceholder')}+ <TextArea+ placeholder={t('pin.descriptionPlaceholder')}rows={3}/></Form.Item>-+<Form.Itemlabel={t('pin.link')}name="link"><Input placeholder={t('pin.linkPlaceholder')} /></Form.Item>-+<Form.Itemlabel={t('pin.altText')}name="alt_text"><Input placeholder={t('pin.altTextPlaceholder')} /></Form.Item>-+<Form.Itemlabel={t('pin.dominantColor')}name="dominant_color"@@ -967,7 +1012,9 @@ export default function PinterestPage() {</Row><Divider /><Text type="secondary">- {t('board.createTime')}: {new Date(selectedBoard.created_at).toLocaleDateString()}+ {t('board.createTime')}+ :+ {new Date(selectedBoard.created_at).toLocaleDateString()}</Text></div>)}@@ -986,18 +1033,18 @@ export default function PinterestPage() {<Title level={4}>{selectedPin.title}</Title><Text type="secondary">{selectedPin.description || selectedPin.note}</Text><Divider />-+{/* 图片显示 - 优先使用高清图片 */}{selectedPin.media?.images && (- <div style={{ textAlign: "center", marginBottom: 16 }}>- <img+ <div style={{ textAlign: 'center', marginBottom: 16 }}>+ <imgsrc={- selectedPin.media.images["1200x"]?.url ||- selectedPin.media.images["600x"]?.url ||- selectedPin.media.images["400x300"]?.url+ selectedPin.media.images['1200x']?.url+ || selectedPin.media.images['600x']?.url+ || selectedPin.media.images['400x300']?.url}alt={selectedPin.alt_text || selectedPin.title || t('pin.imageAlt')}- style={{ maxWidth: "100%", maxHeight: "400px", borderRadius: "8px" }}+ style={{ maxWidth: '100%', maxHeight: '400px', borderRadius: '8px' }}/></div>)}@@ -1005,30 +1052,46 @@ export default function PinterestPage() {{/* Pin信息 */}<Row gutter={[16, 16]} style={{ marginBottom: 16 }}><Col span={12}>- <Text strong>{t('pin.pinId')}: </Text>+ <Text strong>+ {t('pin.pinId')}+ :+ {' '}+ </Text><Text copyable>{selectedPin.id}</Text></Col><Col span={12}>- <Text strong>{t('pin.boardId')}: </Text>+ <Text strong>+ {t('pin.boardId')}+ :+ {' '}+ </Text><Text copyable>{selectedPin.board_id}</Text></Col>{selectedPin.creative_type && (<Col span={12}>- <Text strong>{t('pin.creativeType')}: </Text>+ <Text strong>+ {t('pin.creativeType')}+ :+ {' '}+ </Text><Badge text={selectedPin.creative_type} /></Col>)}{selectedPin.dominant_color && (<Col span={12}>- <Text strong>{t('pin.dominantColor')}: </Text>- <div style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>- <div- style={{- width: 20,- height: 20,+ <Text strong>+ {t('pin.dominantColor')}+ :+ {' '}+ </Text>+ <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>+ <div+ style={{+ width: 20,+ height: 20,backgroundColor: selectedPin.dominant_color,- borderRadius: "4px",- border: "1px solid #d9d9d9"+ borderRadius: '4px',+ border: '1px solid #d9d9d9',}}/><Text>{selectedPin.dominant_color}</Text>@@ -1040,24 +1103,36 @@ export default function PinterestPage() {{/* 状态信息 */}<Row gutter={[16, 8]} style={{ marginBottom: 16 }}><Col span={8}>- <Text strong>{t('pin.isOwner')}: </Text>- <Badge- color={selectedPin.is_owner ? "green" : "default"}- text={selectedPin.is_owner ? t('badges.yes') : t('badges.no')}+ <Text strong>+ {t('pin.isOwner')}+ :+ {' '}+ </Text>+ <Badge+ color={selectedPin.is_owner ? 'green' : 'default'}+ text={selectedPin.is_owner ? t('badges.yes') : t('badges.no')}/></Col><Col span={8}>- <Text strong>{t('pin.isRemovable')}: </Text>- <Badge- color={selectedPin.is_removable ? "green" : "red"}- text={selectedPin.is_removable ? t('badges.yes') : t('badges.no')}+ <Text strong>+ {t('pin.isRemovable')}+ :+ {' '}+ </Text>+ <Badge+ color={selectedPin.is_removable ? 'green' : 'red'}+ text={selectedPin.is_removable ? t('badges.yes') : t('badges.no')}/></Col><Col span={8}>- <Text strong>{t('pin.isStandard')}: </Text>- <Badge- color={selectedPin.is_standard ? "blue" : "default"}- text={selectedPin.is_standard ? t('badges.yes') : t('badges.no')}+ <Text strong>+ {t('pin.isStandard')}+ :+ {' '}+ </Text>+ <Badge+ color={selectedPin.is_standard ? 'blue' : 'default'}+ text={selectedPin.is_standard ? t('badges.yes') : t('badges.no')}/></Col></Row>@@ -1065,7 +1140,11 @@ export default function PinterestPage() {{/* 链接信息 */}{selectedPin.link && (<div style={{ marginBottom: 16 }}>- <Text strong>{t('pin.link')}: </Text>+ <Text strong>+ {t('pin.link')}+ :+ {' '}+ </Text><a href={selectedPin.link} target="_blank" rel="noopener noreferrer">{selectedPin.link}</a>@@ -1075,7 +1154,11 @@ export default function PinterestPage() {{/* Alt文本 */}{selectedPin.alt_text && (<div style={{ marginBottom: 16 }}>- <Text strong>{t('pin.altText')}: </Text>+ <Text strong>+ {t('pin.altText')}+ :+ {' '}+ </Text><Text>{selectedPin.alt_text}</Text></div>)}@@ -1083,18 +1166,27 @@ export default function PinterestPage() {{/* Board拥有者信息 */}{selectedPin.board_owner && (<div style={{ marginBottom: 16 }}>- <Text strong>{t('pin.boardOwner')}: </Text>- <Text>@{selectedPin.board_owner.username}</Text>+ <Text strong>+ {t('pin.boardOwner')}+ :+ {' '}+ </Text>+ <Text>+ @+ {selectedPin.board_owner.username}+ </Text></div>)}<Divider /><Text type="secondary">- {t('board.createTime')}: {new Date(selectedPin.created_at).toLocaleDateString('zh-CN')}+ {t('board.createTime')}+ :+ {new Date(selectedPin.created_at).toLocaleDateString('zh-CN')}</Text></div>)}</Modal></div>- );-}\ No newline at end of file+ )+}diff --git a/project/web/src/app/[lng]/pinterest/pinterest.module.scss b/project/web/src/app/[lng]/pinterest/pinterest.module.scssindex 0c11b830..d5fac280 100644--- a/project/web/src/app/[lng]/pinterest/pinterest.module.scss+++ b/project/web/src/app/[lng]/pinterest/pinterest.module.scss@@ -15,7 +15,7 @@border-bottom: 1px solid #e0e0e0;flex-wrap: wrap;gap: 20px;-+@media (max-width: 768px) {flex-direction: column;text-align: center;@@ -27,7 +27,7 @@font-weight: bold;color: #e60023;margin: 0;-+@media (max-width: 768px) {font-size: 28px;}@@ -38,7 +38,7 @@gap: 15px;align-items: center;flex-wrap: wrap;-+@media (max-width: 768px) {justify-content: center;width: 100%;@@ -47,7 +47,7 @@.tabs {margin-bottom: 30px;-+:global(.ant-tabs-nav) {margin-bottom: 24px;}@@ -58,7 +58,7 @@border-radius: 12px;padding: 25px;box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);-+@media (max-width: 768px) {padding: 15px;}@@ -66,17 +66,17 @@.statsCard {margin-bottom: 24px;-+:global(.ant-card-body) {padding: 24px;}-+:global(.ant-statistic-title) {color: rgba(0, 0, 0, 0.65);font-size: 14px;margin-bottom: 4px;}-+:global(.ant-statistic-content) {color: rgba(0, 0, 0, 0.85);font-size: 24px;@@ -90,7 +90,7 @@margin-bottom: 24px;align-items: center;flex-wrap: wrap;-+@media (max-width: 768px) {flex-direction: column;align-items: stretch;@@ -102,7 +102,7 @@min-width: 200px;max-width: 320px;flex: 1;-+@media (max-width: 768px) {min-width: unset;max-width: unset;@@ -119,17 +119,17 @@grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));gap: 24px;margin-top: 20px;-+@media (max-width: 1200px) {grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));gap: 20px;}-+@media (max-width: 768px) {grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));gap: 16px;}-+@media (max-width: 480px) {grid-template-columns: 1fr;gap: 16px;@@ -140,28 +140,28 @@height: 100%; // 确保所有卡片高度一致display: flex;flex-direction: column;-+:global(.ant-card-body) {padding: 16px;flex: 1;display: flex;flex-direction: column;}-+:global(.ant-card-actions) {border-top: 1px solid #f0f0f0;background: #fafafa;-+li {margin: 8px 0;-+button {height: auto;padding: 4px 8px;}}}-+&:hover {transform: translateY(-2px);box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);@@ -178,7 +178,7 @@font-size: 48px;color: #bbb;overflow: hidden;-+img {width: 100%;height: 100%;@@ -191,7 +191,7 @@flex: 1;display: flex;flex-direction: column;-+:global(.ant-card-meta-title) {font-size: 16px;font-weight: 600;@@ -200,7 +200,7 @@text-overflow: ellipsis;white-space: nowrap;}-+:global(.ant-card-meta-description) {flex: 1;display: -webkit-box;@@ -220,11 +220,11 @@gap: 16px;align-items: center;margin-top: auto;-+:global(.ant-badge) {display: inline-flex;align-items: center;-+:global(.ant-badge-count) {position: relative;transform: none;@@ -239,7 +239,7 @@border-radius: 10px;}}-+.badgeText {font-size: 14px;color: rgba(0, 0, 0, 0.65);@@ -253,17 +253,17 @@grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));gap: 24px;margin-top: 20px;-+@media (max-width: 1200px) {grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));gap: 20px;}-+@media (max-width: 768px) {grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));gap: 16px;}-+@media (max-width: 480px) {grid-template-columns: repeat(2, 1fr);gap: 12px;@@ -274,21 +274,21 @@height: 100%;display: flex;flex-direction: column;-+:global(.ant-card-body) {padding: 12px;flex: 1;display: flex;flex-direction: column;}-+:global(.ant-card-actions) {border-top: 1px solid #f0f0f0;background: #fafafa;-+li {margin: 6px 0;-+button {height: auto;padding: 4px 8px;@@ -296,7 +296,7 @@}}}-+&:hover {transform: translateY(-2px);box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);@@ -313,7 +313,7 @@font-size: 36px;color: #bbb;overflow: hidden;-+img {width: 100%;height: 100%;@@ -323,7 +323,7 @@.pinCardMeta {flex: 1;-+:global(.ant-card-meta-title) {font-size: 14px;font-weight: 600;@@ -332,7 +332,7 @@text-overflow: ellipsis;white-space: nowrap;}-+:global(.ant-card-meta-description) {display: -webkit-box;-webkit-line-clamp: 2;@@ -350,10 +350,10 @@gap: 8px;flex-wrap: wrap;margin-top: 8px;-+:global(.ant-badge) {font-size: 11px;-+:global(.ant-badge-status-text) {font-size: 11px;color: rgba(0, 0, 0, 0.65);@@ -364,11 +364,11 @@.loading {text-align: center;padding: 60px 20px;-+:global(.ant-spin-lg .ant-spin-dot) {font-size: 32px;}-+@media (max-width: 768px) {padding: 40px 20px;}@@ -380,7 +380,7 @@margin-top: 32px;padding-top: 24px;border-top: 1px solid #f0f0f0;-+:global(.ant-pagination) {@media (max-width: 768px) {:global(.ant-pagination-options) {@@ -395,7 +395,7 @@:global(.ant-modal-content) {border-radius: 12px;}-+:global(.ant-modal-header) {border-radius: 12px 12px 0 0;}@@ -410,7 +410,7 @@transition: all 0.3s;background: #fafafa;position: relative;-+&:hover {border-color: #e60023;background: #fff2f0;@@ -494,7 +494,7 @@border-radius: 6px;cursor: pointer;outline: none;-+&:focus {border-color: #e60023;box-shadow: 0 0 0 2px rgba(230, 0, 35, 0.2);@@ -516,28 +516,28 @@cursor: pointer;outline: none;background: none;-+&::-webkit-color-swatch-wrapper {padding: 0;border: none;border-radius: 5px;}-+&::-webkit-color-swatch {border: none;border-radius: 5px;}-+&::-moz-color-swatch {border: none;border-radius: 5px;}-+&:focus {border-color: #e60023;box-shadow: 0 0 0 2px rgba(230, 0, 35, 0.2);}-+&:hover {border-color: #e60023;}@@ -562,4 +562,4 @@opacity: 1;transform: translateY(0);}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/pricing/page.tsx b/project/web/src/app/[lng]/pricing/page.tsxindex c81ed1c5..b191a8b2 100644--- a/project/web/src/app/[lng]/pricing/page.tsx+++ b/project/web/src/app/[lng]/pricing/page.tsx@@ -1,494 +1,495 @@-"use client";+'use client'-import { useState } from "react";-import { Button, Collapse } from "antd";-import { CheckOutlined } from "@ant-design/icons";-import { useTransClient } from "@/app/i18n/client";-import pricingStyles from "../styles/pricing.module.scss";+import { CheckOutlined } from '@ant-design/icons'+import { Button, Collapse } from 'antd'+import { useState } from 'react'+import { useTransClient } from '@/app/i18n/client'+import pricingStyles from '../styles/pricing.module.scss'/*** 定价页面组件*/export default function PricingPage() {- const { t } = useTransClient('pricing');- const { t: tVip } = useTransClient('vip');+ const { t } = useTransClient('pricing')+ const { t: tVip } = useTransClient('vip')// 直接使用 aaa.md 中的完整数据const fallbackPricingData = [{- model: "gpt-5",- type: "大模型",- duration: "",- resolution: "",- notes: "大模型价格以官方价格为准",- credits: "每百万tokens",- price: "输入 9元,输出 72",- channel: "yun"- },- {- model: "gpt-5-mini",- type: "大模型",- duration: "",- resolution: "",- notes: "",- credits: "",- price: "输入 1.8元,输出 14.4",- channel: "yun"- },- {- model: "gpt-5-nano",- type: "大模型",- duration: "",- resolution: "",- notes: "",- credits: "",- price: "输入 0.36元,输出 2.88",- channel: "yun"- },- {- model: "gemini-2.5-pro",- type: "大模型",- duration: "",- resolution: "支持视频",- notes: "",- credits: "",- price: "输入9元,输出 72",- channel: "yun"- },- {- model: "chatgpt-4o-latest",- type: "大模型",- duration: "",- resolution: "",- notes: "",- credits: "",- price: "输入 36元,输出 108",- channel: "yun"- },- {- model: "gemini-2.5-flash",- type: "大模型",- duration: "",- resolution: "支持视频",- notes: "",- credits: "",- price: "输入 2.16元,输出 18",- channel: "yun"- },- {- model: "qwen-vl-max-latest",- type: "大模型",- duration: "",- resolution: "",- notes: "",- credits: "",- price: "输入1.6元,输出4",- channel: "yun"- },- {- model: "kimi-k2-0711-preview",- type: "大模型",- duration: "",- resolution: "",- notes: "不支持图片",- credits: "",- price: "",- channel: "暂不接入"- },- {- model: "grok-4",- type: "大模型",- duration: "",- resolution: "",- notes: "不支持图片",- credits: "",- price: "",- channel: "暂不接入"- },- {- model: "claude-opus-4-1-20250805-thinking",- type: "大模型",- duration: "",- resolution: "",- notes: "不支持图片,不支持图片的不着急支持",- credits: "",- price: "",- channel: "暂不接入 "- },- {- model: "qwen3-235b-a22b-07-25",- type: "大模型",- duration: "",- resolution: "",- notes: "不支持图片",- credits: "",- price: "",- channel: "暂不接入"- },- {- model: "deepseek-r1-0528",- type: "大模型",- duration: "",- resolution: "",- notes: "不支持图片",- credits: "",- price: "",- channel: "暂不接入"- },- {- model: "claude-sonnet-4-20250514-thinking",- type: "大模型",- duration: "",- resolution: "",- notes: "不支持图片",- credits: "",- price: "",- channel: "暂不接入"- },- {- model: "deepseek-v3-0324",- type: "大模型",- duration: "",- resolution: "",- notes: "不支持图片",- credits: "",- price: "",- channel: "暂不接入"- },- {- model: "gemini-2.5-flash-image",- type: "图片生成",- duration: "",- resolution: "",- notes: "又名nano banana,支持多图像输入",- credits: "1",- price: "0.27",- channel: "yun"- },- {- model: "seedream-3.0",- type: "图片生成",- duration: "",- resolution: "",- notes: "",- credits: "2.6",- price: "0.26",- channel: "官方"- },- {- model: "seededit-3.0",- type: "图片生成",- duration: "",- resolution: "",- notes: "图片编辑,传入图片需要满足以下条件:图片格式:jpeg、png。宽高比(宽/高):在范围 (1/3, 3) 。宽高长度(px) > 14。大小:不超过 10MB。",- credits: "3",- price: "0.3",- channel: "官方"- },- {- model: "gpt-image-1",- type: "图片生成",- duration: "",- resolution: "",- notes: "支持图片编辑",- credits: "1",- price: "low $0.011-0.016, medium $0.042-0.063, high $0.167-0.25",- channel: "yun"- },- {- model: "FLUX.1 Kontext [max]",- type: "图片生成",- duration: "",- resolution: "",- notes: "支持图片编辑",- credits: "1.5",- price: "0.6",- channel: "yun"- },- {- model: "FLUX.1 Kontext [pro]",- type: "图片生成",- duration: "",- resolution: "",- notes: "支持图片编辑",- credits: "1",- price: "0.3",- channel: "yun"- },- {- model: "FLUX.1[dev]",- type: "图片生成",- duration: "",- resolution: "",- notes: "",- credits: "先不上",- price: "0.2",- channel: ""- },- {- model: "Flux 1.1 pro ultra",- type: "图片生成",- duration: "",- resolution: "",- notes: "",- credits: "4.5",- price: "0.45",- channel: "官方"- },- {- model: "Flux1.1 pro",- type: "图片生成",- duration: "",- resolution: "",- notes: "",- credits: "3",- price: "0.3",- channel: "官方"- },- {- model: "midjourney relax",- type: "视频生成",- duration: "5秒",- resolution: "",- notes: "",- credits: "免费",- price: "",- channel: "yun"- },- {- model: "midjourney fast/turbo",- type: "视频生成",- duration: "5秒",- resolution: "",- notes: "",- credits: "4",- price: "",- channel: "yun"- },- {- model: "kling1.5/1.6/2.1",- type: "视频生成",- duration: "5秒",- resolution: "720p",- notes: "",- credits: "20",- price: "2",- channel: "yun"- },- {- model: "kling1.5/1.6/2.1",- type: "视频生成",- duration: "10秒",- resolution: "720p",- notes: "",- credits: "40",- price: "4",- channel: "yun"- },- {- model: "kling1.5/1.6/2.1",- type: "视频生成",- duration: "5秒",- resolution: "1080p",- notes: "",- credits: "35",- price: "3.5",- channel: "yun"- },- {- model: "kling1.5/1.6/2.1",- type: "视频生成",- duration: "10秒",- resolution: "1080p",- notes: "",- credits: "70",- price: "7",- channel: "yun"- },- {- model: "kling1.6多图参考",- type: "视频生成",- duration: "5秒",- resolution: "720p",- notes: "",- credits: "20",- price: "2",- channel: "yun"- },- {- model: "kling1.6多图参考",- type: "视频生成",- duration: "10秒",- resolution: "720p",- notes: "",- credits: "40",- price: "4",- channel: "yun"- },- {- model: "kling1.6多图参考",- type: "视频生成",- duration: "5秒",- resolution: "1080p",- notes: "",- credits: "35",- price: "3.5",- channel: "yun"- },- {- model: "kling1.6多图参考",- type: "视频生成",- duration: "10秒",- resolution: "1080p",- notes: "",- credits: "70",- price: "7",- channel: "yun"- },- {- model: "kling2.1大师",- type: "视频生成",- duration: "5秒",- resolution: "1080p",- notes: "",- credits: "100",- price: "10",- channel: "yun"- },- {- model: "kling2.1大师",- type: "视频生成",- duration: "10秒",- resolution: "1080p",- notes: "",- credits: "200",- price: "20",- channel: "yun"- },- {- model: "wan2.2-plus",- type: "视频生成",- duration: "5秒",- resolution: "480p",- notes: "",- credits: "70",- price: "0.7",- channel: "yun"- },- {- model: "wan2.2-plus",- type: "视频生成",- duration: "5秒",- resolution: "1080p",- notes: "",- credits: "35",- price: "3.5",- channel: "yun"- },- {- model: "wan2.1-turbo(14b)",- type: "视频生成",- duration: "5秒",- resolution: "720p",- notes: "不要使用火山渠道",- credits: "12",- price: "1.2",- channel: "yun"- },- {- model: "wan2.1-plus",- type: "视频生成",- duration: "5秒",- resolution: "720p",- notes: "支持首尾帧",- credits: "35",- price: "3.5",- channel: "yun"- },- {- model: "wanx2.1-vace-plus",- type: "视频生成",- duration: "5秒",- resolution: "720p",- notes: "视频编辑",- credits: "35",- price: "3.5",- channel: "yun"- },- {- model: "seedance-1.0-pro",- type: "视频生成",- duration: "5秒",- resolution: "480p",- notes: "支持10秒",- credits: "7.2",- price: "0.72",- channel: "yun"- },- {- model: "seedance-1.0-pro",- type: "视频生成",- duration: "5秒",- resolution: "720p",- notes: "10秒价格翻倍就行",- credits: "16.4",- price: "1.64",- channel: "yun"- },- {- model: "seedance-1.0-pro",- type: "视频生成",- duration: "5秒",- resolution: "1080p",- notes: "",- credits: "36.7",- price: "3.67",- channel: "yun"- },- {- model: "seedance-1.0-lite",- type: "视频生成",- duration: "5秒",- resolution: "480p",- notes: "支持首尾帧",- credits: "5",- price: "0.5",- channel: "yun"- },- {- model: "seedance-1.0-lite",- type: "视频生成",- duration: "5秒",- resolution: "720p",- notes: "支持10秒",- credits: "11",- price: "1.1",- channel: "yun"- },- {- model: "seedance-1.0-lite",- type: "视频生成",- duration: "5秒",- resolution: "1080p",- notes: "10秒价格翻倍",- credits: "25",- price: "2.5",- channel: "yun"- }- ];+ model: 'gpt-5',+ type: '大模型',+ duration: '',+ resolution: '',+ notes: '大模型价格以官方价格为准',+ credits: '每百万tokens',+ price: '输入 9元,输出 72',+ channel: 'yun',+ },+ {+ model: 'gpt-5-mini',+ type: '大模型',+ duration: '',+ resolution: '',+ notes: '',+ credits: '',+ price: '输入 1.8元,输出 14.4',+ channel: 'yun',+ },+ {+ model: 'gpt-5-nano',+ type: '大模型',+ duration: '',+ resolution: '',+ notes: '',+ credits: '',+ price: '输入 0.36元,输出 2.88',+ channel: 'yun',+ },+ {+ model: 'gemini-2.5-pro',+ type: '大模型',+ duration: '',+ resolution: '支持视频',+ notes: '',+ credits: '',+ price: '输入9元,输出 72',+ channel: 'yun',+ },+ {+ model: 'chatgpt-4o-latest',+ type: '大模型',+ duration: '',+ resolution: '',+ notes: '',+ credits: '',+ price: '输入 36元,输出 108',+ channel: 'yun',+ },+ {+ model: 'gemini-2.5-flash',+ type: '大模型',+ duration: '',+ resolution: '支持视频',+ notes: '',+ credits: '',+ price: '输入 2.16元,输出 18',+ channel: 'yun',+ },+ {+ model: 'qwen-vl-max-latest',+ type: '大模型',+ duration: '',+ resolution: '',+ notes: '',+ credits: '',+ price: '输入1.6元,输出4',+ channel: 'yun',+ },+ {+ model: 'kimi-k2-0711-preview',+ type: '大模型',+ duration: '',+ resolution: '',+ notes: '不支持图片',+ credits: '',+ price: '',+ channel: '暂不接入',+ },+ {+ model: 'grok-4',+ type: '大模型',+ duration: '',+ resolution: '',+ notes: '不支持图片',+ credits: '',+ price: '',+ channel: '暂不接入',+ },+ {+ model: 'claude-opus-4-1-20250805-thinking',+ type: '大模型',+ duration: '',+ resolution: '',+ notes: '不支持图片,不支持图片的不着急支持',+ credits: '',+ price: '',+ channel: '暂不接入 ',+ },+ {+ model: 'qwen3-235b-a22b-07-25',+ type: '大模型',+ duration: '',+ resolution: '',+ notes: '不支持图片',+ credits: '',+ price: '',+ channel: '暂不接入',+ },+ {+ model: 'deepseek-r1-0528',+ type: '大模型',+ duration: '',+ resolution: '',+ notes: '不支持图片',+ credits: '',+ price: '',+ channel: '暂不接入',+ },+ {+ model: 'claude-sonnet-4-20250514-thinking',+ type: '大模型',+ duration: '',+ resolution: '',+ notes: '不支持图片',+ credits: '',+ price: '',+ channel: '暂不接入',+ },+ {+ model: 'deepseek-v3-0324',+ type: '大模型',+ duration: '',+ resolution: '',+ notes: '不支持图片',+ credits: '',+ price: '',+ channel: '暂不接入',+ },+ {+ model: 'gemini-2.5-flash-image',+ type: '图片生成',+ duration: '',+ resolution: '',+ notes: '又名nano banana,支持多图像输入',+ credits: '1',+ price: '0.27',+ channel: 'yun',+ },+ {+ model: 'seedream-3.0',+ type: '图片生成',+ duration: '',+ resolution: '',+ notes: '',+ credits: '2.6',+ price: '0.26',+ channel: '官方',+ },+ {+ model: 'seededit-3.0',+ type: '图片生成',+ duration: '',+ resolution: '',+ notes: '图片编辑,传入图片需要满足以下条件:图片格式:jpeg、png。宽高比(宽/高):在范围 (1/3, 3) 。宽高长度(px) > 14。大小:不超过 10MB。',+ credits: '3',+ price: '0.3',+ channel: '官方',+ },+ {+ model: 'gpt-image-1',+ type: '图片生成',+ duration: '',+ resolution: '',+ notes: '支持图片编辑',+ credits: '1',+ price: 'low $0.011-0.016, medium $0.042-0.063, high $0.167-0.25',+ channel: 'yun',+ },+ {+ model: 'FLUX.1 Kontext [max]',+ type: '图片生成',+ duration: '',+ resolution: '',+ notes: '支持图片编辑',+ credits: '1.5',+ price: '0.6',+ channel: 'yun',+ },+ {+ model: 'FLUX.1 Kontext [pro]',+ type: '图片生成',+ duration: '',+ resolution: '',+ notes: '支持图片编辑',+ credits: '1',+ price: '0.3',+ channel: 'yun',+ },+ {+ model: 'FLUX.1[dev]',+ type: '图片生成',+ duration: '',+ resolution: '',+ notes: '',+ credits: '先不上',+ price: '0.2',+ channel: '',+ },+ {+ model: 'Flux 1.1 pro ultra',+ type: '图片生成',+ duration: '',+ resolution: '',+ notes: '',+ credits: '4.5',+ price: '0.45',+ channel: '官方',+ },+ {+ model: 'Flux1.1 pro',+ type: '图片生成',+ duration: '',+ resolution: '',+ notes: '',+ credits: '3',+ price: '0.3',+ channel: '官方',+ },+ {+ model: 'midjourney relax',+ type: '视频生成',+ duration: '5秒',+ resolution: '',+ notes: '',+ credits: '免费',+ price: '',+ channel: 'yun',+ },+ {+ model: 'midjourney fast/turbo',+ type: '视频生成',+ duration: '5秒',+ resolution: '',+ notes: '',+ credits: '4',+ price: '',+ channel: 'yun',+ },+ {+ model: 'kling1.5/1.6/2.1',+ type: '视频生成',+ duration: '5秒',+ resolution: '720p',+ notes: '',+ credits: '20',+ price: '2',+ channel: 'yun',+ },+ {+ model: 'kling1.5/1.6/2.1',+ type: '视频生成',+ duration: '10秒',+ resolution: '720p',+ notes: '',+ credits: '40',+ price: '4',+ channel: 'yun',+ },+ {+ model: 'kling1.5/1.6/2.1',+ type: '视频生成',+ duration: '5秒',+ resolution: '1080p',+ notes: '',+ credits: '35',+ price: '3.5',+ channel: 'yun',+ },+ {+ model: 'kling1.5/1.6/2.1',+ type: '视频生成',+ duration: '10秒',+ resolution: '1080p',+ notes: '',+ credits: '70',+ price: '7',+ channel: 'yun',+ },+ {+ model: 'kling1.6多图参考',+ type: '视频生成',+ duration: '5秒',+ resolution: '720p',+ notes: '',+ credits: '20',+ price: '2',+ channel: 'yun',+ },+ {+ model: 'kling1.6多图参考',+ type: '视频生成',+ duration: '10秒',+ resolution: '720p',+ notes: '',+ credits: '40',+ price: '4',+ channel: 'yun',+ },+ {+ model: 'kling1.6多图参考',+ type: '视频生成',+ duration: '5秒',+ resolution: '1080p',+ notes: '',+ credits: '35',+ price: '3.5',+ channel: 'yun',+ },+ {+ model: 'kling1.6多图参考',+ type: '视频生成',+ duration: '10秒',+ resolution: '1080p',+ notes: '',+ credits: '70',+ price: '7',+ channel: 'yun',+ },+ {+ model: 'kling2.1大师',+ type: '视频生成',+ duration: '5秒',+ resolution: '1080p',+ notes: '',+ credits: '100',+ price: '10',+ channel: 'yun',+ },+ {+ model: 'kling2.1大师',+ type: '视频生成',+ duration: '10秒',+ resolution: '1080p',+ notes: '',+ credits: '200',+ price: '20',+ channel: 'yun',+ },+ {+ model: 'wan2.2-plus',+ type: '视频生成',+ duration: '5秒',+ resolution: '480p',+ notes: '',+ credits: '70',+ price: '0.7',+ channel: 'yun',+ },+ {+ model: 'wan2.2-plus',+ type: '视频生成',+ duration: '5秒',+ resolution: '1080p',+ notes: '',+ credits: '35',+ price: '3.5',+ channel: 'yun',+ },+ {+ model: 'wan2.1-turbo(14b)',+ type: '视频生成',+ duration: '5秒',+ resolution: '720p',+ notes: '不要使用火山渠道',+ credits: '12',+ price: '1.2',+ channel: 'yun',+ },+ {+ model: 'wan2.1-plus',+ type: '视频生成',+ duration: '5秒',+ resolution: '720p',+ notes: '支持首尾帧',+ credits: '35',+ price: '3.5',+ channel: 'yun',+ },+ {+ model: 'wanx2.1-vace-plus',+ type: '视频生成',+ duration: '5秒',+ resolution: '720p',+ notes: '视频编辑',+ credits: '35',+ price: '3.5',+ channel: 'yun',+ },+ {+ model: 'seedance-1.0-pro',+ type: '视频生成',+ duration: '5秒',+ resolution: '480p',+ notes: '支持10秒',+ credits: '7.2',+ price: '0.72',+ channel: 'yun',+ },+ {+ model: 'seedance-1.0-pro',+ type: '视频生成',+ duration: '5秒',+ resolution: '720p',+ notes: '10秒价格翻倍就行',+ credits: '16.4',+ price: '1.64',+ channel: 'yun',+ },+ {+ model: 'seedance-1.0-pro',+ type: '视频生成',+ duration: '5秒',+ resolution: '1080p',+ notes: '',+ credits: '36.7',+ price: '3.67',+ channel: 'yun',+ },+ {+ model: 'seedance-1.0-lite',+ type: '视频生成',+ duration: '5秒',+ resolution: '480p',+ notes: '支持首尾帧',+ credits: '5',+ price: '0.5',+ channel: 'yun',+ },+ {+ model: 'seedance-1.0-lite',+ type: '视频生成',+ duration: '5秒',+ resolution: '720p',+ notes: '支持10秒',+ credits: '11',+ price: '1.1',+ channel: 'yun',+ },+ {+ model: 'seedance-1.0-lite',+ type: '视频生成',+ duration: '5秒',+ resolution: '1080p',+ notes: '10秒价格翻倍',+ credits: '25',+ price: '2.5',+ channel: 'yun',+ },+ ]// 尝试从 i18n 获取数据,如果失败则使用备选数据const getPricingData = () => {try {- const rows = t('faq.creditDeduction.pricingTable.rows' as any);+ const rows = t('faq.creditDeduction.pricingTable.rows' as any)if (Array.isArray(rows) && rows.length > 0) {- return rows;+ return rows}- } catch (error) {- console.error('Error loading pricing data from i18n:', error);}- return fallbackPricingData;- };+ catch (error) {+ console.error('Error loading pricing data from i18n:', error)+ }+ return fallbackPricingData+ }const plans = [{@@ -510,7 +511,7 @@ export default function PricingPage() {},{name: tVip('modal.plans.monthly.title' as any),- price: '$' + tVip('modal.plans.monthly.price' as any),+ price: `$${tVip('modal.plans.monthly.price' as any)}`,period: tVip('modal.plans.monthly.period' as any),originalPrice: tVip('modal.plans.monthly.originalPrice' as any),subtitle: tVip('modal.plans.monthly.button' as any),@@ -530,38 +531,38 @@ export default function PricingPage() {popular: true,disabled: false,},- ];+ ]const faqItems = [{question: t('faq.paymentMethods.question'),- answer: t('faq.paymentMethods.answer')+ answer: t('faq.paymentMethods.answer'),},{question: t('faq.creditDeduction.question'),- answer: t('faq.creditDeduction.answer')+ answer: t('faq.creditDeduction.answer'),},{question: t('faq.creditExpiry.question'),- answer: t('faq.creditExpiry.answer')+ answer: t('faq.creditExpiry.answer'),},{question: t('faq.moreCredits.question'),- answer: t('faq.moreCredits.answer')+ answer: t('faq.moreCredits.answer'),},{question: t('faq.checkCredits.question'),- answer: t('faq.checkCredits.answer')+ answer: t('faq.checkCredits.answer'),},{question: t('faq.hiddenFees.question'),- answer: t('faq.hiddenFees.answer')+ answer: t('faq.hiddenFees.answer'),},{question: t('faq.refundPolicy.question'),- answer: t('faq.refundPolicy.answer')- }- ];+ answer: t('faq.refundPolicy.answer'),+ },+ ]return (<div className={pricingStyles.pricingPage}>@@ -613,7 +614,7 @@ export default function PricingPage() {className={pricingStyles.ctaButton}onClick={() => {if (!plan.disabled) {- window.location.href = '/accounts?showVip=true';+ window.location.href = '/accounts?showVip=true'}}}>@@ -622,7 +623,9 @@ export default function PricingPage() {{plan.benefitBox && (<div className={pricingStyles.benefitBox}>- <span className={pricingStyles.dot}>•</span> {plan.benefitBox}+ <span className={pricingStyles.dot}>•</span>+ {' '}+ {plan.benefitBox}</div>)}@@ -650,52 +653,52 @@ export default function PricingPage() {{/* FAQ Section */}<div className={pricingStyles.faqSection}>- <h2 className={pricingStyles.faqTitle}>{t('faq.title')}</h2>- <Collapse- className={pricingStyles.faqCollapse}- items={faqItems.map((faq, index) => ({- key: index,- label: faq.question,- children: (- <div>- <p>{faq.answer}</p>- {faq.question === t('faq.creditDeduction.question') && (- <div className={pricingStyles.pricingTableContainer}>- <h4>{t('faq.creditDeduction.pricingTable.title' as any)}</h4>- <div className={pricingStyles.pricingTableWrapper}>- <table className={pricingStyles.pricingTable}>- <thead>- <tr>- <th>{t('faq.creditDeduction.pricingTable.headers.model' as any)}</th>- <th>{t('faq.creditDeduction.pricingTable.headers.type' as any)}</th>- <th>{t('faq.creditDeduction.pricingTable.headers.duration' as any)}</th>- <th>{t('faq.creditDeduction.pricingTable.headers.resolution' as any)}</th>- <th>{t('faq.creditDeduction.pricingTable.headers.credits' as any)}</th>- <th>{t('faq.creditDeduction.pricingTable.headers.price' as any)}</th>+ <h2 className={pricingStyles.faqTitle}>{t('faq.title')}</h2>+ <Collapse+ className={pricingStyles.faqCollapse}+ items={faqItems.map((faq, index) => ({+ key: index,+ label: faq.question,+ children: (+ <div>+ <p>{faq.answer}</p>+ {faq.question === t('faq.creditDeduction.question') && (+ <div className={pricingStyles.pricingTableContainer}>+ <h4>{t('faq.creditDeduction.pricingTable.title' as any)}</h4>+ <div className={pricingStyles.pricingTableWrapper}>+ <table className={pricingStyles.pricingTable}>+ <thead>+ <tr>+ <th>{t('faq.creditDeduction.pricingTable.headers.model' as any)}</th>+ <th>{t('faq.creditDeduction.pricingTable.headers.type' as any)}</th>+ <th>{t('faq.creditDeduction.pricingTable.headers.duration' as any)}</th>+ <th>{t('faq.creditDeduction.pricingTable.headers.resolution' as any)}</th>+ <th>{t('faq.creditDeduction.pricingTable.headers.credits' as any)}</th>+ <th>{t('faq.creditDeduction.pricingTable.headers.price' as any)}</th>+ </tr>+ </thead>+ <tbody>+ {getPricingData().map((row: any, rowIndex: number) => (+ <tr key={rowIndex}>+ <td>{row.model}</td>+ <td>{row.type}</td>+ <td>{row.duration}</td>+ <td>{row.resolution}</td>+ <td>{row.credits}</td>+ <td>{row.price}</td></tr>- </thead>- <tbody>- {getPricingData().map((row: any, rowIndex: number) => (- <tr key={rowIndex}>- <td>{row.model}</td>- <td>{row.type}</td>- <td>{row.duration}</td>- <td>{row.resolution}</td>- <td>{row.credits}</td>- <td>{row.price}</td>- </tr>- ))}- </tbody>- </table>- </div>+ ))}+ </tbody>+ </table></div>- )}- </div>- )- }))}- />- </div>+ </div>+ )}+ </div>+ ),+ }))}+ />+ </div></div></div>- );+ )}diff --git a/project/web/src/app/[lng]/profile/page.tsx b/project/web/src/app/[lng]/profile/page.tsxindex 5ee80a8a..cf02d027 100644--- a/project/web/src/app/[lng]/profile/page.tsx+++ b/project/web/src/app/[lng]/profile/page.tsx@@ -1,160 +1,166 @@-"use client";--import { useEffect, useState, useMemo } from "react";-import { Card, Descriptions, Button, message, Modal, Form, Input, Select } from "antd";-import { CrownOutlined, TrophyOutlined, GiftOutlined, StarOutlined, RocketOutlined, ThunderboltOutlined, HistoryOutlined, DollarOutlined, UserOutlined, GiftFilled, EditOutlined, CopyOutlined } from "@ant-design/icons";-import { useRouter, useSearchParams } from "next/navigation";-import { WalletOutlined } from "@ant-design/icons";-import Image from "next/image";-import { useUserStore } from "@/store/user";-import { getUserInfoApi, updateUserInfoApi, getPointsRecordsApi } from "@/api/apiReq";-import { cancelAccountApi } from "@/api/signIn";-import { createPaymentOrderApi, PaymentType as VipPaymentType } from "@/api/vip";-import { getOrderDetailApi } from "@/api/payment";-import type { Order } from "@/api/types/payment";-import { OrderStatus } from "@/api/types/payment";-import styles from "./profile.module.css";-import { useTransClient } from "@/app/i18n/client";-import PointsRechargeModal from "@/components/modals/PointsRechargeModal";-import VipContentModal from "@/components/modals/VipContentModal";-import PointsDetailModal from "@/components/modals/PointsDetailModal";-import { getChatModels, putUserAiConfigItem } from "@/api/ai";--import plusvip from "@/assets/images/plusvip.png";-import logoHesd from "@/assets/images/logo.png";-+'use client'++import type { Order } from '@/api/types/payment'+import { CopyOutlined, CrownOutlined, DollarOutlined, EditOutlined, GiftFilled, GiftOutlined, HistoryOutlined, RocketOutlined, StarOutlined, ThunderboltOutlined, TrophyOutlined, UserOutlined, WalletOutlined } from '@ant-design/icons'++import { Button, Card, Descriptions, Form, Input, message, Modal, Select } from 'antd'+import Image from 'next/image'+import { useRouter, useSearchParams } from 'next/navigation'+import { useEffect, useMemo, useState } from 'react'+import { getChatModels, putUserAiConfigItem } from '@/api/ai'+import { getPointsRecordsApi, getUserInfoApi, updateUserInfoApi } from '@/api/apiReq'+import { getOrderDetailApi } from '@/api/payment'+import { cancelAccountApi } from '@/api/signIn'+import { OrderStatus } from '@/api/types/payment'+import { createPaymentOrderApi, PaymentType as VipPaymentType } from '@/api/vip'+import { useTransClient } from '@/app/i18n/client'+import logoHesd from '@/assets/images/logo.png'+import plusvip from '@/assets/images/plusvip.png'+import PointsDetailModal from '@/components/modals/PointsDetailModal'+import PointsRechargeModal from '@/components/modals/PointsRechargeModal'+import VipContentModal from '@/components/modals/VipContentModal'++import { useUserStore } from '@/store/user'+import styles from './profile.module.css'export default function ProfilePage() {- const router = useRouter();- const searchParams = useSearchParams();- const { userInfo, setUserInfo, clearLoginStatus, token, lang } = useUserStore();- const { t } = useTransClient('profile');- const [loading, setLoading] = useState(true);- const [isModalOpen, setIsModalOpen] = useState(false);- const [form] = Form.useForm();+ const router = useRouter()+ const searchParams = useSearchParams()+ const { userInfo, setUserInfo, clearLoginStatus, token, lang } = useUserStore()+ const { t } = useTransClient('profile')+ const [loading, setLoading] = useState(true)+ const [isModalOpen, setIsModalOpen] = useState(false)+ const [form] = Form.useForm()// Free trial modal state- const [freeTrialModalVisible, setFreeTrialModalVisible] = useState(false);- const [hasShownFreeTrial, setHasShownFreeTrial] = useState(false);+ const [freeTrialModalVisible, setFreeTrialModalVisible] = useState(false)+ const [hasShownFreeTrial, setHasShownFreeTrial] = useState(false)// Account cancellation related state- const [cancelModalVisible, setCancelModalVisible] = useState(false);- const [cancelForm] = Form.useForm();- const [cancelCode, setCancelCode] = useState('');- const [cancelLoading, setCancelLoading] = useState(false);- const [codeCountdown, setCodeCountdown] = useState(0);+ const [cancelModalVisible, setCancelModalVisible] = useState(false)+ const [cancelForm] = Form.useForm()+ const [cancelCode, setCancelCode] = useState('')+ const [cancelLoading, setCancelLoading] = useState(false)+ const [codeCountdown, setCodeCountdown] = useState(0)// Check if free trial prompt has been shownuseEffect(() => {- const hasShown = localStorage.getItem('freeTrialShown');+ const hasShown = localStorage.getItem('freeTrialShown')if (hasShown) {- setHasShownFreeTrial(true);+ setHasShownFreeTrial(true)}- }, []);+ }, [])// removed URL-driven auto-open; now fully controlled by state// Order detail modal state- const [orderDetailVisible, setOrderDetailVisible] = useState(false);- const [orderDetailLoading, setOrderDetailLoading] = useState(false);- const [currentOrderDetail, setCurrentOrderDetail] = useState<Order | null>(null);+ const [orderDetailVisible, setOrderDetailVisible] = useState(false)+ const [orderDetailLoading, setOrderDetailLoading] = useState(false)+ const [currentOrderDetail, setCurrentOrderDetail] = useState<Order | null>(null)// Points records related state- const [pointsRecords, setPointsRecords] = useState<any[]>([]);- const [pointsLoading, setPointsLoading] = useState(false);+ const [pointsRecords, setPointsRecords] = useState<any[]>([])+ const [pointsLoading, setPointsLoading] = useState(false)const [pointsPagination, setPointsPagination] = useState({current: 1,pageSize: 10,- total: 0- });+ total: 0,+ })// Points recharge related state- const [pointsRechargeVisible, setPointsRechargeVisible] = useState(false);- const [rechargeAmount, setRechargeAmount] = useState(8);- const [rechargeForm] = Form.useForm();- const [isDragging, setIsDragging] = useState(false);- const [paymentOrderId, setPaymentOrderId] = useState<string | null>(null);- const [showPaymentSuccess, setShowPaymentSuccess] = useState(false);- const [pointsDetailVisible, setPointsDetailVisible] = useState(false);- const [vipModalVisible, setVipModalVisible] = useState(false);+ const [pointsRechargeVisible, setPointsRechargeVisible] = useState(false)+ const [rechargeAmount, setRechargeAmount] = useState(8)+ const [rechargeForm] = Form.useForm()+ const [isDragging, setIsDragging] = useState(false)+ const [paymentOrderId, setPaymentOrderId] = useState<string | null>(null)+ const [showPaymentSuccess, setShowPaymentSuccess] = useState(false)+ const [pointsDetailVisible, setPointsDetailVisible] = useState(false)+ const [vipModalVisible, setVipModalVisible] = useState(false)// Default model selection related state- const [chatModels, setChatModels] = useState<any[]>([]);- const [chatModelsLoading, setChatModelsLoading] = useState(false);- const [defaultModel, setDefaultModel] = useState<string | undefined>('gpt-5');- const [showModelDropdown, setShowModelDropdown] = useState(false);+ const [chatModels, setChatModels] = useState<any[]>([])+ const [chatModelsLoading, setChatModelsLoading] = useState(false)+ const [defaultModel, setDefaultModel] = useState<string | undefined>('gpt-5')+ const [showModelDropdown, setShowModelDropdown] = useState(false)// Points record type definitioninterface PointsRecord {- id: string;- userId: string;- amount: number;- balance: number;- type: string;- description: string;- metadata?: any;- createdAt?: string;+ id: string+ userId: string+ amount: number+ balance: number+ type: string+ description: string+ metadata?: any+ createdAt?: string}// Helper function to determine VIP statusconst getVipStatusInfo = (status: string) => {switch (status) {case 'none':- return { isVip: false, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false };+ return { isVip: false, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false }case 'trialing':- return { isVip: true, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false };+ return { isVip: true, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false }case 'monthly_once':- return { isVip: true, isMonthly: true, isYearly: false, isAutoRenew: false, isOnce: true };+ return { isVip: true, isMonthly: true, isYearly: false, isAutoRenew: false, isOnce: true }case 'yearly_once':- return { isVip: true, isMonthly: false, isYearly: true, isAutoRenew: false, isOnce: true };+ return { isVip: true, isMonthly: false, isYearly: true, isAutoRenew: false, isOnce: true }case 'active_monthly':- return { isVip: true, isMonthly: true, isYearly: false, isAutoRenew: true, isOnce: false };+ return { isVip: true, isMonthly: true, isYearly: false, isAutoRenew: true, isOnce: false }case 'active_yearly':- return { isVip: true, isMonthly: false, isYearly: true, isAutoRenew: true, isOnce: false };+ return { isVip: true, isMonthly: false, isYearly: true, isAutoRenew: true, isOnce: false }case 'active_nonrenewing':- return { isVip: true, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false };+ return { isVip: true, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false }case 'expired':- return { isVip: false, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false };+ return { isVip: false, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false }default:- return { isVip: false, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false };+ return { isVip: false, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false }}- };+ }// Get VIP status and expiration timeconst isVip = useMemo(() => {- const vipInfo = userInfo?.vipInfo;- if (!vipInfo) return false;-- const statusInfo = getVipStatusInfo(vipInfo.status);- return statusInfo.isVip && vipInfo.expireTime && new Date(vipInfo.expireTime) > new Date();- }, [userInfo]);-- const vipExpireTime = userInfo?.vipInfo?.expireTime ? new Date(userInfo.vipInfo.expireTime).toLocaleDateString() : '';+ const vipInfo = userInfo?.vipInfo+ if (!vipInfo)+ return false++ const statusInfo = getVipStatusInfo(vipInfo.status)+ return statusInfo.isVip && vipInfo.expireTime && new Date(vipInfo.expireTime) > new Date()+ }, [userInfo])++ const vipExpireTime = userInfo?.vipInfo?.expireTime ? new Date(userInfo.vipInfo.expireTime).toLocaleDateString() : ''// Check if user has never been a VIP member- const hasNeverBeenVip = !userInfo?.vipInfo || userInfo.vipInfo.status === 'none' || userInfo.vipInfo.status === 'expired';+ const hasNeverBeenVip = !userInfo?.vipInfo || userInfo.vipInfo.status === 'none' || userInfo.vipInfo.status === 'expired'// Get VIP status display textconst getVipStatusText = (status: string) => {- const statusInfo = getVipStatusInfo(status);+ const statusInfo = getVipStatusInfo(status)if (statusInfo.isYearly && statusInfo.isAutoRenew) {- return t('yearlyMember');- } else if (statusInfo.isYearly && !statusInfo.isAutoRenew) {- return t('yearlyMember') + ` (${t('memberTypes.oneTime' as any)})`;- } else if (statusInfo.isMonthly && statusInfo.isAutoRenew) {- return t('monthlyMember');- } else if (statusInfo.isMonthly && !statusInfo.isAutoRenew) {- return t('monthlyMember') + ` (${t('memberTypes.oneTime' as any)})`;- } else if (statusInfo.isOnce) {- return statusInfo.isYearly ? t('yearlyMember') + ` (${t('memberTypes.oneTime' as any)})` : t('monthlyMember') + ` (${t('memberTypes.oneTime' as any)})`;- } else if (status === 'trialing') {- return t('monthlyMember') + ` (${t('memberTypes.trial' as any)})`;- } else {- return t('nonMember');+ return t('yearlyMember')+ }+ else if (statusInfo.isYearly && !statusInfo.isAutoRenew) {+ return `${t('yearlyMember')} (${t('memberTypes.oneTime' as any)})`+ }+ else if (statusInfo.isMonthly && statusInfo.isAutoRenew) {+ return t('monthlyMember')+ }+ else if (statusInfo.isMonthly && !statusInfo.isAutoRenew) {+ return `${t('monthlyMember')} (${t('memberTypes.oneTime' as any)})`}- };+ else if (statusInfo.isOnce) {+ return statusInfo.isYearly ? `${t('yearlyMember')} (${t('memberTypes.oneTime' as any)})` : `${t('monthlyMember')} (${t('memberTypes.oneTime' as any)})`+ }+ else if (status === 'trialing') {+ return `${t('monthlyMember')} (${t('memberTypes.trial' as any)})`+ }+ else {+ return t('nonMember')+ }+ }- const vipStatusText = getVipStatusText(userInfo?.vipInfo?.status || 'none');+ const vipStatusText = getVipStatusText(userInfo?.vipInfo?.status || 'none')// VIP benefits dataconst vipBenefits = [@@ -166,374 +172,399 @@ export default function ProfilePage() {{ icon: <HistoryOutlined />, name: t('vipBenefits.unlimitedTime') },{ icon: <ThunderboltOutlined />, name: t('vipBenefits.fastExperience') },{ icon: <RocketOutlined />, name: t('vipBenefits.morePrivileges') },- ];+ ]// Fetch user informationconst fetchUserInfo = async () => {try {- const response: any = await getUserInfoApi();+ const response: any = await getUserInfoApi()if (!response) {- message.error(t('getUserInfoFailed'));- return;+ message.error(t('getUserInfoFailed'))+ return}if (response.code === 0 && response.data) {- setUserInfo(response.data);+ setUserInfo(response.data)// Echo default model (read from aiInfo.agent.defaultModel)try {- const dm = (response.data as any)?.aiInfo?.agent?.defaultModel;+ const dm = (response.data as any)?.aiInfo?.agent?.defaultModelif (typeof dm === 'string' && dm) {- setDefaultModel(dm);+ setDefaultModel(dm)}- } catch {}+ }+ catch {}// Check if free trial prompt needs to be shown- const hasVipInfo = response.data.vipInfo;- const isNeverVip = !hasVipInfo || hasVipInfo.status === 'none' || hasVipInfo.status === 'expired';+ const hasVipInfo = response.data.vipInfo+ const isNeverVip = !hasVipInfo || hasVipInfo.status === 'none' || hasVipInfo.status === 'expired'if (isNeverVip && !hasShownFreeTrial) {// Delay showing modal to ensure page is loadedsetTimeout(() => {- setFreeTrialModalVisible(true);- setHasShownFreeTrial(true);- }, 2000); // Increase delay to let user see page content first+ setFreeTrialModalVisible(true)+ setHasShownFreeTrial(true)+ }, 2000) // Increase delay to let user see page content first}- } else {- message.error(response.message || t('getUserInfoFailed'));}- } catch (error) {- message.error(t('getUserInfoFailed'));- } finally {- setLoading(false);+ else {+ message.error(response.message || t('getUserInfoFailed'))+ }+ }+ catch (error) {+ message.error(t('getUserInfoFailed'))}- };+ finally {+ setLoading(false)+ }+ }// Sync default model when user info updates (only when not currently selected)useEffect(() => {if (!defaultModel) {- const dm = (userInfo as any)?.aiInfo?.agent?.defaultModel;+ const dm = (userInfo as any)?.aiInfo?.agent?.defaultModelif (typeof dm === 'string' && dm) {- setDefaultModel(dm);+ setDefaultModel(dm)}}- }, [userInfo]);+ }, [userInfo])// Load chat modelsconst fetchChatModels = async () => {- setChatModelsLoading(true);+ setChatModelsLoading(true)try {- const res = await getChatModels();+ const res = await getChatModels()if (res?.data && Array.isArray(res.data)) {- setChatModels(res.data);+ setChatModels(res.data)}- } catch (e) {+ }+ catch (e) {// Ignore specific errors, only show prompt- message.error(t('getUserInfoFailed'));- } finally {- setChatModelsLoading(false);+ message.error(t('getUserInfoFailed'))}- };-+ finally {+ setChatModelsLoading(false)+ }+ }// Fetch points records- const fetchPointsRecords = async (params: { page: number; pageSize: number }) => {- setPointsLoading(true);+ const fetchPointsRecords = async (params: { page: number, pageSize: number }) => {+ setPointsLoading(true)try {- const response = await getPointsRecordsApi(params);+ const response = await getPointsRecordsApi(params)if (response?.code === 0 && response.data) {- const paginatedData = response.data;- setPointsRecords(paginatedData.list || []);+ const paginatedData = response.data+ setPointsRecords(paginatedData.list || [])setPointsPagination({current: params.page,pageSize: params.pageSize,- total: paginatedData.total || 0- });- } else {- message.error(response?.message || t('messages.getPointsRecordsFailed' as any));+ total: paginatedData.total || 0,+ })+ }+ else {+ message.error(response?.message || t('messages.getPointsRecordsFailed' as any))}- } catch (error) {- message.error(t('messages.getPointsRecordsFailed' as any));- } finally {- setPointsLoading(false);}- };-+ catch (error) {+ message.error(t('messages.getPointsRecordsFailed' as any))+ }+ finally {+ setPointsLoading(false)+ }+ }// Fetch order detailsconst fetchOrderDetail = async (orderId: string) => {- setOrderDetailLoading(true);+ setOrderDetailLoading(true)try {- const response: any = await getOrderDetailApi(orderId);+ const response: any = await getOrderDetailApi(orderId)if (response?.code === 0 && response.data) {- setCurrentOrderDetail(response.data[0]);- setOrderDetailVisible(true);- } else {- message.error(response?.message || t('getOrderDetailFailed'));+ setCurrentOrderDetail(response.data[0])+ setOrderDetailVisible(true)+ }+ else {+ message.error(response?.message || t('getOrderDetailFailed'))}- } catch (error) {- message.error(t('getOrderDetailFailed'));- } finally {- setOrderDetailLoading(false);}- };+ catch (error) {+ message.error(t('getOrderDetailFailed'))+ }+ finally {+ setOrderDetailLoading(false)+ }+ }/*** Get account cancellation verification code*/const handleGetCancelCode = async () => {try {- const response = await cancelAccountApi.getCancelCode();- console.log('Verification code response:', response);+ const response = await cancelAccountApi.getCancelCode()+ console.log('Verification code response:', response)if (response && response.code === 0) {- setCancelCode(response.data?.code || '');- message.success(t('messages.verificationCodeSent' as any));+ setCancelCode(response.data?.code || '')+ message.success(t('messages.verificationCodeSent' as any))// Start countdown- setCodeCountdown(60);- } else {- message.error(response?.message || t('messages.getVerificationCodeFailed' as any));+ setCodeCountdown(60)}- } catch (error) {- console.error('Get verification code error:', error);- message.error(t('messages.getVerificationCodeFailed' as any));+ else {+ message.error(response?.message || t('messages.getVerificationCodeFailed' as any))+ }+ }+ catch (error) {+ console.error('Get verification code error:', error)+ message.error(t('messages.getVerificationCodeFailed' as any))}- };+ }/*** Handle account cancellation*/const handleCancelAccount = async () => {try {- const values = await cancelForm.validateFields();- setCancelLoading(true);+ const values = await cancelForm.validateFields()+ setCancelLoading(true)- console.log('Send cancellation request, verification code:', values.code);+ console.log('Send cancellation request, verification code:', values.code)const response: any = await cancelAccountApi.cancelAccount({- code: values.code- });-+ code: values.code,+ })if (response && response.code === 0) {- message.success(t('messages.accountCancelledSuccess' as any));- setCancelModalVisible(false);+ message.success(t('messages.accountCancelledSuccess' as any))+ setCancelModalVisible(false)// Clear login status and redirect to login page- clearLoginStatus();- router.push('/login');+ clearLoginStatus()+ router.push('/login')}- } catch (error) {+ }+ catch (error) {- } finally {- setCancelLoading(false);}- };+ finally {+ setCancelLoading(false)+ }+ }/*** Open account cancellation confirmation modal*/const handleOpenCancelModal = () => {- setCancelModalVisible(true);- cancelForm.resetFields();- setCancelCode('');- setCodeCountdown(0);- };+ setCancelModalVisible(true)+ cancelForm.resetFields()+ setCancelCode('')+ setCodeCountdown(0)+ }// Countdown effectuseEffect(() => {- let timer: NodeJS.Timeout;+ let timer: NodeJS.Timeoutif (codeCountdown > 0) {timer = setTimeout(() => {- setCodeCountdown(codeCountdown - 1);- }, 1000);+ setCodeCountdown(codeCountdown - 1)+ }, 1000)}return () => {if (timer) {- clearTimeout(timer);+ clearTimeout(timer)}- };- }, [codeCountdown]);+ }+ }, [codeCountdown])useEffect(() => {if (!token) {- message.error(t('pleaseLoginFirst'));- router.push('/login');- return;+ message.error(t('pleaseLoginFirst'))+ router.push('/login')+ return}- fetchUserInfo();- fetchChatModels();- }, [token, router]);+ fetchUserInfo()+ fetchChatModels()+ }, [token, router])// Clean up slider event listenersuseEffect(() => {return () => {- document.removeEventListener('mousemove', handleSliderMouseMove);- document.removeEventListener('mouseup', handleSliderMouseUp);- };- }, []);+ document.removeEventListener('mousemove', handleSliderMouseMove)+ document.removeEventListener('mouseup', handleSliderMouseUp)+ }+ }, [])const handleLogout = () => {- clearLoginStatus();- message.success(t('logoutSuccess'));- router.push('/login');- };+ clearLoginStatus()+ message.success(t('logoutSuccess'))+ router.push('/login')+ }const handleUpdateName = async (values: { name: string }) => {try {- const response: any = await updateUserInfoApi(values);+ const response: any = await updateUserInfoApi(values)if (!response) {- message.error(t('updateFailed'));- return;+ message.error(t('updateFailed'))+ return}if (response.code === 0 && response.data) {- fetchUserInfo();- message.success(t('updateSuccess'));- setIsModalOpen(false);- } else {- message.error(response.message || t('updateFailed'));+ fetchUserInfo()+ message.success(t('updateSuccess'))+ setIsModalOpen(false)}- } catch (error) {- message.error(t('updateFailed'));+ else {+ message.error(response.message || t('updateFailed'))+ }+ }+ catch (error) {+ message.error(t('updateFailed'))}- };+ }const handleGoToVipPage = () => {- router.push('/vip');- };+ router.push('/vip')+ }// 处理免费会员弹框const handleFreeTrialModalOk = () => {- setFreeTrialModalVisible(false);- localStorage.setItem('freeTrialShown', 'true');- setVipModalVisible(true);- };+ setFreeTrialModalVisible(false)+ localStorage.setItem('freeTrialShown', 'true')+ setVipModalVisible(true)+ }const handleFreeTrialModalCancel = () => {- setFreeTrialModalVisible(false);- localStorage.setItem('freeTrialShown', 'true');- };+ setFreeTrialModalVisible(false)+ localStorage.setItem('freeTrialShown', 'true')+ }// Points related handler functionsconst handleGoToPublish = () => {- router.push('/accounts');+ router.push('/accounts')// Can add logic to trigger publish window here- };+ }const handleGoToVip = () => {- router.push('/vip');- };+ router.push('/vip')+ }const handleRechargePoints = () => {- setPointsRechargeVisible(true);- };+ setPointsRechargeVisible(true)+ }const handleRechargeSubmit = async (values: any) => {try {const response = await createPaymentOrderApi({- returnTo: lang === 'zh-CN' ? "https://aitoearn.ai/zh-CN/profile" : "https://aitoearn.ai/en/profile",+ returnTo: lang === 'zh-CN' ? 'https://aitoearn.ai/zh-CN/profile' : 'https://aitoearn.ai/en/profile',mode: 'payment',payment: VipPaymentType.POINTS,quantity: rechargeAmount, // Purchase quantity of 1000 points packagesmetadata: {- userId: userInfo?.id || ''- }- });+ userId: userInfo?.id || '',+ },+ })if (response?.code === 0 && response.data && typeof response.data === 'object' && 'url' in response.data) {// Save order IDif ('id' in response.data) {- setPaymentOrderId((response.data as any).id);- setShowPaymentSuccess(true);+ setPaymentOrderId((response.data as any).id)+ setShowPaymentSuccess(true)}// Redirect to payment page- window.open((response.data as any).url, '_blank');+ window.open((response.data as any).url, '_blank')// setPointsRechargeVisible(false);- message.success(t('pointsPurchase.redirectingToPayment' as any));- } else {- message.error(response?.message || t('pointsPurchase.createOrderFailed' as any));+ message.success(t('pointsPurchase.redirectingToPayment' as any))}- } catch (error) {- message.error(t('pointsPurchase.createOrderFailed' as any));+ else {+ message.error(response?.message || t('pointsPurchase.createOrderFailed' as any))+ }+ }+ catch (error) {+ message.error(t('pointsPurchase.createOrderFailed' as any))}- };+ }const handleRechargeCancel = () => {- setPointsRechargeVisible(false);- setPaymentOrderId(null);- setShowPaymentSuccess(false);- };+ setPointsRechargeVisible(false)+ setPaymentOrderId(null)+ setShowPaymentSuccess(false)+ }// Handle "I have paid" button clickconst handlePaymentSuccess = async () => {- if (!paymentOrderId) return;+ if (!paymentOrderId)+ returntry {- const response = await getOrderDetailApi(paymentOrderId);+ const response = await getOrderDetailApi(paymentOrderId)if (response?.code === 0 && response.data) {- const order = Array.isArray(response.data) ? response.data[0] : response.data;+ const order = Array.isArray(response.data) ? response.data[0] : response.data// Check order status: 1=payment success, 2=waiting for payment, 3=refunded, 4=cancelledif (order.status === 1) {- message.success(t('pointsPurchase.purchaseSuccess' as any));- setShowPaymentSuccess(false);- setPaymentOrderId(null);- setPointsRechargeVisible(false);+ message.success(t('pointsPurchase.purchaseSuccess' as any))+ setShowPaymentSuccess(false)+ setPaymentOrderId(null)+ setPointsRechargeVisible(false)// Refresh user information- fetchUserInfo();- } else if (order.status === 2) {- message.warning(t('pointsPurchase.paymentPending' as any));- } else if (order.status === 3) {- message.warning(t('pointsPurchase.orderRefunded' as any));- setShowPaymentSuccess(false);- setPaymentOrderId(null);- } else if (order.status === 4) {- message.warning(t('pointsPurchase.orderCancelled' as any));- setShowPaymentSuccess(false);- setPaymentOrderId(null);- } else {- message.warning(t('pointsPurchase.orderUnknown' as any));+ fetchUserInfo()+ }+ else if (order.status === 2) {+ message.warning(t('pointsPurchase.paymentPending' as any))+ }+ else if (order.status === 3) {+ message.warning(t('pointsPurchase.orderRefunded' as any))+ setShowPaymentSuccess(false)+ setPaymentOrderId(null)+ }+ else if (order.status === 4) {+ message.warning(t('pointsPurchase.orderCancelled' as any))+ setShowPaymentSuccess(false)+ setPaymentOrderId(null)}- } else {- message.error(t('pointsPurchase.queryFailed' as any));+ else {+ message.warning(t('pointsPurchase.orderUnknown' as any))+ }+ }+ else {+ message.error(t('pointsPurchase.queryFailed' as any))}- } catch (error) {- message.error(t('pointsPurchase.queryFailed' as any));}- };+ catch (error) {+ message.error(t('pointsPurchase.queryFailed' as any))+ }+ }// Slider drag handlingconst handleSliderMouseDown = (e: React.MouseEvent) => {- setIsDragging(true);- document.addEventListener('mousemove', handleSliderMouseMove);- document.addEventListener('mouseup', handleSliderMouseUp);- };+ setIsDragging(true)+ document.addEventListener('mousemove', handleSliderMouseMove)+ document.addEventListener('mouseup', handleSliderMouseUp)+ }const handleSliderMouseMove = (e: MouseEvent) => {- if (!isDragging) return;-- const sliderTrack = document.querySelector(`.${styles.sliderTrack}`) as HTMLElement;- if (!sliderTrack) return;-- const rect = sliderTrack.getBoundingClientRect();- const x = e.clientX - rect.left;- const percentage = Math.max(0, Math.min(1, x / rect.width));- const newAmount = Math.round(percentage * 49) + 1; // 1-50, only multiples of 1000- setRechargeAmount(newAmount);- };+ if (!isDragging)+ return++ const sliderTrack = document.querySelector(`.${styles.sliderTrack}`) as HTMLElement+ if (!sliderTrack)+ return++ const rect = sliderTrack.getBoundingClientRect()+ const x = e.clientX - rect.left+ const percentage = Math.max(0, Math.min(1, x / rect.width))+ const newAmount = Math.round(percentage * 49) + 1 // 1-50, only multiples of 1000+ setRechargeAmount(newAmount)+ }const handleSliderMouseUp = () => {- setIsDragging(false);- document.removeEventListener('mousemove', handleSliderMouseMove);- document.removeEventListener('mouseup', handleSliderMouseUp);- };+ setIsDragging(false)+ document.removeEventListener('mousemove', handleSliderMouseMove)+ document.removeEventListener('mouseup', handleSliderMouseUp)+ }const handleSliderClick = (e: React.MouseEvent) => {- const sliderTrack = e.currentTarget as HTMLElement;- const rect = sliderTrack.getBoundingClientRect();- const x = e.clientX - rect.left;- const percentage = Math.max(0, Math.min(1, x / rect.width));- const newAmount = Math.round(percentage * 49) + 1; // 1-50- setRechargeAmount(newAmount);- };-+ const sliderTrack = e.currentTarget as HTMLElement+ const rect = sliderTrack.getBoundingClientRect()+ const x = e.clientX - rect.left+ const percentage = Math.max(0, Math.min(1, x / rect.width))+ const newAmount = Math.round(percentage * 49) + 1 // 1-50+ setRechargeAmount(newAmount)+ }// Profile content renderingconst renderProfileContent = () => (@@ -549,7 +580,8 @@ export default function ProfilePage() {gap: 8,color: '#a66ae4',fontWeight: 700,- }}>+ }}+ ><Image src={plusvip} alt="VIP" className={styles.vipBadgeTop} /><span style={{ fontSize: 16 }}>{t('vipHonorText' as any)}</span></div>@@ -575,8 +607,6 @@ export default function ProfilePage() {<div className={styles.scoreRow}>--</div></div>@@ -589,43 +619,67 @@ export default function ProfilePage() {<span className={styles.statsCurrency}>{t('stats.currencyYuan' as any)}</span></div><div className={styles.statsGrid}>- <div className={styles.statsItem} onClick={() => router.push('/income')} >-- <div className={styles.statsLabel}>{t('stats.balance' as any)} <span className={styles.statsValue}> {( userInfo?.income as number / 100 || 0).toFixed(2)} </span> CNY</div>+ <div className={styles.statsItem} onClick={() => router.push('/income')}>++ <div className={styles.statsLabel}>+ {t('stats.balance' as any)}+ {' '}+ <span className={styles.statsValue}>+ {' '}+ {(userInfo?.income as number / 100 || 0).toFixed(2)}+ {' '}+ </span>+ {' '}+ CNY+ </div></div><div className={styles.statsItem} style={{ cursor: 'pointer' }} onClick={() => setPointsDetailVisible(true)}>- <div className={styles.statsLabel}>{t('stats.points' as any)} <span className={styles.statsValue}>{(Math.floor((userInfo?.score as number) || 0)).toFixed(1)} </span> {t('stats.points' as any)}</div>+ <div className={styles.statsLabel}>+ {t('stats.points' as any)}+ {' '}+ <span className={styles.statsValue}>+ {(Math.floor((userInfo?.score as number) || 0)).toFixed(1)}+ {' '}+ </span>+ {' '}+ {t('stats.points' as any)}+ </div></div></div></div>-- <div className={styles.editCard}>- <div style={{display: 'flex', flexDirection: 'column', alignItems: 'flex-start'}}>- <span className={styles.scoreLabel}>{t('username')}</span>- <div className={styles.fieldContainer}>- <span className={styles.fieldInput}>{userInfo?.name || '-'}</span>- <button className={styles.fieldButton} onClick={() => setIsModalOpen(true)}>{t('edit' as any)}</button>- </div>- </div>- <div style={{display: 'flex', flexDirection: 'column', alignItems: 'flex-start'}}>- <span className={styles.scoreLabel}>{t('inviteCode' as any)}</span>- <div className={styles.fieldContainer}>- <span className={styles.fieldInput}>{userInfo?.popularizeCode || '-'}</span>- <button className={styles.fieldButton} onClick={() => {- const code = userInfo?.popularizeCode || '';- if (!code) return;- navigator.clipboard?.writeText(code).then(() => {- message.success(t('copySuccess' as any));- }).catch(() => {- message.success(t('copySuccess' as any));- });- }}>{t('copy' as any)}</button>- </div>- </div>- <div style={{display: 'flex', flexDirection: 'column', alignItems: 'flex-start'}}>+ <div className={styles.editCard}>+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>+ <span className={styles.scoreLabel}>{t('username')}</span>+ <div className={styles.fieldContainer}>+ <span className={styles.fieldInput}>{userInfo?.name || '-'}</span>+ <button className={styles.fieldButton} onClick={() => setIsModalOpen(true)}>{t('edit' as any)}</button>+ </div>+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>+ <span className={styles.scoreLabel}>{t('inviteCode' as any)}</span>+ <div className={styles.fieldContainer}>+ <span className={styles.fieldInput}>{userInfo?.popularizeCode || '-'}</span>+ <button+ className={styles.fieldButton}+ onClick={() => {+ const code = userInfo?.popularizeCode || ''+ if (!code)+ return+ navigator.clipboard?.writeText(code).then(() => {+ message.success(t('copySuccess' as any))+ }).catch(() => {+ message.success(t('copySuccess' as any))+ })+ }}+ >+ {t('copy' as any)}+ </button>+ </div>+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}><span className={styles.scoreLabel}>{t('defaultModel' as any)}</span><div className={styles.fieldContainer}><div style={{ flex: 1, minWidth: 260 }}>@@ -643,7 +697,7 @@ export default function ProfilePage() {borderRadius: 8,border: '1px solid #E5E7EB',background: '#fff',- cursor: 'pointer'+ cursor: 'pointer',}}><div style={{ display: 'flex', alignItems: 'center', gap: 10, overflow: 'hidden', flex: 1 }}>@@ -651,14 +705,14 @@ export default function ProfilePage() {<div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0 }}><div style={{ fontWeight: 600, color: '#111827', fontSize: 14, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{(() => {- const m: any = (chatModels || []).find((x: any) => x.name === defaultModel);- return m?.name || t('pleaseSelect' as any);+ const m: any = (chatModels || []).find((x: any) => x.name === defaultModel)+ return m?.name || t('pleaseSelect' as any)})()}</div><div style={{ color: '#6B7280', fontSize: 12, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', textAlign: 'left', marginTop: 2 }}>{(() => {- const m: any = (chatModels || []).find((x: any) => x.name === defaultModel);- return m?.description || '';+ const m: any = (chatModels || []).find((x: any) => x.name === defaultModel)+ return m?.description || ''})()}</div></div>@@ -670,11 +724,11 @@ export default function ProfilePage() {<div style={{ position: 'absolute', zIndex: 20, top: '110%', left: 0, right: 0, background: '#fff', border: '1px solid #E5E7EB', borderRadius: 10, boxShadow: '0 8px 24px rgba(0,0,0,0.08)' }}><div style={{ maxHeight: 250, overflowY: 'auto', padding: 6 }}>{(chatModels || []).map((m: any) => {- const isActive = defaultModel === m.name;+ const isActive = defaultModel === m.namereturn (<divkey={m.name}- onClick={() => { setDefaultModel(m.name); setShowModelDropdown(false); }}+ onClick={() => { setDefaultModel(m.name); setShowModelDropdown(false) }}style={{display: 'flex',alignItems: 'center',@@ -682,7 +736,7 @@ export default function ProfilePage() {padding: '10px 10px',borderRadius: 8,cursor: 'pointer',- background: isActive ? '#F3E8FF' : 'transparent'+ background: isActive ? '#F3E8FF' : 'transparent',}}><div style={{ width: 28, height: 28, borderRadius: 6, background: '#F3F4F6', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#6B7280', fontSize: 14 }}>AI</div>@@ -697,15 +751,20 @@ export default function ProfilePage() {<span key={tag} style={{ fontSize: 10, background: '#F3F4F6', color: '#6B7280', padding: '2px 6px', borderRadius: 10 }}>{tag}</span>))}</div>- {m?.pricing ? (- <div style={{ color: '#374151', fontSize: 12, marginTop: 0 }}>- <span>prompt {m.pricing.prompt}</span>- {m.pricing.completion ? <span>{` · completion ${m.pricing.completion}`}</span> : null}- </div>- ) : null}+ {m?.pricing+ ? (+ <div style={{ color: '#374151', fontSize: 12, marginTop: 0 }}>+ <span>+ prompt+ {m.pricing.prompt}+ </span>+ {m.pricing.completion ? <span>{` · completion ${m.pricing.completion}`}</span> : null}+ </div>+ )+ : null}</div></div>- );+ )})}</div></div>@@ -716,25 +775,27 @@ export default function ProfilePage() {className={styles.fieldButton}onClick={async () => {if (!defaultModel) {- message.warning(t('pleaseSelect' as any));- return;+ message.warning(t('pleaseSelect' as any))+ return}try {const res = await putUserAiConfigItem({type: 'agent',value: {- defaultModel: defaultModel,+ defaultModel,option: {},},- });+ })if (res && res.code === 0) {- message.success(t('updateSuccess'));- fetchUserInfo();- } else {- message.error(res?.message || t('updateFailed'));+ message.success(t('updateSuccess'))+ fetchUserInfo()+ }+ else {+ message.error(res?.message || t('updateFailed'))}- } catch (e) {- message.error(t('updateFailed'));+ }+ catch (e) {+ message.error(t('updateFailed'))}}}>@@ -742,8 +803,7 @@ export default function ProfilePage() {</button></div></div>- </div>-+ </div>{/* Account status (shown only when abnormal) */}{userInfo?.status !== 1 && (@@ -751,14 +811,15 @@ export default function ProfilePage() {marginTop: 18,marginBottom: 18,color: '#ef4444',- fontSize: 14- }}>- {t('accountStatus')}: {t('disabled')}+ fontSize: 14,+ }}+ >+ {t('accountStatus')}+ :+ {t('disabled')}</div>)}--{/* Bottom account cancellation button */}{/* <div style={{ textAlign: 'center', paddingTop: 24, display:'flex', flexDirection:'column', justifyContent:'center', alignItems:"flex-start" }}><div style={{ display:'flex', flexDirection:'column', justifyContent:'space-between', alignItems:"flex-start", marginBottom: 8 }}>@@ -768,12 +829,10 @@ export default function ProfilePage() {<Button danger onClick={handleOpenCancelModal}>{t('deleteAccount.apply' as any)}</Button></div> */}</div>- );--+ )if (loading) {- return null;+ return null}return (@@ -800,7 +859,7 @@ export default function ProfilePage() {rules={[{ required: true, message: t('pleaseEnterUsername') },{ min: 2, message: t('usernameLengthMin') },- { max: 20, message: t('usernameLengthMax') }+ { max: 20, message: t('usernameLengthMax') },]}><Input placeholder={t('pleaseEnterUsername')} />@@ -829,13 +888,13 @@ export default function ProfilePage() {type="primary"onClick={() => {if (currentOrderDetail?.url) {- window.open(currentOrderDetail.url, '_blank');+ window.open(currentOrderDetail.url, '_blank')}}}>{t('goToPayment')}</Button>- )+ ),]}width={600}loading={orderDetailLoading}@@ -850,20 +909,24 @@ export default function ProfilePage() {<Descriptions.Item label={t('subscriptionMode')}>{currentOrderDetail.mode}</Descriptions.Item><Descriptions.Item label={t('amount')}>{(() => {- const displayAmount = (currentOrderDetail.amount / 100).toFixed(2);- const symbol = currentOrderDetail.currency === 'usd' ? '$' :- currentOrderDetail.currency === 'cny' ? '¥' :- currentOrderDetail.currency?.toUpperCase();- return `${symbol}${displayAmount}`;+ const displayAmount = (currentOrderDetail.amount / 100).toFixed(2)+ const symbol = currentOrderDetail.currency === 'usd'+ ? '$'+ : currentOrderDetail.currency === 'cny'+ ? '¥'+ : currentOrderDetail.currency?.toUpperCase()+ return `${symbol}${displayAmount}`})()}</Descriptions.Item><Descriptions.Item label={t('refundedAmount')}>{(() => {- const displayAmount = (currentOrderDetail.amount_refunded / 100).toFixed(2);- const symbol = currentOrderDetail.currency === 'usd' ? '$' :- currentOrderDetail.currency === 'cny' ? '¥' :- currentOrderDetail.currency?.toUpperCase();- return `${symbol}${displayAmount}`;+ const displayAmount = (currentOrderDetail.amount_refunded / 100).toFixed(2)+ const symbol = currentOrderDetail.currency === 'usd'+ ? '$'+ : currentOrderDetail.currency === 'cny'+ ? '¥'+ : currentOrderDetail.currency?.toUpperCase()+ return `${symbol}${displayAmount}`})()}</Descriptions.Item><Descriptions.Item label={t('status')}>@@ -871,16 +934,16 @@ export default function ProfilePage() {const statusMap = {[OrderStatus.COMPLETE]: { color: 'green', text: t('paymentSuccess') },[OrderStatus.OPEN]: { color: 'orange', text: t('waitingForPayment') },- [OrderStatus.EXPIRED]: { color: 'red', text: t('orderExpired' as any) }- };- const config = statusMap[currentOrderDetail.status] || { color: 'default', text: `状态${currentOrderDetail.status}` };- return <span style={{ color: config.color, fontWeight: 'bold' }}>{config.text}</span>;+ [OrderStatus.EXPIRED]: { color: 'red', text: t('orderExpired' as any) },+ }+ const config = statusMap[currentOrderDetail.status] || { color: 'default', text: `状态${currentOrderDetail.status}` }+ return <span style={{ color: config.color, fontWeight: 'bold' }}>{config.text}</span>})()}</Descriptions.Item><Descriptions.Item label={t('createTime')}>{new Date(currentOrderDetail.created * 1000).toLocaleString()}</Descriptions.Item>- <Descriptions.Item label={ t('expireTime')}>+ <Descriptions.Item label={t('expireTime')}>{new Date(currentOrderDetail.expires_at * 1000).toLocaleString()}</Descriptions.Item><Descriptions.Item label={t('userId')}>{currentOrderDetail.userId}</Descriptions.Item>@@ -909,11 +972,11 @@ export default function ProfilePage() {{/* 免费会员提示弹框 */}<Modal- title={+ title={(<div style={{ textAlign: 'center', fontSize: '18px', fontWeight: 'bold', color: '#C026D2' }}>{t('freeTrial.title')}</div>- }+ )}open={freeTrialModalVisible}onOk={handleFreeTrialModalOk}onCancel={handleFreeTrialModalCancel}@@ -924,14 +987,14 @@ export default function ProfilePage() {backgroundColor: '#C026D2',borderColor: '#C026D2',borderRadius: '8px',- fontWeight: '600'- }+ fontWeight: '600',+ },}}cancelButtonProps={{style: {borderRadius: '8px',- fontWeight: '600'- }+ fontWeight: '600',+ },}}width={500}centered@@ -951,8 +1014,9 @@ export default function ProfilePage() {borderRadius: '12px',padding: '16px',marginBottom: '20px',- border: '1px solid #e2e8f0'- }}>+ border: '1px solid #e2e8f0',+ }}+ ><div style={{ display: 'flex', flex: 1, justifyContent: 'flex-start', marginBottom: '8px' }}><span style={{ color: '#374151', fontSize: '14px', paddingRight: 9 }}>{t('freeTrial.unlimitedAI')}</span><span style={{ color: '#374151', fontSize: '14px', paddingLeft: 9 }}>{t('freeTrial.priorityProcessing')}</span>@@ -961,7 +1025,7 @@ export default function ProfilePage() {<span style={{ color: '#374151', fontSize: '14px', paddingRight: 9 }}>{t('freeTrial.advancedModels')}</span><span style={{ color: '#374151', fontSize: '14px', paddingLeft: 9 }}>{t('freeTrial.dedicatedSupport')}</span></div>-+</div><p style={{ color: '#C026D2', fontSize: '14px', fontWeight: '600' }}>{t('freeTrial.completelyFree')}@@ -1017,7 +1081,6 @@ export default function ProfilePage() {</div></Form.Item>-<Form.Item><div style={{ display: 'flex', gap: '12px', justifyContent: 'flex-end' }}><Button onClick={() => setCancelModalVisible(false)}>@@ -1037,5 +1100,5 @@ export default function ProfilePage() {</div></Modal></div>- );-}\ No newline at end of file+ )+}diff --git a/project/web/src/app/[lng]/profile/profile.module.css b/project/web/src/app/[lng]/profile/profile.module.cssindex 00da8a81..8c253f5e 100644--- a/project/web/src/app/[lng]/profile/profile.module.css+++ b/project/web/src/app/[lng]/profile/profile.module.css@@ -38,7 +38,7 @@/* 个人信息卡片特殊样式 */.personalInfoCard {- background: linear-gradient(135deg, #2B2F36 0%, #4E4C4D 100%);+ background: linear-gradient(135deg, #2b2f36 0%, #4e4c4d 100%);color: #fff;border: 1px solid rgba(255, 255, 255, 0.1);box-shadow: 0 4px 16px rgba(43, 47, 54, 0.2);@@ -135,7 +135,7 @@left: 0;right: 0;bottom: 0;- background: linear-gradient(135deg, #2B2F36 0%, #4E4C4D 100%);+ background: linear-gradient(135deg, #2b2f36 0%, #4e4c4d 100%);z-index: 0;border-radius: 12px;}@@ -294,7 +294,9 @@.activateButton:focus {outline: none;- box-shadow: 0 0 0 3px rgba(166, 106, 228, 0.3), 0 4px 16px rgba(166, 106, 228, 0.3);+ box-shadow:+ 0 0 0 3px rgba(166, 106, 228, 0.3),+ 0 4px 16px rgba(166, 106, 228, 0.3);}.normalUserCallToAction {@@ -313,7 +315,7 @@/* 积分卡片样式 */.pointsCard {- background: linear-gradient(135deg, #2B2F36 0%, #4E4C4D 100%);+ background: linear-gradient(135deg, #2b2f36 0%, #4e4c4d 100%);border-radius: 12px;padding: 20px;margin-bottom: 20px;@@ -336,8 +338,13 @@}@keyframes shimmer {- 0%, 100% { transform: translateX(-100%); }- 50% { transform: translateX(100%); }+ 0%,+ 100% {+ transform: translateX(-100%);+ }+ 50% {+ transform: translateX(100%);+ }}.pointsContent {@@ -604,7 +611,7 @@.container {padding: 12px;}-+.card {margin-bottom: 12px;}@@ -718,24 +725,24 @@font-size: 12px;}- .methodContent p {- font-size: 10px;- }+ .methodContent p {+ font-size: 10px;+ }- .paymentSuccessTip {- padding: 10px;- margin-bottom: 12px;- }+ .paymentSuccessTip {+ padding: 10px;+ margin-bottom: 12px;+ }- .paymentSuccessTip p {- font-size: 12px;- }+ .paymentSuccessTip p {+ font-size: 12px;+ }- .paymentSuccessButton {- font-size: 12px;- padding: 6px 12px;- }- }+ .paymentSuccessButton {+ font-size: 12px;+ padding: 6px 12px;+ }+}/* 积分充值弹窗样式 */.rechargeContent {@@ -743,7 +750,7 @@}.currentPoints {- background: linear-gradient(135deg, #2B2F36 0%, #4E4C4D 100%);+ background: linear-gradient(135deg, #2b2f36 0%, #4e4c4d 100%);border-radius: 12px;padding: 20px;text-align: center;@@ -864,44 +871,44 @@color: #fff;}- .rechargeButton:hover {- transform: translateY(-2px);- box-shadow: 0 4px 12px rgba(106, 90, 205, 0.3);- background: linear-gradient(135deg, #7b68ee 0%, #b76dd9 100%);- }-- /* 支付成功提示样式 */- .paymentSuccessTip {- background: rgba(82, 196, 26, 0.1);- border: 1px solid rgba(82, 196, 26, 0.3);- border-radius: 8px;- padding: 12px;- margin-bottom: 16px;- text-align: center;- margin-top: 20px;- }-- .paymentSuccessTip p {- color: #52c41a;- font-size: 13px;- margin-bottom: 8px;- font-weight: 500;- }-- .paymentSuccessButton {- background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);- border: none;- border-radius: 6px;- font-weight: 600;- transition: all 0.3s ease;- box-shadow: 0 2px 8px rgba(82, 196, 26, 0.3);- }-- .paymentSuccessButton:hover {- background: linear-gradient(135deg, #73d13d 0%, #95de64 100%);- transform: translateY(-1px);- box-shadow: 0 4px 12px rgba(82, 196, 26, 0.4);- }+.rechargeButton:hover {+ transform: translateY(-2px);+ box-shadow: 0 4px 12px rgba(106, 90, 205, 0.3);+ background: linear-gradient(135deg, #7b68ee 0%, #b76dd9 100%);+}++/* 支付成功提示样式 */+.paymentSuccessTip {+ background: rgba(82, 196, 26, 0.1);+ border: 1px solid rgba(82, 196, 26, 0.3);+ border-radius: 8px;+ padding: 12px;+ margin-bottom: 16px;+ text-align: center;+ margin-top: 20px;+}++.paymentSuccessTip p {+ color: #52c41a;+ font-size: 13px;+ margin-bottom: 8px;+ font-weight: 500;+}++.paymentSuccessButton {+ background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);+ border: none;+ border-radius: 6px;+ font-weight: 600;+ transition: all 0.3s ease;+ box-shadow: 0 2px 8px rgba(82, 196, 26, 0.3);+}++.paymentSuccessButton:hover {+ background: linear-gradient(135deg, #73d13d 0%, #95de64 100%);+ transform: translateY(-1px);+ box-shadow: 0 4px 12px rgba(82, 196, 26, 0.4);+}/* 余额卡片样式 */.incomeCard {@@ -909,7 +916,7 @@border-radius: 12px;padding: 20px;margin-bottom: 20px;- color: #2B2F36;+ color: #2b2f36;box-shadow: 0 4px 16px rgba(43, 47, 54, 0.08);position: relative;overflow: hidden;@@ -918,7 +925,7 @@/* 顶部头部信息卡片 */.headerCard {- background-color: #F7F8FA;+ background-color: #f7f8fa;border-radius: 16px;padding: 20px 30px;display: flex;@@ -939,7 +946,7 @@justify-content: center;color: #a66ae4;font-size: 28px;- border: 2px solid rgba(166,106,228,0.35);+ border: 2px solid rgba(166, 106, 228, 0.35);}.nameBlock {@@ -1005,16 +1012,15 @@margin-top: 2px;font-weight: 600;font-size: 18px;- background: #F2F3F5;-+ background: #f2f3f5;}/* 深色统计卡片 */.statsCard {border-radius: 14px;- padding: 18px 0;+ padding: 18px 0;color: #e5e7eb;- border: 1px solid rgba(255,255,255,0.06);+ border: 1px solid rgba(255, 255, 255, 0.06);overflow: hidden;margin-top: 20px;}@@ -1026,20 +1032,20 @@}.statsTitle {- color: #4B6775;+ color: #4b6775;font-size: 14px;}.statsAmount {font-size: 28px;font-weight: 800;- color: #54687B;+ color: #54687b;margin-bottom: 10px;}.statsCurrency {margin-left: 6px;- color: #4B6775;+ color: #4b6775;}.statsGrid {@@ -1059,7 +1065,7 @@padding: 16px 8px 18px 8px;}-.statsItem:hover{+.statsItem:hover {cursor: pointer;}@@ -1071,7 +1077,7 @@.statsLabel {margin-top: 4px;- color: #95887D;+ color: #95887d;font-size: 12px;text-align: left;}@@ -1119,7 +1125,7 @@.incomeTitle {font-size: 18px;font-weight: 600;- color: #2B2F36;+ color: #2b2f36;}.incomeCount {@@ -1202,7 +1208,9 @@.incomeButton:focus {outline: none;- box-shadow: 0 0 0 3px rgba(166, 106, 228, 0.35), 0 2px 8px rgba(166, 106, 228, 0.35);+ box-shadow:+ 0 0 0 3px rgba(166, 106, 228, 0.35),+ 0 2px 8px rgba(166, 106, 228, 0.35);}/* Edit Card 样式 */@@ -1242,7 +1250,7 @@.editCard .fieldInput {flex: 1;- background-color: #F2F3F5;+ background-color: #f2f3f5;padding: 15px 12px;border-radius: 8px;border: none;@@ -1252,12 +1260,12 @@}.editCard .fieldButton {- color: #424A57;+ color: #424a57;cursor: pointer;font-size: 14px;font-weight: 600;padding: 15px 16px;- background-color: #F2F3F5;+ background-color: #f2f3f5;border-radius: 8px;border: none;transition: all 0.2s ease;@@ -1266,4 +1274,4 @@.editCard .fieldButton:hover {background-color: #e2e8f0;color: #8b5cf6;-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/register/page.tsx b/project/web/src/app/[lng]/register/page.tsxindex a46d98a4..caea89c8 100644--- a/project/web/src/app/[lng]/register/page.tsx+++ b/project/web/src/app/[lng]/register/page.tsx@@ -1,23 +1,22 @@-"use client";+'use client'-import { useState } from "react";-import Link from "next/link";-import styles from "./register.module.css";+import Link from 'next/link'+import { useState } from 'react'+import styles from './register.module.css'export default function RegisterPage() {- const [email, setEmail] = useState("");- const [password, setPassword] = useState("");- const [confirmPassword, setConfirmPassword] = useState("");+ const [email, setEmail] = useState('')+ const [password, setPassword] = useState('')+ const [confirmPassword, setConfirmPassword] = useState('')const handleSubmit = (e: React.FormEvent) => {- e.preventDefault();+ e.preventDefault()if (password !== confirmPassword) {- alert("两次输入的密码不一致");- return;+ return}// TODO: 实现注册逻辑- console.log("注册:", { email, password });- };+ console.log('注册:', { email, password })+ }return (<div className={styles.container}>@@ -29,7 +28,7 @@ export default function RegisterPage() {type="email"placeholder="邮箱"value={email}- onChange={(e) => setEmail(e.target.value)}+ onChange={e => setEmail(e.target.value)}className={styles.input}required/>@@ -39,7 +38,7 @@ export default function RegisterPage() {type="password"placeholder="密码"value={password}- onChange={(e) => setPassword(e.target.value)}+ onChange={e => setPassword(e.target.value)}className={styles.input}required/>@@ -49,7 +48,7 @@ export default function RegisterPage() {type="password"placeholder="确认密码"value={confirmPassword}- onChange={(e) => setConfirmPassword(e.target.value)}+ onChange={e => setConfirmPassword(e.target.value)}className={styles.input}required/>@@ -65,5 +64,5 @@ export default function RegisterPage() {</div></div></div>- );-}\ No newline at end of file+ )+}diff --git a/project/web/src/app/[lng]/register/register.module.css b/project/web/src/app/[lng]/register/register.module.cssindex 4ee53b4f..77cd2625 100644--- a/project/web/src/app/[lng]/register/register.module.css+++ b/project/web/src/app/[lng]/register/register.module.css@@ -99,4 +99,4 @@.submitButton {padding: 0.7rem;}-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/styles/difyHome.module.scss b/project/web/src/app/[lng]/styles/difyHome.module.scssindex 4e6ff173..495cb789 100644--- a/project/web/src/app/[lng]/styles/difyHome.module.scss+++ b/project/web/src/app/[lng]/styles/difyHome.module.scss@@ -15,7 +15,7 @@font-size: 14px;cursor: pointer;transition: all 0.3s ease;-+&:hover {background: linear-gradient(90deg, #4338ca 0%, #6d28d9 100%);}@@ -76,7 +76,7 @@display: flex;align-items: center;gap: 10px;-+@media (max-width: 768px) {gap: 8px;}@@ -101,7 +101,7 @@.logoText {margin-left: 15px;-+@media (max-width: 768px) {display: none;}@@ -124,16 +124,16 @@cursor: pointer;font-family: inherit;padding: 0;-+&:hover {color: #4f46e5;}-+&.active {color: #4f46e5;font-weight: 600;position: relative;-+&::after {content: '';position: absolute;@@ -158,13 +158,13 @@font-size: 16px;cursor: pointer;transition: all 0.2s ease;-+&:hover {background: #4338ca;transform: translateY(-1px);box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);}-+@media (max-width: 768px) {display: none;}@@ -181,12 +181,12 @@padding: 8px;border-radius: 4px;transition: all 0.2s ease;-+&:hover {background: #f3f4f6;color: #4f46e5;}-+@media (max-width: 768px) {display: flex;align-items: center;@@ -219,11 +219,11 @@transition: right 0.3s ease-out;display: flex;flex-direction: column;-+&.mobileMenuOpen {right: 0;}-+@media (max-width: 480px) {width: 280px;}@@ -254,7 +254,7 @@padding: 4px;border-radius: 4px;transition: all 0.2s ease;-+&:hover {background: #f3f4f6;color: #374151;@@ -277,13 +277,13 @@font-size: 16px;transition: all 0.2s ease;border-left: 3px solid transparent;-+&:hover {background: #f8fafc;color: #4f46e5;border-left-color: #4f46e5;}-+&.active {background: #f0f4ff;color: #4f46e5;@@ -369,13 +369,13 @@align-items: center;text-align: center;overflow: hidden; // 防止内容溢出-+// 响应式高度调整@media (max-width: 768px) {font-size: 48px;height: 140px;}-+@media (max-width: 480px) {font-size: 36px;height: 110px;@@ -403,10 +403,12 @@}@keyframes cursorBlink {- 0%, 50% {+ 0%,+ 50% {opacity: 1;}- 51%, 100% {+ 51%,+ 100% {opacity: 0;}}@@ -434,7 +436,7 @@align-items: center;gap: 8px;transition: all 0.3s ease;-+&:hover {background: #4338ca;transform: translateY(-2px);@@ -471,7 +473,7 @@text-decoration: underline;margin: 0;transition: color 0.2s ease;-+&:hover {color: #4338ca;}@@ -503,7 +505,7 @@overflow: hidden;position: relative;white-space: nowrap;-+&::before,&::after {content: '';@@ -514,12 +516,12 @@z-index: 2;pointer-events: none;}-+&::before {left: 0;background: linear-gradient(to right, white, transparent);}-+&::after {right: 0;background: linear-gradient(to left, white, transparent);@@ -530,7 +532,7 @@display: flex;animation: scrollLeft 60s linear infinite;width: max-content;-+&:hover {animation-play-state: paused;}@@ -558,7 +560,7 @@min-width: 120px;flex-shrink: 0;white-space: normal;-+&:hover {background: #f8fafc;transform: translateY(-4px);@@ -812,7 +814,7 @@margin-bottom: 8px;color: #1f2937;}-+p {color: #6b7280;line-height: 1.6;@@ -954,7 +956,7 @@padding: 12px 20px;transition: all 0.3s ease;border: 1px solid #4338ca;-+&:hover {background: #4338ca;transform: translateY(-2px);@@ -1062,7 +1064,7 @@justify-content: space-between;align-items: center;margin-bottom: 20px;-+h3 {font-size: 20px;font-weight: 600;@@ -1174,7 +1176,8 @@.qrCodePattern {width: 100%;height: 100%;- background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Crect width='100' height='100' fill='%23000'/%3E%3Crect x='10' y='10' width='20' height='20' fill='%23fff'/%3E%3Crect x='40' y='10' width='20' height='20' fill='%23fff'/%3E%3Crect x='70' y='10' width='20' height='20' fill='%23fff'/%3E%3Crect x='10' y='40' width='20' height='20' fill='%23fff'/%3E%3Crect x='70' y='40' width='20' height='20' fill='%23fff'/%3E%3Crect x='10' y='70' width='20' height='20' fill='%23fff'/%3E%3Crect x='40' y='70' width='20' height='20' fill='%23fff'/%3E%3Crect x='70' y='70' width='20' height='20' fill='%23fff'/%3E%3C/svg%3E") no-repeat center;+ background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'%3E%3Crect width='100' height='100' fill='%23000'/%3E%3Crect x='10' y='10' width='20' height='20' fill='%23fff'/%3E%3Crect x='40' y='10' width='20' height='20' fill='%23fff'/%3E%3Crect x='70' y='10' width='20' height='20' fill='%23fff'/%3E%3Crect x='10' y='40' width='20' height='20' fill='%23fff'/%3E%3Crect x='70' y='40' width='20' height='20' fill='%23fff'/%3E%3Crect x='10' y='70' width='20' height='20' fill='%23fff'/%3E%3Crect x='40' y='70' width='20' height='20' fill='%23fff'/%3E%3Crect x='70' y='70' width='20' height='20' fill='%23fff'/%3E%3C/svg%3E")+ no-repeat center;background-size: contain;}@@ -1185,21 +1188,21 @@gap: 40px;text-align: center;}-+.downloadTitle {font-size: 36px;}-+.phoneFrame {width: 240px;height: 500px;}-+.phoneContainer {flex-direction: column;gap: 20px;}-+.qrCodeImage {width: 100px;height: 100px;@@ -1234,13 +1237,13 @@.productionFeature {text-align: left;-+h3 {font-size: 24px;font-weight: 700;margin-bottom: 12px;}-+p {color: #cbd5e1;line-height: 1.6;@@ -1306,7 +1309,7 @@color: #1f2937;margin-bottom: 8px;}-+.statLabel {color: #6b7280;font-size: 16px;@@ -1334,7 +1337,7 @@font-weight: 700;margin-bottom: 4px;}-+.authorTitle {opacity: 0.8;font-size: 14px;@@ -1352,7 +1355,7 @@color: #6b7280;margin-bottom: 8px;}-+.caseNumber {font-size: 32px;font-weight: 800;@@ -1366,7 +1369,7 @@text-align: center;position: relative;overflow: hidden;-+&::before {content: '';position: absolute;@@ -1432,7 +1435,7 @@gap: 8px;transition: all 0.3s ease;box-shadow: 0 4px 12px rgba(79, 70, 229, 0.3);-+&:hover {background: linear-gradient(135deg, #4338ca 0%, #5b21b6 100%);transform: translateY(-2px);@@ -1453,7 +1456,7 @@z-index: 1000;margin-top: 12px;animation: fadeInUp 0.3s ease-out;-+&::before {content: '';position: absolute;@@ -1507,13 +1510,13 @@padding: 24px;border: 1px solid rgba(255, 255, 255, 0.8);transition: all 0.3s ease;-+&:hover {background: rgba(255, 255, 255, 0.8);transform: translateY(-4px);box-shadow: 0 12px 32px rgba(79, 70, 229, 0.15);}-+.statNumber {font-size: 36px;font-weight: 800;@@ -1521,7 +1524,7 @@margin-bottom: 8px;text-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);}-+.statLabel {color: #475569;font-weight: 500;@@ -1566,7 +1569,7 @@margin-bottom: 24px;letter-spacing: 1px;}-+a {display: block;color: #374151;@@ -1576,12 +1579,12 @@transition: all 0.2s ease;cursor: pointer;position: relative;-+&:hover {color: #1f2937;transform: translateX(4px);}-+&::after {content: '';position: absolute;@@ -1592,7 +1595,7 @@background: #4f46e5;transition: width 0.2s ease;}-+&:hover::after {width: 100%;}@@ -1615,13 +1618,13 @@display: flex;gap: 24px;justify-content: flex-end;-+a {color: #6b7280;text-decoration: none;font-size: 15px;transition: color 0.2s ease;-+&:hover {color: #1f2937;}@@ -1645,7 +1648,11 @@line-height: 1.2;color: #1f2937;margin-bottom: 220px;- font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;+ font-family:+ 'Inter',+ -apple-system,+ BlinkMacSystemFont,+ sans-serif;cursor: pointer;}@@ -1674,48 +1681,48 @@font-size: 12px;color: #6b7280;line-height: 1.4;-+h1 {font-size: 16px;font-weight: 700;color: #1f2937;margin-bottom: 8px;}-+h2 {font-size: 14px;font-weight: 600;color: #374151;margin: 12px 0 6px 0;}-+p {margin: 6px 0;-+strong {font-weight: 600;color: #374151;}}-+ol {margin: 8px 0;padding-left: 20px;-+li {margin: 3px 0;}}-+// 响应式调整@media (max-width: 768px) {padding: 15px 20px;font-size: 11px;-+h1 {font-size: 14px;}-+h2 {font-size: 12px;}@@ -1741,53 +1748,53 @@.heroTitle {font-size: 56px;}-+.buildContent,.connectContent {//grid-template-columns: 1fr;//gap: 40px;}-+.productionFeatures {grid-template-columns: 1fr;}-+.statsGrid {grid-template-columns: repeat(2, 1fr);}-+.footer {margin-top: 40px;}-+.footerContainer {padding: 40px 30px 30px;}-+.footerTop {flex-direction: column;gap: 40px;margin-bottom: 40px;}-+.footerColumns {gap: 60px;}-+.footerInfo {max-width: none;text-align: center;}-+.socialLinks {justify-content: center;}-+.bigText {font-size: 100px;margin-bottom: 30px;}-+.footerCopyright {flex-direction: column;gap: 12px;@@ -1799,24 +1806,24 @@.headerContainer {padding: 0 16px;}-+.nav {display: none;}-+.heroTitle {font-size: 40px;}-+.heroSubtitle {font-size: 18px;}-+.brandContainer {flex-wrap: wrap;justify-content: center;}-+.buildTitle,.connectTitle,.productionTitle,@@ -1824,54 +1831,54 @@.communityTitle {font-size: 32px;}-+.buildContent {min-height: 400px;}-+.statsGrid {grid-template-columns: 1fr;}-+.communityStats {grid-template-columns: 1fr;}-+.footer {margin-top: 30px;}-+.footerContainer {padding: 30px 20px 20px;}-+.footerColumns {flex-direction: column;gap: 30px;}-+.bigText {font-size: 60px;}-+.footerText {font-size: 14px;}-+// 轮播组件移动端适配.imageCarousel {height: 100%;}-+.carouselHint {display: none; // 移动端隐藏滚轮提示}-+.carouselIndicators {right: 15px;gap: 10px;}-+.indicator {width: 10px;height: 10px;@@ -1947,7 +1954,7 @@position: relative;width: 100%;height: 100%;-+// 手机版图片容器特殊样式&.mobileContainer {display: flex;@@ -1990,7 +1997,7 @@// height: 100%;object-fit: cover;transition: transform 0.3s ease;-+.carouselSlide:hover & {transform: scale(1.02);}@@ -2061,12 +2068,12 @@background: rgba(255, 255, 255, 0.5);cursor: pointer;transition: all 0.3s ease;-+&.active {background: #fff;transform: scale(1.3);}-+&:hover {background: rgba(255, 255, 255, 0.8);}@@ -2085,7 +2092,7 @@transition: opacity 0.3s ease;pointer-events: none;z-index: 10;-+.imageCarousel:hover & {opacity: 1;}@@ -2116,11 +2123,11 @@.productionFeature {animation: fadeInUp 1s ease-out;-+&:nth-child(2) {animation-delay: 0.2s;}-+&:nth-child(3) {animation-delay: 0.4s;}@@ -2128,15 +2135,15 @@.statItem {animation: fadeInUp 1s ease-out;-+&:nth-child(2) {animation-delay: 0.1s;}-+&:nth-child(3) {animation-delay: 0.2s;}-+&:nth-child(4) {animation-delay: 0.3s;}@@ -2156,7 +2163,7 @@padding: 40px;position: relative;overflow: hidden;-+&::before {content: '';position: absolute;@@ -2176,7 +2183,11 @@}@keyframes bounce {- 0%, 20%, 50%, 80%, 100% {+ 0%,+ 20%,+ 50%,+ 80%,+ 100% {transform: translateY(0);}40% {@@ -2185,18 +2196,7 @@60% {transform: translateY(-5px);}-}-----------+}.pricingPage {min-height: 100vh;@@ -2214,7 +2214,7 @@display: flex;justify-content: flex-start;margin-bottom: 2rem;-+.backButton {display: flex;align-items: center;@@ -2229,17 +2229,17 @@cursor: pointer;transition: all 0.3s ease;backdrop-filter: blur(10px);-+&:hover {background: rgba(255, 255, 255, 0.2);border-color: rgba(255, 255, 255, 0.3);transform: translateY(-1px);}-+svg {transition: transform 0.2s ease;}-+&:hover svg {transform: translateX(-2px);}diff --git a/project/web/src/app/[lng]/styles/pricing.module.scss b/project/web/src/app/[lng]/styles/pricing.module.scssindex 1ef2b70a..e84dc67a 100644--- a/project/web/src/app/[lng]/styles/pricing.module.scss+++ b/project/web/src/app/[lng]/styles/pricing.module.scss@@ -79,9 +79,15 @@}@keyframes pulse {- 0% { transform: scale(1); }- 50% { transform: scale(1.05); }- 100% { transform: scale(1); }+ 0% {+ transform: scale(1);+ }+ 50% {+ transform: scale(1.05);+ }+ 100% {+ transform: scale(1);+ }}.pricingCards {@@ -99,7 +105,7 @@background: #ffffff;border-radius: 12px;padding: 24px;- box-shadow: 0 1px 2px rgba(0,0,0,0.04);+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);border: 1px solid #eef2f7;transition: all 0.3s ease;position: relative;@@ -115,19 +121,29 @@background: #ffffff;color: #111827;transform: scale(1.02);- box-shadow: 0 0 0 1px rgba(166,106,228,0.4), 0 0 30px rgba(166,106,228,0.25) inset;+ box-shadow:+ 0 0 0 1px rgba(166, 106, 228, 0.4),+ 0 0 30px rgba(166, 106, 228, 0.25) inset;min-height: 530px;}.pricingCard.popular:hover {transform: translateY(-5px) scale(1.02);- box-shadow: 0 0 0 1px rgba(166,106,228,0.5), 0 0 40px rgba(166,106,228,0.3) inset;+ box-shadow:+ 0 0 0 1px rgba(166, 106, 228, 0.5),+ 0 0 40px rgba(166, 106, 228, 0.3) inset;}@keyframes gradientShift {- 0% { background-position: 0% 50%; }- 50% { background-position: 100% 50%; }- 100% { background-position: 0% 50%; }+ 0% {+ background-position: 0% 50%;+ }+ 50% {+ background-position: 100% 50%;+ }+ 100% {+ background-position: 0% 50%;+ }}.popularBadge {@@ -458,29 +474,29 @@.container {padding: 0 1rem;}-+.title {font-size: 2.5rem;}-+.pricingCards {grid-template-columns: 1fr;gap: 1.5rem;}-+.pricingCard {padding: 2rem;}-+.mainFeatures {grid-template-columns: 1fr;gap: 0.8rem;}-+.faqSection {padding: 2rem;}-+.faqTitle {font-size: 2rem;}@@ -551,16 +567,16 @@padding: 1rem;margin-top: 1.5rem;}-+.pricingTableContainer h4 {font-size: 1.125rem;}-+.pricingTable {font-size: 0.8rem;min-width: 600px;}-+.pricingTable th,.pricingTable td {padding: 0.5rem;diff --git a/project/web/src/app/[lng]/tasks/page.tsx b/project/web/src/app/[lng]/tasks/page.tsxindex 0c3af971..a0c38edf 100644--- a/project/web/src/app/[lng]/tasks/page.tsx+++ b/project/web/src/app/[lng]/tasks/page.tsx@@ -1,7 +1,7 @@-"use client";+'use client'-import TaskPageCore from "./taskPageCore";+import TaskPageCore from './taskPageCore'export default function TaskPage() {- return <TaskPageCore />;+ return <TaskPageCore />}diff --git a/project/web/src/app/[lng]/tasks/taskPageCore.tsx b/project/web/src/app/[lng]/tasks/taskPageCore.tsxindex 85a2ff36..1a3d89aa 100644--- a/project/web/src/app/[lng]/tasks/taskPageCore.tsx+++ b/project/web/src/app/[lng]/tasks/taskPageCore.tsx@@ -1,45 +1,48 @@-"use client";--import React, { useState, useEffect } from "react";-import { Tabs, Card, Button, List, Tag, message, Spin, Empty, Modal, Input, Row, Col, Image, Tooltip, Pagination } from "antd";-import { CheckOutlined, ClockCircleOutlined, PlayCircleOutlined, UploadOutlined, EyeOutlined } from "@ant-design/icons";-import { useTransClient } from "@/app/i18n/client";-import { useUserStore } from "@/store/user";-import {- apiGetTaskOpportunityList,+'use client'++import type {+ TaskOpportunity,+ UserTask,+} from '@/api/task'+import type { SocialAccount } from '@/api/types/account.type'+import type { PlatType } from '@/app/config/platConfig'+import { CheckOutlined, ClockCircleOutlined, EyeOutlined, PlayCircleOutlined, UploadOutlined } from '@ant-design/icons'+import { Button, Card, Col, Empty, Image, Input, List, message, Modal, Pagination, Radio, Row, Spin, Steps, Tabs, Tag, Tooltip } from 'antd'++import { useParams, useRouter } from 'next/navigation'+import React, { useEffect, useState } from 'react'+import { getAccountListApi } from '@/api/account'+import { apiGetMaterialList } from '@/api/material'+import { acceptTask, getTaskDetail, submitTask } from '@/api/notification'+import { apiCreatePublish } from '@/api/plat/publish'+import {+ apiAcceptTask,+ apiGetTaskOpportunityList,+ apiGetUserTaskDetail,apiGetUserTaskList,- apiGetUserTaskDetail,- apiAcceptTask,- apiSubmitTask,apiMarkTaskAsViewed,- TaskOpportunity,- UserTask-} from "@/api/task";-import { apiCreatePublish } from "@/api/plat/publish";-import { AccountPlatInfoMap, PlatType } from "@/app/config/platConfig";-import { getOssUrl } from "@/utils/oss";-import { getAppDownloadConfig, getTasksRequiringApp } from "@/app/config/appDownloadConfig";-import DownloadAppModal from "@/components/common/DownloadAppModal";-import { getAccountListApi } from "@/api/account";-import { SocialAccount } from "@/api/types/account.type";-import { getTaskDetail, acceptTask, submitTask } from "@/api/notification";-import { getDays, getUtcDays } from "@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils";-import { Steps, Radio } from "antd";-import http from "@/utils/request";-import { useRouter, useParams } from "next/navigation";-import styles from "./taskPageCore.module.scss";-import { apiGetMaterialList } from "@/api/material";-import DraftSelectionModal from "@/components/PublishDialog/compoents/DraftSelectionModal";--const { TabPane } = Tabs;+ apiSubmitTask,+} from '@/api/task'+import { getDays, getUtcDays } from '@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils'+import { getAppDownloadConfig, getTasksRequiringApp } from '@/app/config/appDownloadConfig'+import { AccountPlatInfoMap } from '@/app/config/platConfig'+import { useTransClient } from '@/app/i18n/client'+import DownloadAppModal from '@/components/common/DownloadAppModal'+import DraftSelectionModal from '@/components/PublishDialog/compoents/DraftSelectionModal'+import { useUserStore } from '@/store/user'+import { getOssUrl } from '@/utils/oss'+import http from '@/utils/request'+import styles from './taskPageCore.module.scss'++const { TabPane } = Tabsexport default function TaskPageCore() {- const { t } = useTransClient("task" as any);- const token = useUserStore((state) => state.token);- const router = useRouter();- const params = useParams();- const lng = params.lng as string;-+ const { t } = useTransClient('task' as any)+ const token = useUserStore(state => state.token)+ const router = useRouter()+ const params = useParams()+ const lng = params.lng as string+// 如果未登录,显示登录提示if (!token) {return (@@ -52,167 +55,176 @@ export default function TaskPageCore() {<Empty description={t('messages.pleaseLoginFirst')} /></div></div>- );+ )}-+// 状态管理- const [activeTab, setActiveTab] = useState("pending"); // pending: 待接受, accepted: 已接受- const [pendingTasks, setPendingTasks] = useState<TaskOpportunity[]>([]);- const [acceptedTasks, setAcceptedTasks] = useState<UserTask[]>([]);- const [loading, setLoading] = useState(false);-+ const [activeTab, setActiveTab] = useState('pending') // pending: 待接受, accepted: 已接受+ const [pendingTasks, setPendingTasks] = useState<TaskOpportunity[]>([])+ const [acceptedTasks, setAcceptedTasks] = useState<UserTask[]>([])+ const [loading, setLoading] = useState(false)+// 分页状态const [pendingPagination, setPendingPagination] = useState({current: 1,pageSize: 15,- total: 0- });+ total: 0,+ })const [acceptedPagination, setAcceptedPagination] = useState({current: 1,pageSize: 15,- total: 0- });- const [selectedTask, setSelectedTask] = useState<TaskOpportunity | null>(null);- const [submitModalVisible, setSubmitModalVisible] = useState(false);- const [submissionUrl, setSubmissionUrl] = useState("");- const [submittingTaskId, setSubmittingTaskId] = useState<string | null>(null);-+ total: 0,+ })+ const [selectedTask, setSelectedTask] = useState<TaskOpportunity | null>(null)+ const [submitModalVisible, setSubmitModalVisible] = useState(false)+ const [submissionUrl, setSubmissionUrl] = useState('')+ const [submittingTaskId, setSubmittingTaskId] = useState<string | null>(null)+// 新增状态- const [accountList, setAccountList] = useState<SocialAccount[]>([]);- const [taskDetailModalVisible, setTaskDetailModalVisible] = useState(false);- const [taskDetail, setTaskDetail] = useState<any>(null);- const [taskDetailLoading, setTaskDetailLoading] = useState(false);- const [currentTaskId, setCurrentTaskId] = useState<string | null>(null);-+ const [accountList, setAccountList] = useState<SocialAccount[]>([])+ const [taskDetailModalVisible, setTaskDetailModalVisible] = useState(false)+ const [taskDetail, setTaskDetail] = useState<any>(null)+ const [taskDetailLoading, setTaskDetailLoading] = useState(false)+ const [currentTaskId, setCurrentTaskId] = useState<string | null>(null)+// 已接受任务详情弹窗状态- const [acceptedTaskDetailModalVisible, setAcceptedTaskDetailModalVisible] = useState(false);- const [acceptedTaskDetail, setAcceptedTaskDetail] = useState<any>(null);- const [acceptedTaskDetailLoading, setAcceptedTaskDetailLoading] = useState(false);-+ const [acceptedTaskDetailModalVisible, setAcceptedTaskDetailModalVisible] = useState(false)+ const [acceptedTaskDetail, setAcceptedTaskDetail] = useState<any>(null)+ const [acceptedTaskDetailLoading, setAcceptedTaskDetailLoading] = useState(false)+// 媒体预览弹窗状态- const [mediaPreviewVisible, setMediaPreviewVisible] = useState(false);+ const [mediaPreviewVisible, setMediaPreviewVisible] = useState(false)const [previewMedia, setPreviewMedia] = useState<{- type: 'video' | 'image';- url: string;- title?: string;- } | null>(null);- const [videoRef, setVideoRef] = useState<HTMLVideoElement | null>(null);-+ type: 'video' | 'image'+ url: string+ title?: string+ } | null>(null)+ const [videoRef, setVideoRef] = useState<HTMLVideoElement | null>(null)+// 任务进度弹窗状态- const [taskProgressVisible, setTaskProgressVisible] = useState(false);+ const [taskProgressVisible, setTaskProgressVisible] = useState(false)const [taskProgress, setTaskProgress] = useState({currentStep: 0,steps: [{ title: t('acceptingTask' as any), status: 'processing' },{ title: t('publishingTask' as any), status: 'wait' },{ title: t('submittingTask' as any), status: 'wait' },- { title: t('taskCompleted' as any), status: 'wait' }- ]- });-+ { title: t('taskCompleted' as any), status: 'wait' },+ ],+ })+// 下载App弹窗状态 - 暂时注释- const [downloadAppVisible, setDownloadAppVisible] = useState(false);+ const [downloadAppVisible, setDownloadAppVisible] = useState(false)const [downloadAppConfig, setDownloadAppConfig] = useState({- platform: "",- appName: "",- downloadUrl: "",- qrCodeUrl: "" as string | undefined- });+ platform: '',+ appName: '',+ downloadUrl: '',+ qrCodeUrl: '' as string | undefined,+ })// 账号选择弹窗状态- const [accountSelectVisible, setAccountSelectVisible] = useState(false);- const [availableAccounts, setAvailableAccounts] = useState<SocialAccount[]>([]);- const [selectedAccount, setSelectedAccount] = useState<SocialAccount | null>(null);-+ const [accountSelectVisible, setAccountSelectVisible] = useState(false)+ const [availableAccounts, setAvailableAccounts] = useState<SocialAccount[]>([])+ const [selectedAccount, setSelectedAccount] = useState<SocialAccount | null>(null)+// 素材列表状态- const [materialList, setMaterialList] = useState<any[]>([]);- const [materialLoading, setMaterialLoading] = useState(false);+ const [materialList, setMaterialList] = useState<any[]>([])+ const [materialLoading, setMaterialLoading] = useState(false)const [materialPagination, setMaterialPagination] = useState({current: 1,pageSize: 9,- total: 0- });-+ total: 0,+ })+// 草稿选择状态- const [draftSource, setDraftSource] = useState<'task' | 'own'>('task'); // 'task': 任务草稿, 'own': 自己的草稿- const [selectedMaterial, setSelectedMaterial] = useState<any>(null); // 选中的任务素材- const [draftModalOpen, setDraftModalOpen] = useState(false); // 自己草稿选择弹窗- const [requiredAccountTypes, setRequiredAccountTypes] = useState<string[]>([]);+ const [draftSource, setDraftSource] = useState<'task' | 'own'>('task') // 'task': 任务草稿, 'own': 自己的草稿+ const [selectedMaterial, setSelectedMaterial] = useState<any>(null) // 选中的任务素材+ const [draftModalOpen, setDraftModalOpen] = useState(false) // 自己草稿选择弹窗+ const [requiredAccountTypes, setRequiredAccountTypes] = useState<string[]>([])// 获取待接受任务列表const fetchPendingTasks = async (page: number = 1, pageSize: number = 15) => {- if (!token) return;-+ if (!token)+ return+try {- setLoading(true);- const response = await apiGetTaskOpportunityList({ page, pageSize });+ setLoading(true)+ const response = await apiGetTaskOpportunityList({ page, pageSize })if (response && response.data) {- setPendingTasks(response.data.list || []);+ setPendingTasks(response.data.list || [])setPendingPagination(prev => ({...prev,current: page,- total: (response.data as any).total || 0- }));- } else {- setPendingTasks([]);+ total: (response.data as any).total || 0,+ }))+ }+ else {+ setPendingTasks([])}- } catch (error) {- console.error("获取待接受任务失败:", error);- message.error(t('messages.getPendingTasksFailed'));- setPendingTasks([]);- } finally {- setLoading(false);}- };+ catch (error) {+ console.error('获取待接受任务失败:', error)+ message.error(t('messages.getPendingTasksFailed'))+ setPendingTasks([])+ }+ finally {+ setLoading(false)+ }+ }// 获取已接受任务列表const fetchAcceptedTasks = async (page: number = 1, pageSize: number = 15) => {- if (!token) return;-+ if (!token)+ return+try {- setLoading(true);- const response = await apiGetUserTaskList({ page, pageSize });+ setLoading(true)+ const response = await apiGetUserTaskList({ page, pageSize })if (response && response.data) {- setAcceptedTasks(response.data.list || []);+ setAcceptedTasks(response.data.list || [])setAcceptedPagination(prev => ({...prev,current: page,- total: (response.data as any).total || 0- }));- } else {- setAcceptedTasks([]);+ total: (response.data as any).total || 0,+ }))}- } catch (error) {- console.error("获取已接受任务失败:", error);- message.error(t('messages.getAcceptedTasksFailed'));- setAcceptedTasks([]);- } finally {- setLoading(false);+ else {+ setAcceptedTasks([])+ }+ }+ catch (error) {+ console.error('获取已接受任务失败:', error)+ message.error(t('messages.getAcceptedTasksFailed'))+ setAcceptedTasks([])+ }+ finally {+ setLoading(false)}- };+ }// 获取账号列表const fetchAccountList = async () => {if (!token) {- setAccountList([]);- return;+ setAccountList([])+ return}try {- const response = await getAccountListApi();+ const response = await getAccountListApi()if (response && response.data) {- setAccountList(response.data || []);+ setAccountList(response.data || [])}- } catch (error) {- console.error("获取账号列表失败:", error);}- };+ catch (error) {+ console.error('获取账号列表失败:', error)+ }+ }// 接受任务- const handleAcceptTask = async (task: any ) => {+ const handleAcceptTask = async (task: any) => {// 暂时简化,直接接受任务- await doAcceptTask(task);-+ await doAcceptTask(task)+// TODO: 添加平台限制检查// if (!task.accountTypes || task.accountTypes.length === 0) {// // 没有账号类型限制,直接接取任务@@ -222,12 +234,12 @@ export default function TaskPageCore() {// // 检查需要App操作的平台// const appRequiredPlatforms = getTasksRequiringApp(task.accountTypes);-+// if (appRequiredPlatforms.length > 0) {// // 有需要App操作的平台,显示第一个平台的下载提示// const firstPlatform = appRequiredPlatforms[0];// const config = getAppDownloadConfig(firstPlatform);-+// if (config) {// setDownloadAppConfig({// platform: config.platform,@@ -239,426 +251,443 @@ export default function TaskPageCore() {// return;// }// }-+// // 其他任务类型正常接取// await doAcceptTask(task);- };+ }// 执行接受任务const doAcceptTask = async (task: TaskOpportunity) => {try {- const response = await apiAcceptTask(task.id);+ const response = await apiAcceptTask(task.id)if (response && response.code === 0) {- message.success(t('messages.acceptTaskSuccess'));+ message.success(t('messages.acceptTaskSuccess'))// 刷新任务列表- fetchPendingTasks();- fetchAcceptedTasks();+ fetchPendingTasks()+ fetchAcceptedTasks()// 切换到已接受任务标签- setActiveTab("accepted");- } else {- message.error(t('messages.acceptTaskFailed'));+ setActiveTab('accepted')+ }+ else {+ message.error(t('messages.acceptTaskFailed'))}- } catch (error) {- message.error(t('messages.acceptTaskFailed'));- console.error("接受任务失败:", error);}- };-+ catch (error) {+ message.error(t('messages.acceptTaskFailed'))+ console.error('接受任务失败:', error)+ }+ }// 获取平台显示名称const getPlatformName = (type: string) => {const platformNames: Record<string, string> = {- 'tiktok': t('platforms.tiktok' as any),- 'youtube': t('platforms.youtube' as any),- 'twitter': t('platforms.twitter' as any),- 'bilibili': t('platforms.bilibili' as any),- 'KWAI': t('platforms.KWAI' as any),- 'douyin': t('platforms.douyin' as any),- 'xhs': t('platforms.xhs' as any),- 'wxSph': t('platforms.wxSph' as any),- 'wxGzh': t('platforms.wxGzh' as any),- 'facebook': t('platforms.facebook' as any),- 'instagram': t('platforms.instagram' as any),- 'threads': t('platforms.threads' as any),- 'pinterest': t('platforms.pinterest' as any),- };- return platformNames[type] || type;- };+ tiktok: t('platforms.tiktok' as any),+ youtube: t('platforms.youtube' as any),+ twitter: t('platforms.twitter' as any),+ bilibili: t('platforms.bilibili' as any),+ KWAI: t('platforms.KWAI' as any),+ douyin: t('platforms.douyin' as any),+ xhs: t('platforms.xhs' as any),+ wxSph: t('platforms.wxSph' as any),+ wxGzh: t('platforms.wxGzh' as any),+ facebook: t('platforms.facebook' as any),+ instagram: t('platforms.instagram' as any),+ threads: t('platforms.threads' as any),+ pinterest: t('platforms.pinterest' as any),+ }+ return platformNames[type] || type+ }// 获取任务类型显示名称const getTaskTypeName = (type: string) => {const taskTypeNames: Record<string, string> = {- 'video': t('taskTypes.video' as any),- 'article': t('taskTypes.article' as any),- 'article2': t('taskTypes.article2' as any),- };- return taskTypeNames[type] || type;- };+ video: t('taskTypes.video' as any),+ article: t('taskTypes.article' as any),+ article2: t('taskTypes.article2' as any),+ }+ return taskTypeNames[type] || type+ }// 格式化时间(相对时间,如"3小时前")const formatTime = (timeString: string) => {- const date = new Date(timeString);- const now = new Date();- const diff = now.getTime() - date.getTime();- const minutes = Math.floor(diff / (1000 * 60));- const hours = Math.floor(diff / (1000 * 60 * 60));- const days = Math.floor(diff / (1000 * 60 * 60 * 24));-- if (minutes < 1) return t('time.justNow' as any);- if (minutes < 60) return t('time.minutesAgo' as any, { minutes });- if (hours < 24) return t('time.hoursAgo' as any, { hours });- if (days < 7) return t('time.daysAgo' as any, { days });- return date.toLocaleDateString();- };+ const date = new Date(timeString)+ const now = new Date()+ const diff = now.getTime() - date.getTime()+ const minutes = Math.floor(diff / (1000 * 60))+ const hours = Math.floor(diff / (1000 * 60 * 60))+ const days = Math.floor(diff / (1000 * 60 * 60 * 24))++ if (minutes < 1)+ return t('time.justNow' as any)+ if (minutes < 60)+ return t('time.minutesAgo' as any, { minutes })+ if (hours < 24)+ return t('time.hoursAgo' as any, { hours })+ if (days < 7)+ return t('time.daysAgo' as any, { days })+ return date.toLocaleDateString()+ }// 格式化绝对时间(显示具体日期时间)const formatAbsoluteTime = (timeString: string) => {- const date = new Date(timeString);- const now = new Date();- const diff = date.getTime() - now.getTime();-+ const date = new Date(timeString)+ const now = new Date()+ const diff = date.getTime() - now.getTime()+// 如果是未来时间,显示剩余时间if (diff > 0) {- const minutes = Math.floor(diff / (1000 * 60));- const hours = Math.floor(diff / (1000 * 60 * 60));- const days = Math.floor(diff / (1000 * 60 * 60 * 24));-- if (minutes < 60) return `${minutes}分钟后`;- if (hours < 24) return `${hours}小时后`;- if (days < 7) return `${days}天后` ;+ const minutes = Math.floor(diff / (1000 * 60))+ const hours = Math.floor(diff / (1000 * 60 * 60))+ const days = Math.floor(diff / (1000 * 60 * 60 * 24))++ if (minutes < 60)+ return `${minutes}分钟后`+ if (hours < 24)+ return `${hours}小时后`+ if (days < 7)+ return `${days}天后`}-+// 显示具体日期时间return date.toLocaleString('zh-CN', {year: 'numeric',month: '2-digit',day: '2-digit',hour: '2-digit',- minute: '2-digit'- });- };+ minute: '2-digit',+ })+ }// 获取任务状态标签const getTaskStatusTag = (status: string) => {- const statusMap: Record<string, { color: string; text: string }> = {- 'pending': { color: 'green', text: '已完成' }, // pending 是已完成- 'doing': { color: 'orange', text: '待完成' }, // doing 是待完成- 'accepted': { color: 'blue', text: t('taskStatus.accepted' as any) },- 'completed': { color: 'green', text: t('taskStatus.completed' as any) },- 'rejected': { color: 'red', text: t('taskStatus.rejected' as any) },- };- return statusMap[status] || { color: 'default', text: status };- };+ const statusMap: Record<string, { color: string, text: string }> = {+ pending: { color: 'green', text: '已完成' }, // pending 是已完成+ doing: { color: 'orange', text: '待完成' }, // doing 是待完成+ accepted: { color: 'blue', text: t('taskStatus.accepted' as any) },+ completed: { color: 'green', text: t('taskStatus.completed' as any) },+ rejected: { color: 'red', text: t('taskStatus.rejected' as any) },+ }+ return statusMap[status] || { color: 'default', text: status }+ }// 根据accountId获取账号信息const getAccountById = (accountId: string): SocialAccount | null => {- return accountList.find(account => account.id === accountId) || null;- };+ return accountList.find(account => account.id === accountId) || null+ }// 获取符合条件的账号const getAvailableAccounts = (accountTypes: string[]): SocialAccount[] => {if (!accountTypes || accountTypes.length === 0) {- return accountList;+ return accountList}- return accountList.filter(account => accountTypes.includes(account.type));- };+ return accountList.filter(account => accountTypes.includes(account.type))+ }// 处理任务操作(接受任务)const handleTaskAction = (task: any) => {// 首先检查任务支持的所有平台是否都需要App操作- const taskPlatforms = task.accountTypes || [];- const appRequiredPlatforms = getTasksRequiringApp(taskPlatforms);-+ const taskPlatforms = task.accountTypes || []+ const appRequiredPlatforms = getTasksRequiringApp(taskPlatforms)+// 如果所有平台都需要App操作,直接显示下载App提示if (appRequiredPlatforms.length > 0 && appRequiredPlatforms.length === taskPlatforms.length) {- const firstPlatform = appRequiredPlatforms[0];- const config = getAppDownloadConfig(firstPlatform);-+ const firstPlatform = appRequiredPlatforms[0]+ const config = getAppDownloadConfig(firstPlatform)+if (config) {setDownloadAppConfig({platform: config.platform,appName: config.appName,downloadUrl: config.downloadUrl,- qrCodeUrl: config.qrCodeUrl- });- setDownloadAppVisible(true);- return;+ qrCodeUrl: config.qrCodeUrl,+ })+ setDownloadAppVisible(true)+ return}}// 如果任务指定了账号,使用指定账号的逻辑if (task.accountId) {- const publishAccount = getAccountById(task.accountId);+ const publishAccount = getAccountById(task.accountId)if (publishAccount) {// 检查发布账号的平台是否需要App操作- const appRequiredPlatforms = getTasksRequiringApp([publishAccount.type]);-+ const appRequiredPlatforms = getTasksRequiringApp([publishAccount.type])+if (appRequiredPlatforms.length > 0) {// 有需要App操作的平台,显示第一个平台的下载提示- const firstPlatform = appRequiredPlatforms[0];- const config = getAppDownloadConfig(firstPlatform);-+ const firstPlatform = appRequiredPlatforms[0]+ const config = getAppDownloadConfig(firstPlatform)+if (config) {setDownloadAppConfig({platform: config.platform,appName: config.appName,downloadUrl: config.downloadUrl,- qrCodeUrl: config.qrCodeUrl- });- setDownloadAppVisible(true);- return;+ qrCodeUrl: config.qrCodeUrl,+ })+ setDownloadAppVisible(true)+ return}}-+// 直接使用指定账号接受任务- handleAcceptTaskFromDetail(task, publishAccount);- return;+ handleAcceptTaskFromDetail(task, publishAccount)+ return}}// 如果没有指定账号,需要用户选择账号- const availableAccounts = getAvailableAccounts(task.accountTypes || []);-+ const availableAccounts = getAvailableAccounts(task.accountTypes || [])+if (availableAccounts.length === 0) {// 没有符合条件的账号,跳转到账户界面并弹出授权界面- setRequiredAccountTypes(task.accountTypes || []);- setTaskDetailModalVisible(false); // 关闭任务详情弹窗- // 关闭消息通知弹窗- message.info(t('accountSelect.redirectingToAccounts' as any));-+ setRequiredAccountTypes(task.accountTypes || [])+ setTaskDetailModalVisible(false) // 关闭任务详情弹窗+ // 关闭消息通知弹窗+ message.info(t('accountSelect.redirectingToAccounts' as any))+// 构建跳转URL,包含需要的平台类型参数- const accountTypes = task.accountTypes || [];- const platformParam = accountTypes.length > 0 ? accountTypes[0] : undefined;- const accountsUrl = platformParam+ const accountTypes = task.accountTypes || []+ const platformParam = accountTypes.length > 0 ? accountTypes[0] : undefined+ const accountsUrl = platformParam? `/${lng}/accounts?platform=${platformParam}`- : `/${lng}/accounts`;-- router.push(accountsUrl); // 跳转到账户界面并自动打开添加账号弹窗- return;+ : `/${lng}/accounts`++ router.push(accountsUrl) // 跳转到账户界面并自动打开添加账号弹窗+ return}if (availableAccounts.length === 1) {// 只有一个符合条件的账号,直接使用- const account = availableAccounts[0];-+ const account = availableAccounts[0]+// 检查是否需要App操作- const appRequiredPlatforms = getTasksRequiringApp([account.type]);+ const appRequiredPlatforms = getTasksRequiringApp([account.type])if (appRequiredPlatforms.length > 0) {- const firstPlatform = appRequiredPlatforms[0];- const config = getAppDownloadConfig(firstPlatform);-+ const firstPlatform = appRequiredPlatforms[0]+ const config = getAppDownloadConfig(firstPlatform)+if (config) {setDownloadAppConfig({platform: config.platform,appName: config.appName,downloadUrl: config.downloadUrl,- qrCodeUrl: config.qrCodeUrl- });- setDownloadAppVisible(true);- return;+ qrCodeUrl: config.qrCodeUrl,+ })+ setDownloadAppVisible(true)+ return}}-+// 直接使用这个账号接受任务- handleAcceptTaskFromDetail(task, account);- return;+ handleAcceptTaskFromDetail(task, account)+ return}-+// 多个符合条件的账号,显示选择弹窗- setAvailableAccounts(availableAccounts);- setAccountSelectVisible(true);- };+ setAvailableAccounts(availableAccounts)+ setAccountSelectVisible(true)+ }// 处理账号选择const handleAccountSelect = (account: SocialAccount) => {- setSelectedAccount(account);- setAccountSelectVisible(false);-+ setSelectedAccount(account)+ setAccountSelectVisible(false)+// 检查是否需要App操作- const appRequiredPlatforms = getTasksRequiringApp([account.type]);+ const appRequiredPlatforms = getTasksRequiringApp([account.type])if (appRequiredPlatforms.length > 0) {- const firstPlatform = appRequiredPlatforms[0];- const config = getAppDownloadConfig(firstPlatform);-+ const firstPlatform = appRequiredPlatforms[0]+ const config = getAppDownloadConfig(firstPlatform)+if (config) {setDownloadAppConfig({platform: config.platform,appName: config.appName,downloadUrl: config.downloadUrl,- qrCodeUrl: config.qrCodeUrl- });- setDownloadAppVisible(true);- return;+ qrCodeUrl: config.qrCodeUrl,+ })+ setDownloadAppVisible(true)+ return}}-+// 使用选择的账号接受任务if (taskDetail) {- handleAcceptTaskFromDetail(taskDetail, account);+ handleAcceptTaskFromDetail(taskDetail, account)}- };+ }// 检查是否有新添加的符合条件账号const checkForNewAccounts = () => {if (requiredAccountTypes.length > 0 && taskDetail) {- const newAvailableAccounts = getAvailableAccounts(requiredAccountTypes);-+ const newAvailableAccounts = getAvailableAccounts(requiredAccountTypes)+if (newAvailableAccounts.length > 0) {// 有新账号了,清除需求状态- setRequiredAccountTypes([]);-+ setRequiredAccountTypes([])+if (newAvailableAccounts.length === 1) {// 只有一个新账号,直接使用- const account = newAvailableAccounts[0];-+ const account = newAvailableAccounts[0]+// 检查是否需要App操作- const appRequiredPlatforms = getTasksRequiringApp([account.type]);+ const appRequiredPlatforms = getTasksRequiringApp([account.type])if (appRequiredPlatforms.length > 0) {- const firstPlatform = appRequiredPlatforms[0];- const config = getAppDownloadConfig(firstPlatform);-+ const firstPlatform = appRequiredPlatforms[0]+ const config = getAppDownloadConfig(firstPlatform)+if (config) {setDownloadAppConfig({platform: config.platform,appName: config.appName,downloadUrl: config.downloadUrl,- qrCodeUrl: config.qrCodeUrl- });- setDownloadAppVisible(true);- return;+ qrCodeUrl: config.qrCodeUrl,+ })+ setDownloadAppVisible(true)+ return}}-+// 直接使用这个账号接受任务- handleAcceptTaskFromDetail(taskDetail, account);- } else {+ handleAcceptTaskFromDetail(taskDetail, account)+ }+ else {// 多个新账号,显示选择弹窗- setAvailableAccounts(newAvailableAccounts);- setAccountSelectVisible(true);+ setAvailableAccounts(newAvailableAccounts)+ setAccountSelectVisible(true)}}}- };+ }// 获取平台图标const getPlatformIcon = (accountType: string) => {- const platInfo = AccountPlatInfoMap.get(accountType as PlatType);- return platInfo?.icon || '';- };-+ const platInfo = AccountPlatInfoMap.get(accountType as PlatType)+ return platInfo?.icon || ''+ }// 获取素材列表const fetchMaterialList = async (groupId: string, page: number = 1, pageSize: number = 9) => {try {- setMaterialLoading(true);- const response: any = await apiGetMaterialList(groupId, page, pageSize);+ setMaterialLoading(true)+ const response: any = await apiGetMaterialList(groupId, page, pageSize)if (response && response.data && response.code === 0) {- setMaterialList(response.data.list || []);+ setMaterialList(response.data.list || [])setMaterialPagination({current: page,- pageSize: pageSize,- total: response.data.total || 0- });+ pageSize,+ total: response.data.total || 0,+ })// 默认选中第一个素材if (response.data.list && response.data.list.length > 0 && !selectedMaterial) {- setSelectedMaterial(response.data.list[0]);+ setSelectedMaterial(response.data.list[0])}}- } catch (error) {- console.error("获取素材列表失败:", error);- message.error("获取素材列表失败");- } finally {- setMaterialLoading(false);}- };-+ catch (error) {+ console.error('获取素材列表失败:', error)+ message.error('获取素材列表失败')+ }+ finally {+ setMaterialLoading(false)+ }+ }+// 查看任务详情const handleViewTaskDetail = async (opportunityId: string) => {try {- setTaskDetailLoading(true);- const response: any = await getTaskDetail(opportunityId);+ setTaskDetailLoading(true)+ const response: any = await getTaskDetail(opportunityId)if (response && response.data && response.code === 0) {- setTaskDetail(response.data);- setTaskDetailModalVisible(true);-+ setTaskDetail(response.data)+ setTaskDetailModalVisible(true)+// 重置草稿选择状态- setDraftSource('task');- setSelectedMaterial(null);-+ setDraftSource('task')+ setSelectedMaterial(null)+// 如果有 materialGroupId,获取素材列表if (response.data.materialGroupId) {- fetchMaterialList(response.data.materialGroupId, 1, 9);+ fetchMaterialList(response.data.materialGroupId, 1, 9)}// 标记任务为已读try {- await apiMarkTaskAsViewed(opportunityId);+ await apiMarkTaskAsViewed(opportunityId)// 刷新任务列表以更新未读状态- fetchPendingTasks(pendingPagination.current, pendingPagination.pageSize);- } catch (error) {- console.error("标记任务为已读失败:", error);+ fetchPendingTasks(pendingPagination.current, pendingPagination.pageSize)+ }+ catch (error) {+ console.error('标记任务为已读失败:', error)// 标记失败不影响主流程,不显示错误提示}- } else {- message.error(t('messages.getTaskDetailFailed'));}- } catch (error) {- message.error(t('messages.getTaskDetailFailed'));- console.error("获取任务详情失败:", error);- } finally {- setTaskDetailLoading(false);+ else {+ message.error(t('messages.getTaskDetailFailed'))+ }}- };+ catch (error) {+ message.error(t('messages.getTaskDetailFailed'))+ console.error('获取任务详情失败:', error)+ }+ finally {+ setTaskDetailLoading(false)+ }+ }// 查看已接受任务详情const handleViewAcceptedTaskDetail = async (taskId: string) => {try {- setAcceptedTaskDetailLoading(true);- setCurrentTaskId(taskId);- const response: any = await apiGetUserTaskDetail(taskId);+ setAcceptedTaskDetailLoading(true)+ setCurrentTaskId(taskId)+ const response: any = await apiGetUserTaskDetail(taskId)if (response && response.data && response.code === 0) {- setAcceptedTaskDetail(response.data);- setAcceptedTaskDetailModalVisible(true);- } else {- message.error(t('messages.getTaskDetailFailed'));+ setAcceptedTaskDetail(response.data)+ setAcceptedTaskDetailModalVisible(true)}- } catch (error) {- message.error(t('messages.getTaskDetailFailed'));- console.error("获取任务详情失败:", error);- } finally {- setAcceptedTaskDetailLoading(false);+ else {+ message.error(t('messages.getTaskDetailFailed'))+ }+ }+ catch (error) {+ message.error(t('messages.getTaskDetailFailed'))+ console.error('获取任务详情失败:', error)+ }+ finally {+ setAcceptedTaskDetailLoading(false)}- };+ }// 从任务详情接受任务const handleAcceptTaskFromDetail = async (task: any, account?: SocialAccount) => {+ if (!task)+ return- if (!task) return;-// 验证是否选择了素材if (!selectedMaterial) {- message.error("请选择一个草稿素材");- return;+ message.error('请选择一个草稿素材')+ return}-+// 关闭详情弹窗- setTaskDetailModalVisible(false);-+ setTaskDetailModalVisible(false)+// 显示进度弹窗- setTaskProgressVisible(true);+ setTaskProgressVisible(true)setTaskProgress({currentStep: 0,steps: [{ title: '正在接受任务...', status: 'processing' },{ title: '正在发布任务...', status: 'wait' },{ title: '正在提交任务...', status: 'wait' },- { title: '任务完成', status: 'wait' }- ]- });-+ { title: '任务完成', status: 'wait' },+ ],+ })+try {// 第一步:接受任务- const response: any = await acceptTask(task.id, task.opportunityId, account?.id);+ const response: any = await acceptTask(task.id, task.opportunityId, account?.id)if (response && response.code === 0 && response.data.id) {// 更新进度:第一步完成,开始第二步setTaskProgress(prev => ({@@ -668,19 +697,19 @@ export default function TaskPageCore() {{ title: t('acceptingTask' as any), status: 'finish' },{ title: t('publishingTask' as any), status: 'processing' },{ title: t('submittingTask' as any), status: 'wait' },- { title: t('taskCompleted' as any), status: 'wait' }- ]- }));+ { title: t('taskCompleted' as any), status: 'wait' },+ ],+ }))// 第二步:发布任务- const publishAccount = account || getAccountById(task.accountId);+ const publishAccount = account || getAccountById(task.accountId)if (publishAccount) {// 使用选中的素材- const material = selectedMaterial;-+ const material = selectedMaterial+// 处理媒体内容- const videos = material.mediaList?.filter((m: any) => m.type === 'video') || [];- const images = material.mediaList?.filter((m: any) => m.type !== 'video') || [];+ const videos = material.mediaList?.filter((m: any) => m.type === 'video') || []+ const images = material.mediaList?.filter((m: any) => m.type !== 'video') || []const publishData = {flowId: publishAccount.uid, // 使用账号的uid作为flowId@@ -688,22 +717,21 @@ export default function TaskPageCore() {accountId: publishAccount.id,title: material.title || task.title,desc: material.desc || task.description,- type: "article" as any, // 固定为 article 类型+ type: 'article' as any, // 固定为 article 类型// 处理素材数据videoUrl: videos.length > 0 ? getOssUrl(videos[0].url) : undefined,coverUrl: material.coverUrl ? getOssUrl(material.coverUrl) : undefined,imgUrlList: images.map((img: any) => getOssUrl(img.url)),option: {},topics: [],- publishTime: getUtcDays(getDays().add(6, "minute")).format(),+ publishTime: getUtcDays(getDays().add(6, 'minute')).format(),userTaskId: response.data.id,- taskMaterialId: material._id // 使用选中素材的ID- };-- const publishResponse: any = await apiCreatePublish(publishData);+ taskMaterialId: material._id, // 使用选中素材的ID+ }+ const publishResponse: any = await apiCreatePublish(publishData)- console.log("publishResponse", publishResponse);+ console.log('publishResponse', publishResponse)// return false;if (publishResponse && publishResponse.code === 0) {@@ -715,14 +743,14 @@ export default function TaskPageCore() {{ title: t('acceptingTask' as any), status: 'finish' },{ title: t('publishingTask' as any), status: 'finish' },{ title: t('submittingTask' as any), status: 'processing' },- { title: t('taskCompleted' as any), status: 'wait' }- ]- }));+ { title: t('taskCompleted' as any), status: 'wait' },+ ],+ }))// 第三步:提交任务- const userTaskId = response.data.id;- const submitResponse: any = await submitTask(userTaskId, material._id);-+ const userTaskId = response.data.id+ const submitResponse: any = await submitTask(userTaskId, material._id)+if (submitResponse && submitResponse.code === 0) {// 更新进度:第三步完成,开始第四步setTaskProgress(prev => ({@@ -732,168 +760,178 @@ export default function TaskPageCore() {{ title: t('acceptingTask' as any), status: 'finish' },{ title: t('publishingTask' as any), status: 'finish' },{ title: t('submittingTask' as any), status: 'finish' },- { title: t('taskCompleted' as any), status: 'finish' }- ]- }));+ { title: t('taskCompleted' as any), status: 'finish' },+ ],+ }))// 延迟1秒后关闭进度窗口并刷新任务列表setTimeout(() => {- setTaskProgressVisible(false);- setTaskDetail(null);- fetchPendingTasks();- fetchAcceptedTasks();- setActiveTab("accepted");- }, 1000);- } else {- throw new Error('提交任务失败');+ setTaskProgressVisible(false)+ setTaskDetail(null)+ fetchPendingTasks()+ fetchAcceptedTasks()+ setActiveTab('accepted')+ }, 1000)+ }+ else {+ throw new Error('提交任务失败')}- } else {- throw new Error('发布任务失败');}- } else {- throw new Error('找不到发布账号信息');+ else {+ throw new Error('发布任务失败')+ }}- } else {- throw new Error('接受任务失败');+ else {+ throw new Error('找不到发布账号信息')+ }+ }+ else {+ throw new Error('接受任务失败')}- } catch (error) {- console.error("任务处理失败:", error);- message.error("任务处理失败");- setTaskProgressVisible(false);}- };+ catch (error) {+ console.error('任务处理失败:', error)+ message.error('任务处理失败')+ setTaskProgressVisible(false)+ }+ }// 已经接受没有完成的任务 去完成const handleCompleteTask = async () => {- if (!currentTaskId) return;-+ if (!currentTaskId)+ return+// 显示进度弹窗- setTaskProgressVisible(true);+ setTaskProgressVisible(true)setTaskProgress({currentStep: 0,steps: [{ title: t('completeTask' as any), status: 'processing' },{ title: t('publishingTask' as any), status: 'wait' },{ title: t('submittingTask' as any), status: 'wait' },- { title: t('taskCompleted' as any), status: 'wait' }- ]- });-- try {- // 更新进度:第一步完成,开始第二步- setTaskProgress(prev => ({- ...prev,- currentStep: 1,- steps: [- { title: '正在完成任务...', status: 'finish' },- { title: '正在发布任务...', status: 'processing' },- { title: '正在提交任务...', status: 'wait' },- { title: '任务完成', status: 'wait' }- ]- }));+ { title: t('taskCompleted' as any), status: 'wait' },+ ],+ })- // 第二步:发布任务- const publishAccount = getAccountById(acceptedTaskDetail.accountId);- if (publishAccount) {- // 处理素材链接,确保使用完整链接- const processedMaterials = acceptedTaskDetail.task?.materials?.map((material: any) => ({- ...material,- coverUrl: material.coverUrl ? getOssUrl(material.coverUrl) : undefined,- mediaList: material.mediaList?.map((media: any) => ({- ...media,- url: getOssUrl(media.url),- coverUrl: media.coverUrl ? getOssUrl(media.coverUrl) : undefined- }))- }));-- const publishData = {- flowId: publishAccount.uid, // 使用账号的uid作为flowId- accountType: publishAccount.type,- accountId: publishAccount.id,- title: acceptedTaskDetail.task?.title,- desc: acceptedTaskDetail.task?.description,- type: acceptedTaskDetail.task?.type as any, // 转换为PubType- // 处理素材数据- videoUrl: processedMaterials?.[0]?.mediaList?.[0]?.type === 'video' ?- getOssUrl(processedMaterials[0].mediaList[0].url) : undefined,- coverUrl: processedMaterials?.[0]?.coverUrl,- imgUrlList: processedMaterials?.flatMap((material: any) =>- material.mediaList?.filter((media: any) => media.type !== 'video')- .map((media: any) => getOssUrl(media.url)) || []- ),- option: {},- topics: [],- publishTime: getUtcDays(getDays().add(6, "minute")).format(),- userTaskId: acceptedTaskDetail.task?.id,- taskMaterialId: acceptedTaskDetail.task?.materialIds[0]+ try {+ // 更新进度:第一步完成,开始第二步+ setTaskProgress(prev => ({+ ...prev,+ currentStep: 1,+ steps: [+ { title: '正在完成任务...', status: 'finish' },+ { title: '正在发布任务...', status: 'processing' },+ { title: '正在提交任务...', status: 'wait' },+ { title: '任务完成', status: 'wait' },+ ],+ }))++ // 第二步:发布任务+ const publishAccount = getAccountById(acceptedTaskDetail.accountId)+ if (publishAccount) {+ // 处理素材链接,确保使用完整链接+ const processedMaterials = acceptedTaskDetail.task?.materials?.map((material: any) => ({+ ...material,+ coverUrl: material.coverUrl ? getOssUrl(material.coverUrl) : undefined,+ mediaList: material.mediaList?.map((media: any) => ({+ ...media,+ url: getOssUrl(media.url),+ coverUrl: media.coverUrl ? getOssUrl(media.coverUrl) : undefined,+ })),+ }))++ const publishData = {+ flowId: publishAccount.uid, // 使用账号的uid作为flowId+ accountType: publishAccount.type,+ accountId: publishAccount.id,+ title: acceptedTaskDetail.task?.title,+ desc: acceptedTaskDetail.task?.description,+ type: acceptedTaskDetail.task?.type as any, // 转换为PubType+ // 处理素材数据+ videoUrl: processedMaterials?.[0]?.mediaList?.[0]?.type === 'video'+ ? getOssUrl(processedMaterials[0].mediaList[0].url)+ : undefined,+ coverUrl: processedMaterials?.[0]?.coverUrl,+ imgUrlList: processedMaterials?.flatMap((material: any) =>+ material.mediaList?.filter((media: any) => media.type !== 'video')+ .map((media: any) => getOssUrl(media.url)) || [],+ ),+ option: {},+ topics: [],+ publishTime: getUtcDays(getDays().add(6, 'minute')).format(),+ userTaskId: acceptedTaskDetail.task?.id,+ taskMaterialId: acceptedTaskDetail.task?.materialIds[0],- };+ }- const publishResponse: any = await apiCreatePublish(publishData);- if (publishResponse && publishResponse.code === 0) {- // 更新进度:第二步完成,开始第三步+ const publishResponse: any = await apiCreatePublish(publishData)+ if (publishResponse && publishResponse.code === 0) {+ // 更新进度:第二步完成,开始第三步+ setTaskProgress(prev => ({+ ...prev,+ currentStep: 2,+ steps: [+ { title: '正在完成任务...', status: 'finish' },+ { title: '正在发布任务...', status: 'finish' },+ { title: '正在提交任务...', status: 'processing' },+ { title: '任务完成', status: 'wait' },+ ],+ }))++ // 第三步:提交任务+ const userTaskId = acceptedTaskDetail.id+ const submitResponse: any = await submitTask(userTaskId, acceptedTaskDetail.task?.materialIds[0])++ if (submitResponse && submitResponse.code === 0) {+ // 更新进度:第三步完成,开始第四步setTaskProgress(prev => ({...prev,- currentStep: 2,+ currentStep: 3,steps: [{ title: '正在完成任务...', status: 'finish' },{ title: '正在发布任务...', status: 'finish' },- { title: '正在提交任务...', status: 'processing' },- { title: '任务完成', status: 'wait' }- ]- }));-- // 第三步:提交任务- const userTaskId = acceptedTaskDetail.id;- const submitResponse: any = await submitTask(userTaskId, acceptedTaskDetail.task?.materialIds[0]);-- if (submitResponse && submitResponse.code === 0) {- // 更新进度:第三步完成,开始第四步- setTaskProgress(prev => ({- ...prev,- currentStep: 3,- steps: [- { title: '正在完成任务...', status: 'finish' },- { title: '正在发布任务...', status: 'finish' },- { title: '正在提交任务...', status: 'finish' },- { title: '任务完成', status: 'finish' }- ]- }));+ { title: '正在提交任务...', status: 'finish' },+ { title: '任务完成', status: 'finish' },+ ],+ }))- // 延迟1秒后关闭进度窗口并刷新任务列表- setTimeout(() => {- setTaskProgressVisible(false);- setAcceptedTaskDetailModalVisible(false);- setAcceptedTaskDetail(null);- setCurrentTaskId(null);- fetchAcceptedTasks();- }, 1000);- } else {- throw new Error('提交任务失败');- }- } else {- throw new Error('发布任务失败');+ // 延迟1秒后关闭进度窗口并刷新任务列表+ setTimeout(() => {+ setTaskProgressVisible(false)+ setAcceptedTaskDetailModalVisible(false)+ setAcceptedTaskDetail(null)+ setCurrentTaskId(null)+ fetchAcceptedTasks()+ }, 1000)+ }+ else {+ throw new Error('提交任务失败')}- } else {- throw new Error('找不到发布账号信息');}-- } catch (error) {- console.error("任务处理失败:", error);- message.error("任务处理失败");- setTaskProgressVisible(false);+ else {+ throw new Error('发布任务失败')+ }+ }+ else {+ throw new Error('找不到发布账号信息')+ }}- };+ catch (error) {+ console.error('任务处理失败:', error)+ message.error('任务处理失败')+ setTaskProgressVisible(false)+ }+ }// 处理待接受任务分页变化const handlePendingPageChange = (page: number, pageSize?: number) => {- fetchPendingTasks(page, pageSize || pendingPagination.pageSize);- };+ fetchPendingTasks(page, pageSize || pendingPagination.pageSize)+ }// 处理已接受任务分页变化const handleAcceptedPageChange = (page: number, pageSize?: number) => {- fetchAcceptedTasks(page, pageSize || acceptedPagination.pageSize);- };+ fetchAcceptedTasks(page, pageSize || acceptedPagination.pageSize)+ }// 处理媒体点击const handleMediaClick = (media: any, materialTitle?: string) => {@@ -901,54 +939,55 @@ export default function TaskPageCore() {setPreviewMedia({type: 'video',url: getOssUrl(media.url),- title: materialTitle- });- } else {+ title: materialTitle,+ })+ }+ else {setPreviewMedia({type: 'image',url: getOssUrl(media.url),- title: materialTitle- });+ title: materialTitle,+ })}- setMediaPreviewVisible(true);- };+ setMediaPreviewVisible(true)+ }// 处理视频封面点击const handleVideoCoverClick = (media: any, materialTitle?: string) => {setPreviewMedia({type: 'video',url: getOssUrl(media.url),- title: materialTitle- });- setMediaPreviewVisible(true);- };+ title: materialTitle,+ })+ setMediaPreviewVisible(true)+ }// 关闭媒体预览const handleCloseMediaPreview = () => {// 停止视频播放if (videoRef) {- videoRef.pause();- videoRef.currentTime = 0;+ videoRef.pause()+ videoRef.currentTime = 0}- setMediaPreviewVisible(false);- setPreviewMedia(null);- setVideoRef(null);- };+ setMediaPreviewVisible(false)+ setPreviewMedia(null)+ setVideoRef(null)+ }useEffect(() => {if (token) {- fetchPendingTasks();- fetchAcceptedTasks();- fetchAccountList();+ fetchPendingTasks()+ fetchAcceptedTasks()+ fetchAccountList()}- }, [token]);+ }, [token])// 监听账号列表变化,检查是否有新添加的符合条件账号useEffect(() => {if (accountList.length > 0) {- checkForNewAccounts();+ checkForNewAccounts()}- }, [accountList, requiredAccountTypes, taskDetail]);+ }, [accountList, requiredAccountTypes, taskDetail])return (<div className={styles.taskPage}>@@ -957,18 +996,20 @@ export default function TaskPageCore() {<p>接受任务,完成任务,获得奖励</p></div> */}- <Tabs- activeKey={activeTab}+ <Tabs+ activeKey={activeTab}onChange={setActiveTab}className={styles.tabs}>- <TabPane- tab={+ <TabPane+ tab={(<span><ClockCircleOutlined />- {t('pendingTasks')}+ + {' '}+ {t('pendingTasks')}</span>- }+ )}key="pending"><Spin spinning={loading}>@@ -976,117 +1017,145 @@ export default function TaskPageCore() {<div><div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(350px, 1fr))', gap: '16px', marginBottom: '16px' }}>{pendingTasks.map((task: any) => {- const publishAccount = getAccountById(task.accountId);- return (- <Card- key={task.id}- className={styles.taskCard}- style={{ marginBottom: 0, position: 'relative' }}- >- {/* 未读红点标识 */}- {!task.isView && (- <div style={{- position: 'absolute',- top: '8px',- right: '8px',- width: '8px',- height: '8px',- backgroundColor: '#ff4d4f',- borderRadius: '50%',- zIndex: 1,- boxShadow: '0 0 0 2px #fff'- }} />- )}-- <div className={styles.taskHeader}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- {/* 显示多个平台图标 */}- <div style={{ display: 'flex', gap: '4px' }}>- {(task.accountTypes && task.accountTypes.length > 0 ? task.accountTypes : [task.accountType]).map((platformType: string, index: number) => (- <img- key={platformType}- src={getPlatformIcon(platformType)}- alt="platform"- style={{ width: '20px', height: '20px' }}- />- ))}+ const publishAccount = getAccountById(task.accountId)+ return (+ <Card+ key={task.id}+ className={styles.taskCard}+ style={{ marginBottom: 0, position: 'relative' }}+ >+ {/* 未读红点标识 */}+ {!task.isView && (+ <div style={{+ position: 'absolute',+ top: '8px',+ right: '8px',+ width: '8px',+ height: '8px',+ backgroundColor: '#ff4d4f',+ borderRadius: '50%',+ zIndex: 1,+ boxShadow: '0 0 0 2px #fff',+ }}+ />+ )}++ <div className={styles.taskHeader}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ {/* 显示多个平台图标 */}+ <div style={{ display: 'flex', gap: '4px' }}>+ {(task.accountTypes && task.accountTypes.length > 0 ? task.accountTypes : [task.accountType]).map((platformType: string, index: number) => (+ <img+ key={platformType}+ src={getPlatformIcon(platformType)}+ alt="platform"+ style={{ width: '20px', height: '20px' }}+ />+ ))}+ </div>+ <h3 style={{ margin: 0, fontSize: '16px' }}>+ {task.accountTypes && task.accountTypes.length > 0+ ? `${task.accountTypes.map((type: string) => getPlatformName(type)).join('、')}任务`+ : `${getPlatformName(task.accountType)}任务`}+ </h3></div>- <h3 style={{ margin: 0, fontSize: '16px' }}>- {task.accountTypes && task.accountTypes.length > 0- ? `${task.accountTypes.map((type: string) => getPlatformName(type)).join('、')}任务`- : `${getPlatformName(task.accountType)}任务`- }- </h3>- </div>- <Tag color="orange">{t('taskStatus.pending' as any)}</Tag>- </div>-- <div className={styles.taskContent}>- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>- <span><strong>{t('taskInfo.publishTime' as any)}:</strong>{formatTime(task.createdAt)}</span>- <span><strong>{t('taskInfo.endTime' as any)}:</strong>{formatAbsoluteTime(task.expiredAt)}</span>+ <Tag color="orange">{t('taskStatus.pending' as any)}</Tag></div>-- {task.reward > 0 && <div style={{ marginBottom: '12px' }}>- <strong>{t('taskInfo.reward' as any)}:</strong>- <span style={{ color: '#f50', fontWeight: 'bold' }}>¥ {task.reward/100}</span>- </div>}-- {task.cpmReward > 0 && <div style={{ marginBottom: '12px' }}>- <strong>{t('taskInfo.CPM' as any)}:</strong>- <span style={{ color: '#f50', fontWeight: 'bold' }}>¥ {task.cpmReward/100}</span>- </div>}--- {/* 发布账号信息 */}- {publishAccount && (- <div style={{- display: 'flex',- alignItems: 'center',- gap: '8px',- padding: '8px',- backgroundColor: '#f8f9fa',- borderRadius: '6px',- marginBottom: '12px'- }}>- <img- src={publishAccount.avatar ? getOssUrl(publishAccount.avatar) : '/default-avatar.png'}- alt="账号头像"- style={{- width: '32px',- height: '32px',- borderRadius: '50%',- objectFit: 'cover'- }}- onError={(e) => {- e.currentTarget.src = '/default-avatar.png';- }}- />- <div>- <div style={{ fontWeight: '500', fontSize: '14px' }}>- {publishAccount.nickname}- </div>- <div style={{ fontSize: '12px', color: '#666' }}>- {getPlatformName(publishAccount.type)}++ <div className={styles.taskContent}>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>+ <span>+ <strong>+ {t('taskInfo.publishTime' as any)}+ :+ </strong>+ {formatTime(task.createdAt)}+ </span>+ <span>+ <strong>+ {t('taskInfo.endTime' as any)}+ :+ </strong>+ {formatAbsoluteTime(task.expiredAt)}+ </span>+ </div>++ {task.reward > 0 && (+ <div style={{ marginBottom: '12px' }}>+ <strong>+ {t('taskInfo.reward' as any)}+ :+ </strong>+ <span style={{ color: '#f50', fontWeight: 'bold' }}>+ ¥+ {task.reward / 100}+ </span>+ </div>+ )}++ {task.cpmReward > 0 && (+ <div style={{ marginBottom: '12px' }}>+ <strong>+ {t('taskInfo.CPM' as any)}+ :+ </strong>+ <span style={{ color: '#f50', fontWeight: 'bold' }}>+ ¥+ {task.cpmReward / 100}+ </span>+ </div>+ )}++ {/* 发布账号信息 */}+ {publishAccount && (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ padding: '8px',+ backgroundColor: '#f8f9fa',+ borderRadius: '6px',+ marginBottom: '12px',+ }}+ >+ <img+ src={publishAccount.avatar ? getOssUrl(publishAccount.avatar) : '/default-avatar.png'}+ alt="账号头像"+ style={{+ width: '32px',+ height: '32px',+ borderRadius: '50%',+ objectFit: 'cover',+ }}+ onError={(e) => {+ e.currentTarget.src = '/default-avatar.png'+ }}+ />+ <div>+ <div style={{ fontWeight: '500', fontSize: '14px' }}>+ {publishAccount.nickname}+ </div>+ <div style={{ fontSize: '12px', color: '#666' }}>+ {getPlatformName(publishAccount.type)}+ </div></div></div>- </div>- )}- </div>-- <div className={styles.taskActions}>- <Button- type="primary"- onClick={() => handleViewTaskDetail(task.id)}- icon={<EyeOutlined />}- style={{ width: '100%' }}- >- {t('viewDetails')}- </Button>- </div>- </Card>- );- })}+ )}+ </div>++ <div className={styles.taskActions}>+ <Button+ type="primary"+ onClick={() => handleViewTaskDetail(task.id)}+ icon={<EyeOutlined />}+ style={{ width: '100%' }}+ >+ {t('viewDetails')}+ </Button>+ </div>+ </Card>+ )+ })}</div><div style={{ textAlign: 'center', marginTop: '16px' }}><Pagination@@ -1108,13 +1177,15 @@ export default function TaskPageCore() {</Spin></TabPane>- <TabPane- tab={+ <TabPane+ tab={(<span><PlayCircleOutlined />- {t('acceptedTasks')}+ + {' '}+ {t('acceptedTasks')}</span>- }+ )}key="accepted"><Spin spinning={loading}>@@ -1122,98 +1193,110 @@ export default function TaskPageCore() {<div><div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(350px, 1fr))', gap: '16px', marginBottom: '16px' }}>{acceptedTasks.map((task: any) => {- const publishAccount = getAccountById(task.accountId);- return (- <Card- key={task.id}- className={styles.taskCard}- style={{ marginBottom: 0 }}- >- <div className={styles.taskHeader}>- <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>- {/* 显示多个平台图标 */}- <div style={{ display: 'flex', gap: '4px' }}>- {(task.accountTypes && task.accountTypes.length > 0 ? task.accountTypes : [task.accountType]).map((platformType: string, index: number) => (- <img- key={platformType}- src={getPlatformIcon(platformType)}- alt="platform"- style={{ width: '20px', height: '20px' }}- />- ))}+ const publishAccount = getAccountById(task.accountId)+ return (+ <Card+ key={task.id}+ className={styles.taskCard}+ style={{ marginBottom: 0 }}+ >+ <div className={styles.taskHeader}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>+ {/* 显示多个平台图标 */}+ <div style={{ display: 'flex', gap: '4px' }}>+ {(task.accountTypes && task.accountTypes.length > 0 ? task.accountTypes : [task.accountType]).map((platformType: string, index: number) => (+ <img+ key={platformType}+ src={getPlatformIcon(platformType)}+ alt="platform"+ style={{ width: '20px', height: '20px' }}+ />+ ))}+ </div>+ <h3 style={{ margin: 0, fontSize: '16px' }}>+ {task.accountTypes && task.accountTypes.length > 0+ ? `${task.accountTypes.map((type: string) => getPlatformName(type)).join('、')}任务`+ : `${getPlatformName(task.accountType)}任务`}+ </h3></div>- <h3 style={{ margin: 0, fontSize: '16px' }}>- {task.accountTypes && task.accountTypes.length > 0- ? `${task.accountTypes.map((type: string) => getPlatformName(type)).join('、')}任务`- : `${getPlatformName(task.accountType)}任务`- }- </h3>- </div>- <Tag color={getTaskStatusTag(task.status).color}>- {getTaskStatusTag(task.status).text}- </Tag>- </div>-- <div className={styles.taskContent}>- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>- <span><strong>{t('taskInfo.acceptTime' as any)}:</strong>{formatTime(task.createdAt)}</span>- <span> </span>+ <Tag color={getTaskStatusTag(task.status).color}>+ {getTaskStatusTag(task.status).text}+ </Tag></div>-- <div style={{ marginBottom: '12px' }}>- <strong>{t('taskInfo.reward' as any)}:</strong>- <span style={{ color: '#f50', fontWeight: 'bold' }}>¥ {task.reward/100}</span>- </div>-- {/* 发布账号信息 */}- {publishAccount && (- <div style={{- display: 'flex',- alignItems: 'center',- gap: '8px',- padding: '8px',- backgroundColor: '#f8f9fa',- borderRadius: '6px',- marginBottom: '12px'- }}>- <img- src={publishAccount.avatar ? getOssUrl(publishAccount.avatar) : '/default-avatar.png'}- alt="账号头像"- style={{- width: '32px',- height: '32px',- borderRadius: '50%',- objectFit: 'cover'- }}- onError={(e) => {- e.currentTarget.src = '/default-avatar.png';- }}- />- <div>- <div style={{ fontWeight: '500', fontSize: '14px' }}>- {publishAccount.nickname}- </div>- <div style={{ fontSize: '12px', color: '#666' }}>- {getPlatformName(publishAccount.type)}++ <div className={styles.taskContent}>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '12px' }}>+ <span>+ <strong>+ {t('taskInfo.acceptTime' as any)}+ :+ </strong>+ {formatTime(task.createdAt)}+ </span>+ <span> </span>+ </div>++ <div style={{ marginBottom: '12px' }}>+ <strong>+ {t('taskInfo.reward' as any)}+ :+ </strong>+ <span style={{ color: '#f50', fontWeight: 'bold' }}>+ ¥+ {task.reward / 100}+ </span>+ </div>++ {/* 发布账号信息 */}+ {publishAccount && (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ padding: '8px',+ backgroundColor: '#f8f9fa',+ borderRadius: '6px',+ marginBottom: '12px',+ }}+ >+ <img+ src={publishAccount.avatar ? getOssUrl(publishAccount.avatar) : '/default-avatar.png'}+ alt="账号头像"+ style={{+ width: '32px',+ height: '32px',+ borderRadius: '50%',+ objectFit: 'cover',+ }}+ onError={(e) => {+ e.currentTarget.src = '/default-avatar.png'+ }}+ />+ <div>+ <div style={{ fontWeight: '500', fontSize: '14px' }}>+ {publishAccount.nickname}+ </div>+ <div style={{ fontSize: '12px', color: '#666' }}>+ {getPlatformName(publishAccount.type)}+ </div></div></div>- </div>- )}- </div>-- <div className={styles.taskActions}>- <Button- type="primary"- onClick={() => handleViewAcceptedTaskDetail(task.id)}- icon={<EyeOutlined />}- style={{ width: '100%' }}- >- {t('viewDetails')}- </Button>- </div>- </Card>- );- })}+ )}+ </div>++ <div className={styles.taskActions}>+ <Button+ type="primary"+ onClick={() => handleViewAcceptedTaskDetail(task.id)}+ icon={<EyeOutlined />}+ style={{ width: '100%' }}+ >+ {t('viewDetails')}+ </Button>+ </div>+ </Card>+ )+ })}</div><div style={{ textAlign: 'center', marginTop: '16px' }}><Pagination@@ -1246,10 +1329,13 @@ export default function TaskPageCore() {cancelText={t('modal.cancel')}><div style={{ marginBottom: '16px' }}>- <label>{t('modal.submitLink')}:</label>+ <label>+ {t('modal.submitLink')}+ :+ </label><Inputvalue={submissionUrl}- onChange={(e) => setSubmissionUrl(e.target.value)}+ onChange={e => setSubmissionUrl(e.target.value)}placeholder={t('modal.submitLinkPlaceholder')}style={{ marginTop: '8px' }}/>@@ -1264,11 +1350,11 @@ export default function TaskPageCore() {title={t('taskDetails')}open={taskDetailModalVisible}onCancel={() => {- setTaskDetailModalVisible(false);- setTaskDetail(null);- setMaterialList([]);- setSelectedMaterial(null);- setDraftSource('task');+ setTaskDetailModalVisible(false)+ setTaskDetail(null)+ setMaterialList([])+ setSelectedMaterial(null)+ setDraftSource('task')}}footer={null}width={1200}@@ -1276,39 +1362,42 @@ export default function TaskPageCore() {styles={{header: {borderBottom: '1px solid #f0f0f0',- paddingBottom: '16px'+ paddingBottom: '16px',},body: {- padding: '24px'- }+ padding: '24px',+ },}}><Spin spinning={taskDetailLoading}>{taskDetail ? (<div>{/* 任务基本信息 */}- <div style={{+ <div style={{marginBottom: '24px',padding: '16px',backgroundColor: '#f8f9fa',borderRadius: '8px',- border: '1px solid #e9ecef'- }}>- <h2 style={{- margin: '0 0 12px 0',- fontSize: '18px',+ border: '1px solid #e9ecef',+ }}+ >+ <h2 style={{+ margin: '0 0 12px 0',+ fontSize: '18px',fontWeight: '600',- color: '#1a1a1a'- }}>+ color: '#1a1a1a',+ }}+ >{taskDetail.title}</h2>-- <div style={{- fontSize: '14px',++ <div style={{+ fontSize: '14px',lineHeight: '1.6',color: '#495057',- marginBottom: '12px'- }}>+ marginBottom: '12px',+ }}+ ><div dangerouslySetInnerHTML={{ __html: taskDetail.description }} /></div>@@ -1316,50 +1405,57 @@ export default function TaskPageCore() {<Row gutter={12}>{taskDetail.reward > 0 && (<Col span={8}>- <div style={{+ <div style={{padding: '12px',backgroundColor: '#fff3cd',border: '1px solid #ffeaa7',borderRadius: '8px',- textAlign: 'center'- }}>+ textAlign: 'center',+ }}+ ><div style={{ fontSize: '12px', color: '#856404', marginBottom: '4px' }}>{t('taskInfo.reward' as any)}</div><div style={{ fontSize: '14px', fontWeight: 'bold', color: '#d63031' }}>- ¥ {taskDetail.reward/100}+ ¥+ {' '}+ {taskDetail.reward / 100}</div></div></Col>)}-+{taskDetail.cpmReward > 0 && (<Col span={8}>- <div style={{+ <div style={{padding: '12px',backgroundColor: '#fff3cd',border: '1px solid #ffeaa7',borderRadius: '8px',- textAlign: 'center'- }}>+ textAlign: 'center',+ }}+ ><div style={{ fontSize: '12px', color: '#856404', marginBottom: '4px' }}>{t('taskInfo.CPM' as any)}</div><div style={{ fontSize: '18px', fontWeight: 'bold', color: '#d63031' }}>- ¥ {taskDetail.cpmReward/100}+ ¥+ {' '}+ {taskDetail.cpmReward / 100}</div></div></Col>)}-+<Col span={8}>- <div style={{+ <div style={{padding: '12px',backgroundColor: '#d1ecf1',border: '1px solid #bee5eb',borderRadius: '8px',- textAlign: 'center'- }}>+ textAlign: 'center',+ }}+ ><div style={{ fontSize: '12px', color: '#0c5460', marginBottom: '4px' }}>{t('taskInfo.type' as any)}</div>@@ -1373,20 +1469,21 @@ export default function TaskPageCore() {{/* 草稿选择区域 */}<div style={{ marginBottom: '24px' }}>- <div style={{- display: 'flex',- alignItems: 'center',+ <div style={{+ display: 'flex',+ alignItems: 'center',justifyContent: 'space-between',- marginBottom: '16px'- }}>+ marginBottom: '16px',+ }}+ ><div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}><span style={{ fontSize: '16px', fontWeight: '600' }}>选择草稿:</span>- <Radio.Group- value={draftSource}+ <Radio.Group+ value={draftSource}onChange={(e) => {- setDraftSource(e.target.value);+ setDraftSource(e.target.value)if (e.target.value === 'own') {- setDraftModalOpen(true);+ setDraftModalOpen(true)}}}>@@ -1395,8 +1492,8 @@ export default function TaskPageCore() {</Radio.Group></div>{draftSource === 'own' && selectedMaterial && (- <Button- type="link"+ <Button+ type="link"onClick={() => setDraftModalOpen(true)}>重新选择@@ -1409,12 +1506,13 @@ export default function TaskPageCore() {<Spin spinning={materialLoading}>{materialList.length > 0 ? (<>- <div style={{- display: 'grid',- gridTemplateColumns: 'repeat(3, 1fr)',+ <div style={{+ display: 'grid',+ gridTemplateColumns: 'repeat(3, 1fr)',gap: '16px',- marginBottom: '16px'- }}>+ marginBottom: '16px',+ }}+ >{materialList.map((material: any) => (<divkey={material._id}@@ -1425,15 +1523,16 @@ export default function TaskPageCore() {overflow: 'hidden',cursor: 'pointer',transition: 'all 0.3s ease',- backgroundColor: selectedMaterial?._id === material._id ? '#e6f7ff' : '#fff'+ backgroundColor: selectedMaterial?._id === material._id ? '#e6f7ff' : '#fff',}}>{/* 素材封面 */}- <div style={{- position: 'relative',- paddingTop: '56.25%',- background: '#f0f0f0'- }}>+ <div style={{+ position: 'relative',+ paddingTop: '56.25%',+ background: '#f0f0f0',+ }}+ >{material.coverUrl && (<imgsrc={getOssUrl(material.coverUrl)}@@ -1444,7 +1543,7 @@ export default function TaskPageCore() {left: 0,width: '100%',height: '100%',- objectFit: 'cover'+ objectFit: 'cover',}}/>)}@@ -1456,8 +1555,9 @@ export default function TaskPageCore() {transform: 'translate(-50%, -50%)',color: 'white',fontSize: '32px',- textShadow: '0 2px 4px rgba(0,0,0,0.5)'- }}>+ textShadow: '0 2px 4px rgba(0,0,0,0.5)',+ }}+ >▶</div>)}@@ -1474,39 +1574,42 @@ export default function TaskPageCore() {alignItems: 'center',justifyContent: 'center',color: 'white',- fontSize: '14px'- }}>+ fontSize: '14px',+ }}+ >✓</div>)}</div>-+{/* 素材信息 */}<div style={{ padding: '12px' }}>- <div style={{- fontSize: '14px',+ <div style={{+ fontSize: '14px',fontWeight: '500',marginBottom: '4px',overflow: 'hidden',textOverflow: 'ellipsis',- whiteSpace: 'nowrap'- }}>+ whiteSpace: 'nowrap',+ }}+ >{material.title || '无标题'}</div>- <div style={{- fontSize: '12px',+ <div style={{+ fontSize: '12px',color: '#999',overflow: 'hidden',textOverflow: 'ellipsis',- whiteSpace: 'nowrap'- }}>+ whiteSpace: 'nowrap',+ }}+ >{material.desc || '无描述'}</div></div></div>))}</div>-+{/* 分页 */}{materialPagination.total > materialPagination.pageSize && (<div style={{ textAlign: 'center' }}>@@ -1516,7 +1619,7 @@ export default function TaskPageCore() {total={materialPagination.total}onChange={(page, pageSize) => {if (taskDetail.materialGroupId) {- fetchMaterialList(taskDetail.materialGroupId, page, pageSize);+ fetchMaterialList(taskDetail.materialGroupId, page, pageSize)}}}showSizeChanger={false}@@ -1537,24 +1640,26 @@ export default function TaskPageCore() {borderRadius: '8px',overflow: 'hidden',backgroundColor: '#e6f7ff',- padding: '16px'- }}>+ padding: '16px',+ }}+ ><div style={{ display: 'flex', gap: '16px' }}>{selectedMaterial.coverUrl && (- <div style={{- width: '120px',- height: '120px',+ <div style={{+ width: '120px',+ height: '120px',borderRadius: '8px',overflow: 'hidden',- flexShrink: 0- }}>+ flexShrink: 0,+ }}+ ><imgsrc={getOssUrl(selectedMaterial.coverUrl)}alt={selectedMaterial.title}style={{width: '100%',height: '100%',- objectFit: 'cover'+ objectFit: 'cover',}}/></div>@@ -1575,16 +1680,17 @@ export default function TaskPageCore() {<Empty description="请选择一个草稿" />)}</div>-+{/* 底部按钮 */}{taskDetail.status === 'active' && taskDetail.currentRecruits < taskDetail.maxRecruits && (- <div style={{+ <div style={{textAlign: 'center',paddingTop: '16px',- borderTop: '1px solid #e8e8e8'- }}>- <Button- type="primary"+ borderTop: '1px solid #e8e8e8',+ }}+ >+ <Button+ type="primary"size="large"onClick={() => handleTaskAction(taskDetail)}disabled={!selectedMaterial}@@ -1606,20 +1712,20 @@ export default function TaskPageCore() {)}</Spin></Modal>-+{/* DraftSelectionModal 用于选择自己的草稿 */}<DraftSelectionModaldraftModalOpen={draftModalOpen}onCancel={() => {- setDraftModalOpen(false);+ setDraftModalOpen(false)// 如果取消选择且当前选择的是自己的草稿,切换回任务草稿if (draftSource === 'own' && !selectedMaterial) {- setDraftSource('task');+ setDraftSource('task')}}}onSelectDraft={(draft) => {- setSelectedMaterial(draft);- setDraftSource('own');+ setSelectedMaterial(draft)+ setDraftSource('own')}}/>@@ -1628,49 +1734,51 @@ export default function TaskPageCore() {title={t('taskDetails')}open={acceptedTaskDetailModalVisible}onCancel={() => {- setAcceptedTaskDetailModalVisible(false);- setAcceptedTaskDetail(null);+ setAcceptedTaskDetailModalVisible(false)+ setAcceptedTaskDetail(null)}}footer={[-+]}width={800}zIndex={2000}styles={{header: {borderBottom: '1px solid #f0f0f0',- paddingBottom: '16px'+ paddingBottom: '16px',},body: {- padding: '24px'- }+ padding: '24px',+ },}}><Spin spinning={acceptedTaskDetailLoading}>{acceptedTaskDetail ? (<div>{/* 视频发布风格布局 */}- <div style={{- display: 'flex',+ <div style={{+ display: 'flex',gap: '24px',- marginBottom: '24px'- }}>+ marginBottom: '24px',+ }}+ >{/* 左侧:视频/媒体内容 */}<div style={{ flex: '0 0 400px' }}>{acceptedTaskDetail.task?.materials && acceptedTaskDetail.task.materials.length > 0 && (- <div style={{- border: '1px solid #e8e8e8',- borderRadius: '12px',+ <div style={{+ border: '1px solid #e8e8e8',+ borderRadius: '12px',overflow: 'hidden',- backgroundColor: '#000'- }}>+ backgroundColor: '#000',+ }}+ >{acceptedTaskDetail.task.materials[0].mediaList && acceptedTaskDetail.task.materials[0].mediaList.length > 0 && (<div style={{ position: 'relative', cursor: 'pointer' }}>{acceptedTaskDetail.task.materials[0].mediaList[0].type === 'video' ? (- <div+ <divstyle={{position: 'relative',- overflow: 'hidden'+ overflow: 'hidden',}}onClick={() => handleVideoCoverClick(acceptedTaskDetail.task.materials[0].mediaList[0], acceptedTaskDetail.task.title)}>@@ -1681,7 +1789,7 @@ export default function TaskPageCore() {style={{width: '100%',height: 'auto',- display: 'block'+ display: 'block',}}/>{/* 播放按钮 */}@@ -1700,8 +1808,9 @@ export default function TaskPageCore() {alignItems: 'center',justifyContent: 'center',cursor: 'pointer',- transition: 'all 0.3s ease'- }}>+ transition: 'all 0.3s ease',+ }}+ >▶</div></div>@@ -1712,7 +1821,7 @@ export default function TaskPageCore() {style={{width: '100%',height: 'auto',- display: 'block'+ display: 'block',}}onClick={() => handleMediaClick(acceptedTaskDetail.task.materials[0].mediaList[0], acceptedTaskDetail.task.title)}/>@@ -1727,235 +1836,264 @@ export default function TaskPageCore() {<div style={{ flex: '1', minWidth: '300px' }}>{/* 标题区域 */}<div style={{ marginBottom: '16px' }}>- <h2 style={{- margin: '0 0 8px 0',- fontSize: '20px',+ <h2 style={{+ margin: '0 0 8px 0',+ fontSize: '20px',fontWeight: '600',lineHeight: '1.4',- color: '#1a1a1a'- }}>+ color: '#1a1a1a',+ }}+ >{acceptedTaskDetail.task?.title}</h2>-+{/* 发布账号信息 */}{acceptedTaskDetail.accountId && (() => {- const publishAccount = getAccountById(acceptedTaskDetail.accountId);- return publishAccount ? (- <div style={{- display: 'flex',- alignItems: 'center',- gap: '8px',- marginBottom: '12px'- }}>- <img- src={publishAccount.avatar ? getOssUrl(publishAccount.avatar) : '/default-avatar.png'}- alt="账号头像"- style={{- width: '32px',- height: '32px',- borderRadius: '50%',- objectFit: 'cover'- }}- onError={(e) => {- e.currentTarget.src = '/default-avatar.png';+ const publishAccount = getAccountById(acceptedTaskDetail.accountId)+ return publishAccount+ ? (+ <div style={{+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ marginBottom: '12px',}}- />- <div>- <div style={{- fontSize: '14px',- fontWeight: '500',- color: '#1a1a1a'- }}>- {publishAccount.nickname}- </div>- <div style={{- fontSize: '12px',- color: '#666'- }}>- {getPlatformName(publishAccount.type)}+ >+ <img+ src={publishAccount.avatar ? getOssUrl(publishAccount.avatar) : '/default-avatar.png'}+ alt="账号头像"+ style={{+ width: '32px',+ height: '32px',+ borderRadius: '50%',+ objectFit: 'cover',+ }}+ onError={(e) => {+ e.currentTarget.src = '/default-avatar.png'+ }}+ />+ <div>+ <div style={{+ fontSize: '14px',+ fontWeight: '500',+ color: '#1a1a1a',+ }}+ >+ {publishAccount.nickname}+ </div>+ <div style={{+ fontSize: '12px',+ color: '#666',+ }}+ >+ {getPlatformName(publishAccount.type)}+ </div>+ </div></div>- </div>- </div>- ) : null;+ )+ : null})()}</div>{/* 描述区域 */}- <div style={{+ <div style={{marginBottom: '16px',padding: '16px',backgroundColor: '#f8f9fa',borderRadius: '8px',- border: '1px solid #e9ecef'- }}>- <div style={{- fontSize: '14px',+ border: '1px solid #e9ecef',+ }}+ >+ <div style={{+ fontSize: '14px',lineHeight: '1.6',- color: '#495057'- }}>+ color: '#495057',+ }}+ ><div dangerouslySetInnerHTML={{ __html: acceptedTaskDetail.task?.description }} /></div></div>{/* 任务信息卡片 */}- <div style={{- display: 'flex',+ <div style={{+ display: 'flex',gap: '12px',- marginBottom: '16px'- }}>- <div style={{+ marginBottom: '16px',+ }}+ >+ <div style={{flex: '1',padding: '12px',backgroundColor: '#fff3cd',border: '1px solid #ffeaa7',borderRadius: '8px',- textAlign: 'center'- }}>- <div style={{- fontSize: '12px',+ textAlign: 'center',+ }}+ >+ <div style={{+ fontSize: '12px',color: '#856404',- marginBottom: '4px'- }}>+ marginBottom: '4px',+ }}+ >{t('taskInfo.reward' as any)}</div>- <div style={{- fontSize: '18px',+ <div style={{+ fontSize: '18px',fontWeight: 'bold',- color: '#d63031'- }}>- ¥ {acceptedTaskDetail.reward/100}+ color: '#d63031',+ }}+ >+ ¥+ {' '}+ {acceptedTaskDetail.reward / 100}</div></div>-- <div style={{++ <div style={{flex: '1',padding: '12px',backgroundColor: '#d1ecf1',border: '1px solid #bee5eb',borderRadius: '8px',- textAlign: 'center'- }}>- <div style={{- fontSize: '12px',+ textAlign: 'center',+ }}+ >+ <div style={{+ fontSize: '12px',color: '#0c5460',- marginBottom: '4px'- }}>+ marginBottom: '4px',+ }}+ >{t('taskInfo.type' as any)}</div>- <div style={{- fontSize: '14px',+ <div style={{+ fontSize: '14px',fontWeight: '500',- color: '#0c5460'- }}>+ color: '#0c5460',+ }}+ >{getTaskTypeName(acceptedTaskDetail.task?.type)}</div></div></div>{/* 任务状态信息 */}- <div style={{- display: 'flex',+ <div style={{+ display: 'flex',gap: '12px',- marginBottom: '16px'- }}>- <div style={{+ marginBottom: '16px',+ }}+ >+ <div style={{flex: '1',padding: '12px',backgroundColor: '#e2e3e5',border: '1px solid #d6d8db',borderRadius: '8px',- textAlign: 'center'- }}>- <div style={{- fontSize: '12px',+ textAlign: 'center',+ }}+ >+ <div style={{+ fontSize: '12px',color: '#495057',- marginBottom: '4px'- }}>+ marginBottom: '4px',+ }}+ >接受时间</div>- <div style={{- fontSize: '12px',+ <div style={{+ fontSize: '12px',fontWeight: '500',- color: '#495057'- }}>+ color: '#495057',+ }}+ >{formatTime(acceptedTaskDetail.createdAt)}</div></div>-- <div style={{++ <div style={{flex: '1',padding: '12px',backgroundColor: '#e2e3e5',border: '1px solid #d6d8db',borderRadius: '8px',- textAlign: 'center'- }}>- <div style={{- fontSize: '12px',+ textAlign: 'center',+ }}+ >+ <div style={{+ fontSize: '12px',color: '#495057',- marginBottom: '4px'- }}>+ marginBottom: '4px',+ }}+ >提交时间</div>- <div style={{- fontSize: '12px',+ <div style={{+ fontSize: '12px',fontWeight: '500',- color: '#495057'- }}>+ color: '#495057',+ }}+ >{acceptedTaskDetail.submissionTime ? formatTime(acceptedTaskDetail.submissionTime) : '未提交'}</div></div></div></div></div>-+{/* 底部状态栏 */}- <div style={{- display: 'flex',- justifyContent: 'space-between',+ <div style={{+ display: 'flex',+ justifyContent: 'space-between',alignItems: 'center',padding: '16px 0',borderTop: '1px solid #e8e8e8',- marginTop: '16px'- }}>+ marginTop: '16px',+ }}+ ><div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>- <Tag+ <Tagcolor={getTaskStatusTag(acceptedTaskDetail.status).color}- style={{+ style={{fontSize: '12px',- padding: '4px 8px'+ padding: '4px 8px',}}>{getTaskStatusTag(acceptedTaskDetail.status).text}</Tag>- <span style={{- fontSize: '12px',- color: '#666'- }}>- {acceptedTaskDetail.status === 'doing' ? '任务待完成' :- acceptedTaskDetail.status === 'pending' ? '任务已完成' :- '任务状态:' + acceptedTaskDetail.status}+ <span style={{+ fontSize: '12px',+ color: '#666',+ }}+ >+ {acceptedTaskDetail.status === 'doing'+ ? '任务待完成'+ : acceptedTaskDetail.status === 'pending'+ ? '任务已完成'+ : `任务状态:${acceptedTaskDetail.status}`}</span></div>-- <div style={{- fontSize: '12px',- color: '#999'- }}>++ <div style={{+ fontSize: '12px',+ color: '#999',+ }}+ >{acceptedTaskDetail.isFirstTimeSubmission && (<span style={{ color: '#52c41a' }}>首次提交</span>)}</div></div>-+{/* 根据任务状态显示不同按钮 */}{(() => {// 如果是已接受任务且状态为doing(待完成),显示完成任务按钮if (acceptedTaskDetail.status === 'doing') {return (<div style={{ textAlign: 'center', marginTop: '16px' }}>- <Button- type="primary"+ <Button+ type="primary"size="large"onClick={handleCompleteTask}style={{ marginTop: '12px' }}@@ -1963,10 +2101,10 @@ export default function TaskPageCore() {{t('completeTask')}</Button></div>- );+ )}-- return null;++ return null})()}</div>) : !acceptedTaskDetailLoading && (@@ -1986,7 +2124,7 @@ export default function TaskPageCore() {footer={[<Button key="close" onClick={handleCloseMediaPreview}>{t('modal.close')}- </Button>+ </Button>,]}width={previewMedia?.type === 'video' ? 800 : 600}zIndex={3000}@@ -1994,8 +2132,8 @@ export default function TaskPageCore() {styles={{body: {padding: '24px',- textAlign: 'center'- }+ textAlign: 'center',+ },}}>{previewMedia && (@@ -2008,13 +2146,13 @@ export default function TaskPageCore() {style={{width: '100%',maxHeight: '500px',- borderRadius: '8px'+ borderRadius: '8px',}}autoPlayonEnded={() => {// 视频播放结束时重置到开始if (videoRef) {- videoRef.currentTime = 0;+ videoRef.currentTime = 0}}}/>@@ -2026,7 +2164,7 @@ export default function TaskPageCore() {width: '100%',maxHeight: '500px',objectFit: 'contain',- borderRadius: '8px'+ borderRadius: '8px',}}/>)}@@ -2045,8 +2183,8 @@ export default function TaskPageCore() {zIndex={3000}styles={{body: {- padding: '24px'- }+ padding: '24px',+ },}}><Steps@@ -2055,10 +2193,13 @@ export default function TaskPageCore() {items={taskProgress.steps.map((step, index) => ({title: step.title,status: step.status as 'wait' | 'process' | 'finish' | 'error',- description: index === 0 ? (step.title.includes(t('completeTask' as any)) ? t('messages.taskProcessFailed') : t('messages.taskProcessFailed')) :- index === 1 ? t('messages.taskProcessFailed') :- index === 2 ? t('messages.taskProcessFailed') :- t('messages.taskProcessFailed')+ description: index === 0+ ? (step.title.includes(t('completeTask' as any)) ? t('messages.taskProcessFailed') : t('messages.taskProcessFailed'))+ : index === 1+ ? t('messages.taskProcessFailed')+ : index === 2+ ? t('messages.taskProcessFailed')+ : t('messages.taskProcessFailed'),}))}/></Modal>@@ -2074,11 +2215,11 @@ export default function TaskPageCore() {styles={{header: {borderBottom: '1px solid #f0f0f0',- paddingBottom: '16px'+ paddingBottom: '16px',},body: {- padding: '24px'- }+ padding: '24px',+ },}}><div style={{ marginBottom: '16px' }}>@@ -2088,7 +2229,7 @@ export default function TaskPageCore() {</div><ListdataSource={availableAccounts}- renderItem={(account) => (+ renderItem={account => (<List.Itemstyle={{padding: '16px',@@ -2096,20 +2237,20 @@ export default function TaskPageCore() {borderRadius: '8px',marginBottom: '8px',cursor: 'pointer',- transition: 'all 0.3s ease'+ transition: 'all 0.3s ease',}}onMouseEnter={(e) => {- e.currentTarget.style.borderColor = '#1890ff';- e.currentTarget.style.backgroundColor = '#f6ffed';+ e.currentTarget.style.borderColor = '#1890ff'+ e.currentTarget.style.backgroundColor = '#f6ffed'}}onMouseLeave={(e) => {- e.currentTarget.style.borderColor = '#f0f0f0';- e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.borderColor = '#f0f0f0'+ e.currentTarget.style.backgroundColor = 'transparent'}}onClick={() => handleAccountSelect(account)}><List.Item.Meta- avatar={+ avatar={(<imgsrc={account.avatar ? getOssUrl(account.avatar) : '/default-avatar.png'}alt="账号头像"@@ -2117,25 +2258,35 @@ export default function TaskPageCore() {width: '48px',height: '48px',borderRadius: '50%',- objectFit: 'cover'+ objectFit: 'cover',}}onError={(e) => {- e.currentTarget.src = '/default-avatar.png';+ e.currentTarget.src = '/default-avatar.png'}}/>- }- title={+ )}+ title={(<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><span style={{ fontWeight: '500' }}>{account.nickname}</span><Tag color="blue">{getPlatformName(account.type)}</Tag></div>- }- description={+ )}+ description={(<div style={{ color: '#666' }}>- <div>{t('accountSelect.accountId' as any)}: {account.account}</div>- {account.nickname && <div>昵称: {account.nickname}</div>}+ <div>+ {t('accountSelect.accountId' as any)}+ :+ {' '}+ {account.account}+ </div>+ {account.nickname && (+ <div>+ 昵称:+ {account.nickname}+ </div>+ )}</div>- }+ )}/></List.Item>)}@@ -2153,5 +2304,5 @@ export default function TaskPageCore() {zIndex={3000}/></div>- );+ )}diff --git a/project/web/src/app/[lng]/vip/page.tsx b/project/web/src/app/[lng]/vip/page.tsxindex ee21ed1b..0d367aeb 100644--- a/project/web/src/app/[lng]/vip/page.tsx+++ b/project/web/src/app/[lng]/vip/page.tsx@@ -1,30 +1,30 @@-"use client";+'use client'-import { useState, useEffect } from "react";-import { CrownOutlined, TrophyOutlined, GiftOutlined, StarOutlined, RocketOutlined, DollarOutlined, HistoryOutlined, ThunderboltOutlined } from "@ant-design/icons";-import { message } from "antd";-import { useRouter } from "next/navigation";-import { createPaymentOrderApi, PaymentType } from "@/api/vip";-import { useUserStore } from "@/store/user";-import styles from "./vip.module.css";-import { useTransClient } from "@/app/i18n/client";+import { CrownOutlined, DollarOutlined, GiftOutlined, HistoryOutlined, RocketOutlined, StarOutlined, ThunderboltOutlined, TrophyOutlined } from '@ant-design/icons'+import { message } from 'antd'+import { useRouter } from 'next/navigation'+import { useEffect, useState } from 'react'+import { createPaymentOrderApi, PaymentType } from '@/api/vip'+import { useTransClient } from '@/app/i18n/client'+import { useUserStore } from '@/store/user'+import styles from './vip.module.css'export default function VipPage() {- const router = useRouter();- const { userInfo, lang } = useUserStore();- const { t } = useTransClient('vip');- const [selectedPlan, setSelectedPlan] = useState('month'); // 默认选择连续月费会员- const [loading, setLoading] = useState(false);- const [canUseTrial, setCanUseTrial] = useState(false); // 是否可以使用免费试用+ const router = useRouter()+ const { userInfo, lang } = useUserStore()+ const { t } = useTransClient('vip')+ const [selectedPlan, setSelectedPlan] = useState('month') // 默认选择连续月费会员+ const [loading, setLoading] = useState(false)+ const [canUseTrial, setCanUseTrial] = useState(false) // 是否可以使用免费试用// 检查用户是否可以享受免费试用useEffect(() => {if (userInfo) {// 如果用户没有vipInfo,说明从未开过会员,可以享受免费试用- const hasVipInfo = userInfo.vipInfo && Object.keys(userInfo.vipInfo).length > 0;- setCanUseTrial(!hasVipInfo);+ const hasVipInfo = userInfo.vipInfo && Object.keys(userInfo.vipInfo).length > 0+ setCanUseTrial(!hasVipInfo)}- }, [userInfo]);+ }, [userInfo])// 会员权益数据 (8个)const vipBenefits = [@@ -36,76 +36,80 @@ export default function VipPage() {{ icon: <HistoryOutlined />, name: t('vipBenefits.unlimitedTime') },{ icon: <ThunderboltOutlined />, name: t('vipBenefits.fastExperience') },{ icon: <RocketOutlined />, name: t('vipBenefits.morePrivileges') },- ];+ ]const handleActivate = async () => {try {- setLoading(true);-+ setLoading(true)+// 检查用户是否已登录if (!userInfo?.id) {- message.error(t('pleaseLoginFirst'));- router.push('/login');- return;+ message.error(t('pleaseLoginFirst'))+ router.push('/login')+ return}// 根据选择的计划映射到支付类型- let paymentType;- let paymentMethod;- let flagTrialPeriodDays = 0; // 默认不给免费试用+ let paymentType+ let paymentMethod+ let flagTrialPeriodDays = 0 // 默认不给免费试用switch (selectedPlan) {case 'onceMonth':- paymentType = PaymentType.ONCE_MONTH;- paymentMethod = 'payment';- break;+ paymentType = PaymentType.ONCE_MONTH+ paymentMethod = 'payment'+ breakcase 'month':- paymentType = PaymentType.MONTH;- paymentMethod = 'subscription';+ paymentType = PaymentType.MONTH+ paymentMethod = 'subscription'// 如果是订阅模式且用户从未开过会员,给免费试用- flagTrialPeriodDays = canUseTrial ? 1 : 0;- break;+ flagTrialPeriodDays = canUseTrial ? 1 : 0+ breakcase 'year':- paymentType = PaymentType.YEAR;- paymentMethod = 'subscription';+ paymentType = PaymentType.YEAR+ paymentMethod = 'subscription'// 如果是订阅模式且用户从未开过会员,给免费试用- flagTrialPeriodDays = canUseTrial ? 1 : 0;- break;+ flagTrialPeriodDays = canUseTrial ? 1 : 0+ breakdefault:- paymentType = PaymentType.MONTH;- paymentMethod = 'subscription';- flagTrialPeriodDays = canUseTrial ? 1 : 0;+ paymentType = PaymentType.MONTH+ paymentMethod = 'subscription'+ flagTrialPeriodDays = canUseTrial ? 1 : 0}-+// 创建支付订单const response: any = await createPaymentOrderApi({- returnTo: lang === 'zh-CN' ? "https://aitoearn.ai/zh-CN/profile" : "https://aitoearn.ai/en/profile",+ returnTo: lang === 'zh-CN' ? 'https://aitoearn.ai/zh-CN/profile' : 'https://aitoearn.ai/en/profile',mode: paymentMethod,payment: paymentType,metadata: {- userId: userInfo.id- }- });-+ userId: userInfo.id,+ },+ })+if (response?.code === 0) {- message.success(t('paymentOrderCreated'));+ message.success(t('paymentOrderCreated'))// 直接跳转到支付页面if (response.data?.url) {// window.location.href = response.data.url;- window.open(response.data.url, '_blank');- } else {- message.error(t('paymentLinkNotFound'));+ window.open(response.data.url, '_blank')}- } else {- message.error(response?.message || response?.msg || t('createPaymentOrderFailed'));+ else {+ message.error(t('paymentLinkNotFound'))+ }+ }+ else {+ message.error(response?.message || response?.msg || t('createPaymentOrderFailed'))}- } catch (error) {- console.error('创建支付订单失败:', error);- message.error(t('createPaymentOrderError'));- } finally {- setLoading(false);}- };+ catch (error) {+ console.error('创建支付订单失败:', error)+ message.error(t('createPaymentOrderError'))+ }+ finally {+ setLoading(false)+ }+ }return (<div className={styles.container}>@@ -130,7 +134,7 @@ export default function VipPage() {</div><h3 className={styles.title}>{t('selectDuration')}</h3>-+{/* 免费试用提示 */}{canUseTrial && (<div className={styles.trialNotice}>@@ -140,8 +144,8 @@ export default function VipPage() {)}<div className={styles.priceOptions}>-- <div++ <divclassName={`${styles.priceCard} ${selectedPlan === 'month' ? styles.selected : ''}`}onClick={() => setSelectedPlan('month')}>@@ -155,12 +159,16 @@ export default function VipPage() {{canUseTrial ? t('badge.month') : t('badge.monthOld')}</span></div>- <p className={styles.currentPrice}>$<span>19</span>{t('priceUnits.month')}</p>+ <p className={styles.currentPrice}>+ $+ <span>19</span>+ {t('priceUnits.month')}+ </p>{canUseTrial && (<p className={styles.trialText}>{t('trialText.month')}</p>)}</div>- <div+ <divclassName={`${styles.priceCard} ${selectedPlan === 'year' ? styles.selected : ''}`}onClick={() => setSelectedPlan('year')}>@@ -174,13 +182,20 @@ export default function VipPage() {{canUseTrial ? t('badge.year') : t('badge.yearOld')}</span></div>- <p className={styles.currentPrice}>$<span>12</span>{t('priceUnits.month')}</p>- <p className={styles.monthlyPrice}>$144{t('priceUnits.year')}</p>+ <p className={styles.currentPrice}>+ $+ <span>12</span>+ {t('priceUnits.month')}+ </p>+ <p className={styles.monthlyPrice}>+ $144+ {t('priceUnits.year')}+ </p>{canUseTrial && (<p className={styles.trialText}>{t('trialText.year')}</p>)}</div>- <div+ <divclassName={`${styles.priceCard} ${selectedPlan === 'onceMonth' ? styles.selected : ''}`}onClick={() => setSelectedPlan('onceMonth')}>@@ -190,19 +205,22 @@ export default function VipPage() {<span className={styles.originalPrice}>$30</span><span className={styles.discount}>{t('badge.onceMonth')}</span></div>- <p className={styles.currentPrice}>$<span>25</span></p>+ <p className={styles.currentPrice}>+ $+ <span>25</span>+ </p></div></div>-+<p className={styles.subscriptionInfo}>{t('autoRenewal')}</p>- <button- className={styles.activateButton}+ <button+ className={styles.activateButton}onClick={handleActivate}disabled={loading}>{t('activateNow')}</button></div>- );-}\ No newline at end of file+ )+}diff --git a/project/web/src/app/[lng]/vip/vip.module.css b/project/web/src/app/[lng]/vip/vip.module.cssindex ffb663c4..0f4d4885 100644--- a/project/web/src/app/[lng]/vip/vip.module.css+++ b/project/web/src/app/[lng]/vip/vip.module.css@@ -75,7 +75,7 @@left: 0;right: 0;bottom: 0;- background: linear-gradient(to right, #2B2F36, #4E4C4D);+ background: linear-gradient(to right, #2b2f36, #4e4c4d);z-index: 0;border-radius: 12px;}@@ -243,4 +243,4 @@color: #666;margin-top: 8px;font-style: italic;-}\ No newline at end of file+}diff --git a/project/web/src/app/[lng]/wallet/page.tsx b/project/web/src/app/[lng]/wallet/page.tsxindex e3213ec2..ad4cd24c 100644--- a/project/web/src/app/[lng]/wallet/page.tsx+++ b/project/web/src/app/[lng]/wallet/page.tsx@@ -1,146 +1,149 @@-"use client";+'use client'-import { useEffect, useMemo, useState } from "react";-import { Button, Card, Form, Input, Modal, Select, Table, message, Popconfirm } from "antd";-import { useTransClient } from "@/app/i18n/client";-import { useParams } from "next/navigation";-import { useUserStore } from "@/store/user";+import type {+ UserWalletAccount,+ UserWalletAccountCreateDto,+} from '@/api/userWalletAccount'+import { Button, Card, Form, Input, message, Modal, Popconfirm, Select, Table } from 'antd'+import { useParams } from 'next/navigation'+import { useEffect, useMemo, useState } from 'react'import {createUserWalletAccount,deleteUserWalletAccount,+ EMAIL_REGEX,getUserWalletAccountList,updateUserWalletAccount,- EMAIL_REGEX,- UserWalletAccount,- UserWalletAccountCreateDto,-} from "@/api/userWalletAccount";+} from '@/api/userWalletAccount'+import { useTransClient } from '@/app/i18n/client'+import { useUserStore } from '@/store/user'-const { Option } = Select;+const { Option } = Selectexport default function WalletPage() {- const { t } = useTransClient("wallet");- const { lng } = useParams();- const { userInfo } = useUserStore();+ const { t } = useTransClient('wallet')+ const { lng } = useParams()+ const { userInfo } = useUserStore()- const [list, setList] = useState<UserWalletAccount[]>([]);- const [loading, setLoading] = useState(false);- const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });+ const [list, setList] = useState<UserWalletAccount[]>([])+ const [loading, setLoading] = useState(false)+ const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 })- const [form] = Form.useForm<UserWalletAccountCreateDto>();- const [modalOpen, setModalOpen] = useState(false);- const [editing, setEditing] = useState<UserWalletAccount | null>(null);- const [submitting, setSubmitting] = useState(false);+ const [form] = Form.useForm<UserWalletAccountCreateDto>()+ const [modalOpen, setModalOpen] = useState(false)+ const [editing, setEditing] = useState<UserWalletAccount | null>(null)+ const [submitting, setSubmitting] = useState(false)const columns = useMemo(() => [- {- title: t("columns.userName"),- dataIndex: "userName",- key: "userName",+ {+ title: t('columns.userName'),+ dataIndex: 'userName',+ key: 'userName',width: 100,- ellipsis: true+ ellipsis: true,},- {- title: t("columns.mail"),- dataIndex: "mail",- key: "mail",+ {+ title: t('columns.mail'),+ dataIndex: 'mail',+ key: 'mail',width: 150,ellipsis: true,- responsive: ['md'] as any+ responsive: ['md'] as any,},- {- title: t("columns.account"),- dataIndex: "account",- key: "account",+ {+ title: t('columns.account'),+ dataIndex: 'account',+ key: 'account',width: 120,- ellipsis: true+ ellipsis: true,},- {- title: t("columns.type"),- dataIndex: "type",- key: "type",+ {+ title: t('columns.type'),+ dataIndex: 'type',+ key: 'type',width: 80,- render: (v: string) => (v === "ZFB" ? t("types.ZFB") : t("types.WX_PAY"))+ render: (v: string) => (v === 'ZFB' ? t('types.ZFB') : t('types.WX_PAY')),},- {- title: t("columns.phone"),- dataIndex: "phone",- key: "phone",+ {+ title: t('columns.phone'),+ dataIndex: 'phone',+ key: 'phone',width: 120,ellipsis: true,- responsive: ['lg'] as any+ responsive: ['lg'] as any,},- {- title: t("columns.cardNum"),- dataIndex: "cardNum",- key: "cardNum",+ {+ title: t('columns.cardNum'),+ dataIndex: 'cardNum',+ key: 'cardNum',width: 120,ellipsis: true,- responsive: ['lg'] as any+ responsive: ['lg'] as any,},{- title: t("columns.actions"),- key: "actions",+ title: t('columns.actions'),+ key: 'actions',width: 120,fixed: 'right' as any,render: (_: any, record: UserWalletAccount) => (<div style={{ display: 'flex', flexDirection: 'row', gap: '4px' }}>- <Button- size="small"- type="link"+ <Button+ size="small"+ type="link"onClick={() => onEdit(record)}style={{ padding: '2px 4px', fontSize: '11px' }}>- {t("actions.edit")}+ {t('actions.edit')}</Button>- <Popconfirm- title={t("actions.deleteConfirm")}+ <Popconfirm+ title={t('actions.deleteConfirm')}onConfirm={() => onDelete(record)}- okText={t("actions.confirm" as any)}- cancelText={t("actions.cancel" as any)}+ okText={t('actions.confirm' as any)}+ cancelText={t('actions.cancel' as any)}>- <Button- size="small"- type="link"+ <Button+ size="small"+ type="link"dangerstyle={{ padding: '2px 4px', fontSize: '11px' }}>- {t("actions.delete")}+ {t('actions.delete')}</Button></Popconfirm></div>- )- }+ ),+ },],- [t]- );+ [t],+ )useEffect(() => {- fetchList(1, 10);- }, []);+ fetchList(1, 10)+ }, [])async function fetchList(pageNo: number, pageSize: number) {- setLoading(true);+ setLoading(true)try {- const res = await getUserWalletAccountList(pageNo, pageSize);+ const res = await getUserWalletAccountList(pageNo, pageSize)if (res?.data) {- setList(res.data.list || []);- setPagination({ current: pageNo, pageSize, total: res.data.total || 0 });+ setList(res.data.list || [])+ setPagination({ current: pageNo, pageSize, total: res.data.total || 0 })}- } finally {- setLoading(false);+ }+ finally {+ setLoading(false)}}function openCreate() {- setEditing(null);- form.resetFields();- form.setFieldsValue({ userId: userInfo?._id || "" } as any);- setModalOpen(true);+ setEditing(null)+ form.resetFields()+ form.setFieldsValue({ userId: userInfo?._id || '' } as any)+ setModalOpen(true)}function onEdit(record: UserWalletAccount) {- setEditing(record);+ setEditing(record)form.setFieldsValue({userId: record.userId,mail: record.mail,@@ -149,62 +152,67 @@ export default function WalletPage() {cardNum: record.cardNum,phone: record.phone,type: record.type,- });- setModalOpen(true);+ })+ setModalOpen(true)}async function onDelete(record: UserWalletAccount) {- const res = await deleteUserWalletAccount(record._id);+ const res = await deleteUserWalletAccount(record._id)if (res) {- message.success(t("messages.deleteSuccess"));- fetchList(pagination.current, pagination.pageSize);+ message.success(t('messages.deleteSuccess'))+ fetchList(pagination.current, pagination.pageSize)}}async function onSubmit() {try {- const values = await form.validateFields();- setSubmitting(true);+ const values = await form.validateFields()+ setSubmitting(true)if (editing) {- const res = await updateUserWalletAccount(editing._id, values);- if (res) message.success(t("messages.updateSuccess"));- } else {- const res = await createUserWalletAccount(values);- if (res) message.success(t("messages.createSuccess"));+ const res = await updateUserWalletAccount(editing._id, values)+ if (res)+ message.success(t('messages.updateSuccess'))}- setModalOpen(false);- fetchList(pagination.current, pagination.pageSize);- } finally {- setSubmitting(false);+ else {+ const res = await createUserWalletAccount(values)+ if (res)+ message.success(t('messages.createSuccess'))+ }+ setModalOpen(false)+ fetchList(pagination.current, pagination.pageSize)+ }+ finally {+ setSubmitting(false)}}return (- <div style={{- padding: '16px',+ <div style={{+ padding: '16px',minHeight: '100vh',- backgroundColor: '#f5f5f5'- }}>- <Card- title={t("title")}- extra={- <Button- type="primary"+ backgroundColor: '#f5f5f5',+ }}+ >+ <Card+ title={t('title')}+ extra={(+ <Button+ type="primary"onClick={openCreate}size="small"- style={{+ style={{fontSize: '12px',height: '32px',- padding: '4px 12px'+ padding: '4px 12px',}}>- {t("actions.create")}+ {t('actions.create')}</Button>- }+ )}style={{margin: '0 auto',maxWidth: '100%',- boxShadow: '0 2px 8px rgba(0,0,0,0.1)'+ boxShadow: '0 2px 8px rgba(0,0,0,0.1)',}}><Table@@ -220,67 +228,65 @@ export default function WalletPage() {total: pagination.total,showSizeChanger: false,showQuickJumper: false,- showTotal: (total, range) =>+ showTotal: (total, range) =>`${range[0]}-${range[1]} / ${total}`,onChange: (p, s) => fetchList(p, s || 10),simple: true,pageSizeOptions: ['5', '10', '20'],- responsive: true+ responsive: true,}}style={{- fontSize: '12px'+ fontSize: '12px',}}/></Card><Modalopen={modalOpen}- title={editing ? t("dialogs.editTitle") : t("dialogs.createTitle")}+ title={editing ? t('dialogs.editTitle') : t('dialogs.createTitle')}onCancel={() => setModalOpen(false)}onOk={onSubmit}confirmLoading={submitting}destroyOnHiddenwidth="90%"- style={{+ style={{maxWidth: '500px',- top: '20px'+ top: '20px',}}bodyStyle={{maxHeight: '70vh',overflowY: 'auto',- padding: '16px'+ padding: '16px',}}centered><Form form={form} layout="vertical" preserve={false}>- <Form.Item name="userId" label={t("form.userId")} rules={[{ required: true, message: t("form.required") }]}>- <Input disabled placeholder={t("form.userIdPlaceholder")} />+ <Form.Item name="userId" label={t('form.userId')} rules={[{ required: true, message: t('form.required') }]}>+ <Input disabled placeholder={t('form.userIdPlaceholder')} /></Form.Item>- <Form.Item name="mail" label={t("form.mail")} rules={[{ required: true, pattern: EMAIL_REGEX, message: t("form.mailInvalid") }]}>- <Input placeholder={t("form.mailPlaceholder")} />+ <Form.Item name="mail" label={t('form.mail')} rules={[{ required: true, pattern: EMAIL_REGEX, message: t('form.mailInvalid') }]}>+ <Input placeholder={t('form.mailPlaceholder')} /></Form.Item>- <Form.Item name="userName" label={t("form.userName")}>- <Input placeholder={t("form.userNamePlaceholder")} />+ <Form.Item name="userName" label={t('form.userName')}>+ <Input placeholder={t('form.userNamePlaceholder')} /></Form.Item>- <Form.Item name="account" label={t("form.account")} rules={[{ required: true, message: t("form.required") }]}>- <Input placeholder={t("form.accountPlaceholder")} />+ <Form.Item name="account" label={t('form.account')} rules={[{ required: true, message: t('form.required') }]}>+ <Input placeholder={t('form.accountPlaceholder')} /></Form.Item>- <Form.Item name="cardNum" label={t("form.cardNum")}>- <Input placeholder={t("form.cardNumPlaceholder")} />+ <Form.Item name="cardNum" label={t('form.cardNum')}>+ <Input placeholder={t('form.cardNumPlaceholder')} /></Form.Item>- <Form.Item name="phone" label={t("form.phone")}>- <Input placeholder={t("form.phonePlaceholder")} />+ <Form.Item name="phone" label={t('form.phone')}>+ <Input placeholder={t('form.phonePlaceholder')} /></Form.Item>- <Form.Item name="type" label={t("form.type")} rules={[{ required: true, message: t("form.required") }]}>- <Select placeholder={t("form.typePlaceholder")}>- <Option value="ZFB">{t("types.ZFB")}</Option>- <Option value="WX_PAY">{t("types.WX_PAY")}</Option>+ <Form.Item name="type" label={t('form.type')} rules={[{ required: true, message: t('form.required') }]}>+ <Select placeholder={t('form.typePlaceholder')}>+ <Option value="ZFB">{t('types.ZFB')}</Option>+ <Option value="WX_PAY">{t('types.WX_PAY')}</Option></Select></Form.Item></Form></Modal></div>- );+ )}--diff --git a/project/web/src/app/[lng]/websit/data-deletion/page.tsx b/project/web/src/app/[lng]/websit/data-deletion/page.tsxindex 38d58876..bc9f1d76 100644--- a/project/web/src/app/[lng]/websit/data-deletion/page.tsx+++ b/project/web/src/app/[lng]/websit/data-deletion/page.tsx@@ -1,12 +1,12 @@-"use client";+'use client'-import { useTransClient } from "@/app/i18n/client";-import styles from "../websit.module.scss";+import { useTransClient } from '@/app/i18n/client'+import styles from '../websit.module.scss'// 导入首页的Header组件function Header() {- const { t } = useTransClient('home');-+ const { t } = useTransClient('home')+return (<header className={styles.header}><div className={styles.headerContainer}>@@ -22,14 +22,14 @@ function Header() {<button className={styles.getStartedBtn}>{t('header.getStarted')}</button></div></header>- );+ )}export default function DataDeletionPage() {return (<div className={styles.websitPage}><Header />-+<main className={styles.main}><div className={styles.container}><div className={styles.header}>@@ -40,16 +40,16 @@ export default function DataDeletionPage() {Last Updated: 2025.6.27</p></div>-+<div className={styles.content}><section className={styles.section}><h2 className={styles.sectionTitle}>For Pre-Launch Users:</h2><p className={styles.sectionContent}>- Our application is currently in pre-launch phase and does not store real user data.+ Our application is currently in pre-launch phase and does not store real user data.If you have interacted with our test systems, contact us for data removal.</p></section>-+<section className={styles.section}><h2 className={styles.sectionTitle}>Standard Procedure (Post-Launch):</h2><ol className={styles.stepsList}>@@ -71,17 +71,19 @@ export default function DataDeletionPage() {</li></ol></section>-+<section className={styles.section}><h2 className={styles.sectionTitle}>Contact for Assistance:</h2><div className={styles.contactInfo}><h3 className={styles.contactTitle}>Pre-launch inquiries only</h3><p className={styles.contactText}>- <strong>Email:</strong> [email protected]+ <strong>Email:</strong>+ {' '}</p></div></section>-+<section className={styles.section}><div className={styles.warningBox}><h3 className={styles.warningTitle}>Important Note:</h3>@@ -94,5 +96,5 @@ export default function DataDeletionPage() {</div></main></div>- );-}\ No newline at end of file+ )+}diff --git a/project/web/src/app/[lng]/websit/data-protection-agreement/page.tsx b/project/web/src/app/[lng]/websit/data-protection-agreement/page.tsxindex 6cf904cd..171b6a7e 100644--- a/project/web/src/app/[lng]/websit/data-protection-agreement/page.tsx+++ b/project/web/src/app/[lng]/websit/data-protection-agreement/page.tsx@@ -1,12 +1,12 @@-"use client";+'use client'-import { useTransClient } from "@/app/i18n/client";-import styles from "../websit.module.scss";+import { useTransClient } from '@/app/i18n/client'+import styles from '../websit.module.scss'// 导入首页的Header组件function Header() {- const { t } = useTransClient('home');-+ const { t } = useTransClient('home')+return (<header className={styles.header}><div className={styles.headerContainer}>@@ -22,14 +22,14 @@ function Header() {<button className={styles.getStartedBtn}>{t('header.getStarted')}</button></div></header>- );+ )}export default function DataProtectionAgreementPage() {return (<div className={styles.websitPage}><Header />-+<main className={styles.main}><div className={styles.container}><div className={styles.header}>@@ -40,14 +40,14 @@ export default function DataProtectionAgreementPage() {Last Updated: 2024-12-26</p></div>-+<div className={styles.content}><section className={styles.section}><p className={styles.introduction}>This Data Protection Agreement outlines how we handle, protect, and process your personal data in compliance with applicable data protection laws, including the General Data Protection Regulation (GDPR) and other relevant privacy regulations.</p></section>-+<section className={styles.section}><h2 className={styles.sectionTitle}>1. Data Controller Information</h2><p className={styles.sectionContent}>@@ -56,25 +56,51 @@ export default function DataProtectionAgreementPage() {<div className={styles.contactInfo}><h3 className={styles.contactTitle}>Contact Information</h3><p className={styles.contactText}>- Email: [email protected]<br/>- Address: [Company Address]<br/>+ Email: [email protected]+ <br />+ Address: [Company Address]+ <br />Data Protection Officer: [email protected]</p></div></section>-+<section className={styles.section}><h2 className={styles.sectionTitle}>2. Types of Data We Collect</h2><p className={styles.sectionContent}>We collect and process the following categories of personal data:</p><ul className={styles.listContent}>- <li><strong>Account Information:</strong> Name, email address, username, password</li>- <li><strong>Profile Data:</strong> Profile pictures, bio information, social media links</li>- <li><strong>Content Data:</strong> Posts, comments, media files, scheduling information</li>- <li><strong>Usage Data:</strong> Platform interactions, feature usage, analytics data</li>- <li><strong>Technical Data:</strong> IP address, device information, browser type, session data</li>- <li><strong>Communication Data:</strong> Support tickets, feedback, correspondence</li>+ <li>+ <strong>Account Information:</strong>+ {' '}+ Name, email address, username, password+ </li>+ <li>+ <strong>Profile Data:</strong>+ {' '}+ Profile pictures, bio information, social media links+ </li>+ <li>+ <strong>Content Data:</strong>+ {' '}+ Posts, comments, media files, scheduling information+ </li>+ <li>+ <strong>Usage Data:</strong>+ {' '}+ Platform interactions, feature usage, analytics data+ </li>+ <li>+ <strong>Technical Data:</strong>+ {' '}+ IP address, device information, browser type, session data+ </li>+ <li>+ <strong>Communication Data:</strong>+ {' '}+ Support tickets, feedback, correspondence+ </li></ul></section>@@ -84,10 +110,26 @@ export default function DataProtectionAgreementPage() {We process your personal data based on the following legal grounds:</p><ul className={styles.listContent}>- <li><strong>Contract Performance:</strong> To provide our services and fulfill our contractual obligations</li>- <li><strong>Legitimate Interest:</strong> To improve our services, prevent fraud, and ensure security</li>- <li><strong>Consent:</strong> For marketing communications and optional features (where required)</li>- <li><strong>Legal Obligation:</strong> To comply with applicable laws and regulations</li>+ <li>+ <strong>Contract Performance:</strong>+ {' '}+ To provide our services and fulfill our contractual obligations+ </li>+ <li>+ <strong>Legitimate Interest:</strong>+ {' '}+ To improve our services, prevent fraud, and ensure security+ </li>+ <li>+ <strong>Consent:</strong>+ {' '}+ For marketing communications and optional features (where required)+ </li>+ <li>+ <strong>Legal Obligation:</strong>+ {' '}+ To comply with applicable laws and regulations+ </li></ul></section>@@ -97,10 +139,26 @@ export default function DataProtectionAgreementPage() {We may share your personal data with:</p><ul className={styles.listContent}>- <li><strong>Service Providers:</strong> Cloud hosting, analytics, payment processing, customer support</li>- <li><strong>Social Media Platforms:</strong> When you connect and publish content to external platforms</li>- <li><strong>Legal Authorities:</strong> When required by law or to protect our legal rights</li>- <li><strong>Business Partners:</strong> With your explicit consent for specific integrations</li>+ <li>+ <strong>Service Providers:</strong>+ {' '}+ Cloud hosting, analytics, payment processing, customer support+ </li>+ <li>+ <strong>Social Media Platforms:</strong>+ {' '}+ When you connect and publish content to external platforms+ </li>+ <li>+ <strong>Legal Authorities:</strong>+ {' '}+ When required by law or to protect our legal rights+ </li>+ <li>+ <strong>Business Partners:</strong>+ {' '}+ With your explicit consent for specific integrations+ </li></ul><p className={styles.sectionContent}>We ensure all third parties maintain appropriate data protection standards through contractual agreements.@@ -126,13 +184,41 @@ export default function DataProtectionAgreementPage() {You have the following rights regarding your personal data:</p><ul className={styles.listContent}>- <li><strong>Right of Access:</strong> Request copies of your personal data</li>- <li><strong>Right to Rectification:</strong> Correct inaccurate or incomplete data</li>- <li><strong>Right to Erasure:</strong> Request deletion of your personal data</li>- <li><strong>Right to Restrict Processing:</strong> Limit how we use your data</li>- <li><strong>Right to Data Portability:</strong> Receive your data in a portable format</li>- <li><strong>Right to Object:</strong> Object to certain types of processing</li>- <li><strong>Right to Withdraw Consent:</strong> Withdraw consent for consent-based processing</li>+ <li>+ <strong>Right of Access:</strong>+ {' '}+ Request copies of your personal data+ </li>+ <li>+ <strong>Right to Rectification:</strong>+ {' '}+ Correct inaccurate or incomplete data+ </li>+ <li>+ <strong>Right to Erasure:</strong>+ {' '}+ Request deletion of your personal data+ </li>+ <li>+ <strong>Right to Restrict Processing:</strong>+ {' '}+ Limit how we use your data+ </li>+ <li>+ <strong>Right to Data Portability:</strong>+ {' '}+ Receive your data in a portable format+ </li>+ <li>+ <strong>Right to Object:</strong>+ {' '}+ Object to certain types of processing+ </li>+ <li>+ <strong>Right to Withdraw Consent:</strong>+ {' '}+ Withdraw consent for consent-based processing+ </li></ul></section>@@ -142,11 +228,31 @@ export default function DataProtectionAgreementPage() {We retain your personal data for different periods depending on the purpose:</p><ul className={styles.listContent}>- <li><strong>Account Data:</strong> Until account deletion plus 30 days for backup recovery</li>- <li><strong>Content Data:</strong> Until deletion by user or account termination</li>- <li><strong>Usage Analytics:</strong> Aggregated data retained for 2 years</li>- <li><strong>Legal/Compliance Data:</strong> As required by applicable laws</li>- <li><strong>Marketing Data:</strong> Until consent withdrawal or 3 years of inactivity</li>+ <li>+ <strong>Account Data:</strong>+ {' '}+ Until account deletion plus 30 days for backup recovery+ </li>+ <li>+ <strong>Content Data:</strong>+ {' '}+ Until deletion by user or account termination+ </li>+ <li>+ <strong>Usage Analytics:</strong>+ {' '}+ Aggregated data retained for 2 years+ </li>+ <li>+ <strong>Legal/Compliance Data:</strong>+ {' '}+ As required by applicable laws+ </li>+ <li>+ <strong>Marketing Data:</strong>+ {' '}+ Until consent withdrawal or 3 years of inactivity+ </li></ul></section>@@ -186,8 +292,10 @@ export default function DataProtectionAgreementPage() {<div className={styles.contactInfo}><h3 className={styles.contactTitle}>Data Protection Requests</h3><p className={styles.contactText}>- Email: [email protected]<br/>- Subject Line: Data Protection Request - [Type of Request]<br/>+ Email: [email protected]+ <br />+ Subject Line: Data Protection Request - [Type of Request]+ <br />Response Time: Within 30 days of receipt</p></div>@@ -222,9 +330,13 @@ export default function DataProtectionAgreementPage() {<div className={styles.contactInfo}><h3 className={styles.contactTitle}>Data Protection Inquiries</h3><p className={styles.contactText}>- For any questions about this Data Protection Agreement or our data processing practices:<br/><br/>- Email: [email protected]<br/>- Data Protection Officer: [email protected]<br/>+ For any questions about this Data Protection Agreement or our data processing practices:+ <br />+ <br />+ Email: [email protected]+ <br />+ Data Protection Officer: [email protected]+ <br />General Contact: [email protected]</p></div>@@ -233,5 +345,5 @@ export default function DataProtectionAgreementPage() {</div></main></div>- );-}\ No newline at end of file+ )+}diff --git a/project/web/src/app/[lng]/websit/privacy-policy/page.tsx b/project/web/src/app/[lng]/websit/privacy-policy/page.tsxindex e8eeccc8..9fe8bf50 100644--- a/project/web/src/app/[lng]/websit/privacy-policy/page.tsx+++ b/project/web/src/app/[lng]/websit/privacy-policy/page.tsx@@ -1,12 +1,12 @@-"use client";+'use client'-import { useTransClient } from "@/app/i18n/client";-import styles from "../websit.module.scss";+import { useTransClient } from '@/app/i18n/client'+import styles from '../websit.module.scss'// 导入首页的Header组件function Header() {- const { t } = useTransClient('home');-+ const { t } = useTransClient('home')+return (<header className={styles.header}><div className={styles.headerContainer}>@@ -22,14 +22,14 @@ function Header() {<button className={styles.getStartedBtn}>{t('header.getStarted')}</button></div></header>- );+ )}export default function PrivacyPolicyPage() {return (<div className={styles.websitPage}><Header />-+<main className={styles.main}><div className={styles.container}><div className={styles.header}>@@ -40,20 +40,20 @@ export default function PrivacyPolicyPage() {Last Updated: 2024-12-26</p></div>-+<div className={styles.content}><section className={styles.section}><p className={styles.introduction}>- Aitoearn provides this Privacy Policy to inform you of our policies and procedures regarding the collection, use, protection, and disclosure of Personal Information received from your use of this website, located at https://aitoearn.ai (“Site”), as well as all related websites including our subdomains, applications, browser extensions, and other services provided by us (collectively, together with the Site, our “Service”), and in connection with our customer, vendor, and partner relationships. This Privacy Policy also tells you about your rights and choices with respect to your Personal Information, and how you can reach us to update your contact information or get answers to questions you may have about our privacy practices.+ Aitoearn provides this Privacy Policy to inform you of our policies and procedures regarding the collection, use, protection, and disclosure of Personal Information received from your use of this website, located at https://aitoearn.ai (“Site”), as well as all related websites including our subdomains, applications, browser extensions, and other services provided by us (collectively, together with the Site, our “Service”), and in connection with our customer, vendor, and partner relationships. This Privacy Policy also tells you about your rights and choices with respect to your Personal Information, and how you can reach us to update your contact information or get answers to questions you may have about our privacy practices.</p><p className={styles.sectionContent}>- In addition to the activities described in this Privacy Policy, we may process Personal Information on behalf of our commercial customers when they use the Service. We process such Personal Information as a data processor of our commercial customers, which are the entities responsible for the data processing. To understand how a commercial customer processes your Personal Information, please refer to that customer’s privacy policy.+ In addition to the activities described in this Privacy Policy, we may process Personal Information on behalf of our commercial customers when they use the Service. We process such Personal Information as a data processor of our commercial customers, which are the entities responsible for the data processing. To understand how a commercial customer processes your Personal Information, please refer to that customer’s privacy policy.</p><p className={styles.sectionContent}>Registration with, use of, and access to the Service is subject to this Privacy Policy and our Terms of Use located at https://aitoearn.ai/en/websit/terms-of-service.</p></section>-+<section className={styles.section}><h2 className={styles.sectionTitle}>Table of Contents</h2><ul className={styles.listContent}>@@ -84,7 +84,7 @@ export default function PrivacyPolicyPage() {<section className={styles.section} id="section2"><h2 className={styles.sectionTitle}>2. Personal Information Provided by You</h2>-+<h3 className={styles.subSectionTitle}>Registration</h3><p className={styles.sectionContent}>If you desire to have access to certain restricted sections of the Site or request to receive marketing materials, you may be required to become a registered user, and to submit the following types of Personal Information to Aitoearn: your name, email address, phone number, full user name, password, city, and time zone.@@ -145,7 +145,7 @@ export default function PrivacyPolicyPage() {<section className={styles.section} id="section2b"><h2 className={styles.sectionTitle}>2b. Personal Information Automatically Obtained from Your Interactions with the Service</h2>-+<h3 className={styles.subSectionTitle}>Log Data</h3><p className={styles.sectionContent}>When you use our Service, our servers automatically record information that your browser sends whenever you visit a website ("Log Data"). This Log Data may include information such as your IP address, browser type or the domain from which you are visiting, the web-pages you visit, the search terms you use, and any advertisements on which you click.@@ -257,7 +257,6 @@ export default function PrivacyPolicyPage() {</p></section>-<section className={styles.section} id="section11"><h2 className={styles.sectionTitle}>10. How to Contact Us</h2><div className={styles.contactInfo}>@@ -266,8 +265,13 @@ export default function PrivacyPolicyPage() {Aitoearn Inc. is the entity responsible for the processing of your personal information. If you have any questions or comments regarding this privacy policy, or if you would like to exercise your rights to your personal information, you may contact us:</p><p className={styles.contactText}>- <strong>Email:</strong> [email protected]<br/>- <strong>Privacy Questions:</strong> [email protected]+ <strong>Email:</strong>+ {' '}+ <br />+ <strong>Privacy Questions:</strong>+ {' '}</p><p className={styles.contactText}>If you have any thoughts or questions about this privacy policy please let us know at [email protected]@@ -278,5 +282,5 @@ export default function PrivacyPolicyPage() {</div></main></div>- );-}\ No newline at end of file+ )+}diff --git a/project/web/src/app/[lng]/websit/terms-of-service/page.tsx b/project/web/src/app/[lng]/websit/terms-of-service/page.tsxindex 66b37877..5ce3dfa8 100644--- a/project/web/src/app/[lng]/websit/terms-of-service/page.tsx+++ b/project/web/src/app/[lng]/websit/terms-of-service/page.tsx@@ -1,12 +1,12 @@-"use client";+'use client'-import { useTransClient } from "@/app/i18n/client";-import styles from "../websit.module.scss";+import { useTransClient } from '@/app/i18n/client'+import styles from '../websit.module.scss'// 导入首页的Header组件function Header() {- const { t } = useTransClient('home');-+ const { t } = useTransClient('home')+return (<header className={styles.header}><div className={styles.headerContainer}>@@ -22,14 +22,14 @@ function Header() {<button className={styles.getStartedBtn}>{t('header.getStarted')}</button></div></header>- );+ )}export default function TermsOfServicePage() {return (<div className={styles.websitPage}><Header />-+<main className={styles.main}><div className={styles.container}><div className={styles.header}>@@ -40,28 +40,31 @@ export default function TermsOfServicePage() {Last Updated: 2024-12-26</p></div>-+<div className={styles.content}><section className={styles.section}><p className={styles.introduction}>The following sets forth Aitoearn's Terms of Use. We know how tempting it is to skip these Terms of Use, but it's important to establish what you can expect from us as you use Aitoearn's Service, and what we expect from you. The Terms of Use is a binding legal document, and you are required to read and accept it in full in order to use our Service.</p></section>-+<section className={styles.section}><h2 className={styles.sectionTitle}>Aitoearn, Inc Terms of Use</h2><p className={styles.sectionContent}>Welcome, and thank you for your interest in Aitoearn, Inc. ("Aitoearn," "we," or "us") and our website at aitoearn.ai, along with our related websites, networks, hosted applications, mobile or other downloadable applications, and other services provided by us (collectively, the "Service"). These Terms of Use are a legally binding contract between you and Aitoearn regarding your use of the Service.</p><p className={styles.sectionContent}>- <strong>PLEASE READ THE FOLLOWING TERMS CAREFULLY:</strong><br/>+ <strong>PLEASE READ THE FOLLOWING TERMS CAREFULLY:</strong>+ <br />BY CLICKING "I ACCEPT,"OR BY DOWNLOADING, INSTALLING, OR OTHERWISE ACCESSING OR USING THE SERVICE, YOU AGREE THAT YOU HAVE READ AND UNDERSTOOD, AND, AS A CONDITION TO YOUR USE OF THE SERVICE, YOU AGREE TO BE BOUND BY, THE FOLLOWING TERMS AND CONDITIONS, INCLUDING Aitoearn'S PRIVACY POLICY https://aitoearn.ai/en/websit/privacy-policy AND ANY ADDITIONAL TERMS AND POLICIES Aitoearn MAY PROVIDE FROM TIME TO TIME (TOGETHER, THESE "TERMS").</p><p className={styles.sectionContent}>- <strong>Arbitration NOTICE.</strong> Except for certain kinds of disputes described in Section 14, you agree that disputes arising under these Terms will be resolved by binding, individual arbitration, and BY ACCEPTING THESE TERMS, YOU AND Aitoearn ARE EACH WAIVING THE RIGHT TO A TRIAL BY JURY OR TO PARTICIPATE IN ANY CLASS ACTION OR REPRESENTATIVE PROCEEDING.+ <strong>Arbitration NOTICE.</strong>+ {' '}+ Except for certain kinds of disputes described in Section 14, you agree that disputes arising under these Terms will be resolved by binding, individual arbitration, and BY ACCEPTING THESE TERMS, YOU AND Aitoearn ARE EACH WAIVING THE RIGHT TO A TRIAL BY JURY OR TO PARTICIPATE IN ANY CLASS ACTION OR REPRESENTATIVE PROCEEDING.</p></section>-+<section className={styles.section}><h2 className={styles.sectionTitle}>1. SERVICE AND ACCOUNT</h2><h3 className={styles.subSectionTitle}>1.1 Service Overview</h3>@@ -190,5 +193,5 @@ export default function TermsOfServicePage() {</div></main></div>- );-}\ No newline at end of file+ )+}diff --git a/project/web/src/app/[lng]/websit/websit.module.scss b/project/web/src/app/[lng]/websit/websit.module.scssindex d435846f..22a99953 100644--- a/project/web/src/app/[lng]/websit/websit.module.scss+++ b/project/web/src/app/[lng]/websit/websit.module.scss@@ -32,13 +32,13 @@.logoText {font-size: 24px;font-weight: bold;- color: #733DEC;+ color: #733dec;}.nav {display: flex;gap: 32px;-+@media (max-width: 768px) {display: none;}@@ -49,14 +49,14 @@text-decoration: none;font-weight: 500;transition: color 0.2s;-+&:hover {color: #111827;}}.getStartedBtn {- background: #733DEC;+ background: #733dec;color: white;border: none;padding: 10px 20px;@@ -64,7 +64,7 @@font-weight: 500;cursor: pointer;transition: background 0.2s;-+&:hover {background: #5b2bc7;}@@ -93,7 +93,7 @@font-weight: bold;color: #111827;margin-bottom: 16px;-+@media (max-width: 768px) {font-size: 36px;}@@ -119,7 +119,7 @@padding: 24px;background: #f9fafb;border-radius: 12px;- border-left: 4px solid #733DEC;+ border-left: 4px solid #733dec;}.sectionTitle {@@ -151,7 +151,7 @@}.stepNumber {- background: #733DEC;+ background: #733dec;color: white;width: 24px;height: 24px;@@ -221,20 +221,20 @@.listContent {margin: 16px 0;padding-left: 20px;-+li {color: #374151;font-size: 16px;margin-bottom: 8px;line-height: 1.6;-+a {- color: #733DEC;+ color: #733dec;text-decoration: none;transition: color 0.2s;-+&:hover {- color: #5B21B6;+ color: #5b21b6;text-decoration: underline;}}@@ -253,7 +253,7 @@font-size: 16px;line-height: 1.6;margin-bottom: 12px;-+strong {color: #111827;font-weight: 600;@@ -282,7 +282,7 @@padding: 16px;background: #f8fafc;border-radius: 8px;- border-left: 4px solid #733DEC;+ border-left: 4px solid #733dec;}.stepNumber {@@ -291,7 +291,7 @@justify-content: center;width: 32px;height: 32px;- background: #733DEC;+ background: #733dec;color: white;border-radius: 50%;font-weight: 600;@@ -320,4 +320,4 @@font-weight: 600;color: #92400e;margin-bottom: 8px;-}\ No newline at end of file+}diff --git a/project/web/src/app/config/appDownloadConfig.ts b/project/web/src/app/config/appDownloadConfig.tsindex 10dc126c..e64af430 100644--- a/project/web/src/app/config/appDownloadConfig.ts+++ b/project/web/src/app/config/appDownloadConfig.ts@@ -3,179 +3,179 @@* 管理不同平台的下载链接、二维码等信息*/+// 根据语言获取主应用下载地址+// zh-* 使用中文地址,其余使用英文地址+// 优先使用API返回的direct下载地址,如果获取失败则使用默认地址+import { useUserStore } from '@/store/user'+export interface AppDownloadConfig {- platform: string;- appName: string;- downloadUrl: string;- qrCodeUrl?: string;- description: string;- tips: string[];+ platform: string+ appName: string+ downloadUrl: string+ qrCodeUrl?: string+ description: string+ tips: string[]}// API响应类型定义interface AppReleaseResponse {data: {- _id: string;- platform: string;- version: string;- buildNumber: number;- forceUpdate: boolean;- notes: string;+ _id: string+ platform: string+ version: string+ buildNumber: number+ forceUpdate: boolean+ notes: stringlinks: {- direct?: string;- _id: string;- id: string;- };- publishedAt: string;- id: string;- };- code: number;- message: string;+ direct?: string+ _id: string+ id: string+ }+ publishedAt: string+ id: string+ }+ code: number+ message: string}// 主应用下载配置(默认英文)-export const MAIN_APP_DOWNLOAD_URL = "https://docs.aitoearn.ai/en/downloads";+export const MAIN_APP_DOWNLOAD_URL = 'https://docs.aitoearn.ai/en/downloads'// API端点-const APP_RELEASE_API = "https://aitoearn.ai/api/app-release/latest";+const APP_RELEASE_API = 'https://aitoearn.ai/api/app-release/latest'// 缓存最新下载地址-let cachedDownloadUrl: string | null = null;-let lastFetchTime: number = 0;-const CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存-let inflightRequest: Promise<string | null> | null = null;+let cachedDownloadUrl: string | null = null+let lastFetchTime: number = 0+const CACHE_DURATION = 5 * 60 * 1000 // 5分钟缓存+let inflightRequest: Promise<string | null> | null = null/*** 从API获取最新的Android应用下载地址* @returns 最新的下载地址,如果获取失败则返回null*/-export const fetchLatestDownloadUrl = async (): Promise<string | null> => {+export async function fetchLatestDownloadUrl(): Promise<string | null> {try {// 检查缓存- const now = Date.now();+ const now = Date.now()if (cachedDownloadUrl && (now - lastFetchTime) < CACHE_DURATION) {- return cachedDownloadUrl;+ return cachedDownloadUrl}// 如果存在进行中的请求,直接复用if (inflightRequest) {- return inflightRequest;+ return inflightRequest}inflightRequest = (async () => {- const response = await fetch(`${APP_RELEASE_API}?platform=android`);+ const response = await fetch(`${APP_RELEASE_API}?platform=android`)if (!response.ok) {- console.error('Failed to fetch app release info:', response.statusText);- return null;+ console.error('Failed to fetch app release info:', response.statusText)+ return null}- const result: AppReleaseResponse = await response.json();+ const result: AppReleaseResponse = await response.json()if (result.code === 0 && result.data?.links?.direct) {// 缓存下载地址- cachedDownloadUrl = result.data.links.direct;- lastFetchTime = now;- return cachedDownloadUrl;+ cachedDownloadUrl = result.data.links.direct+ lastFetchTime = now+ return cachedDownloadUrl}- return null;- })();+ return null+ })()- const data = await inflightRequest;- inflightRequest = null;- return data;- } catch (error) {- console.error('Error fetching latest download url:', error);- inflightRequest = null;- return null;+ const data = await inflightRequest+ inflightRequest = null+ return data}-};--// 根据语言获取主应用下载地址-// zh-* 使用中文地址,其余使用英文地址-// 优先使用API返回的direct下载地址,如果获取失败则使用默认地址-import { useUserStore } from "@/store/user";-export const getMainAppDownloadUrl = async (lng?: string): Promise<string> => {+ catch (error) {+ console.error('Error fetching latest download url:', error)+ inflightRequest = null+ return null+ }+}+export async function getMainAppDownloadUrl(lng?: string): Promise<string> {// 尝试从API获取最新下载地址- const latestUrl = await fetchLatestDownloadUrl();+ const latestUrl = await fetchLatestDownloadUrl()if (latestUrl) {- return latestUrl;+ return latestUrl}// 如果API获取失败,使用默认地址- const lang = (lng || useUserStore.getState().lang || "zh-CN").toLowerCase();- const isZh = lang.startsWith("zh");+ const lang = (lng || useUserStore.getState().lang || 'zh-CN').toLowerCase()+ const isZh = lang.startsWith('zh')return isZh- ? "https://docs.aitoearn.ai/zh/downloads"- : "https://docs.aitoearn.ai/en/downloads";-};+ ? 'https://docs.aitoearn.ai/zh/downloads'+ : 'https://docs.aitoearn.ai/en/downloads'+}/*** 同步获取主应用下载地址(用于不支持async的场景)* 会先返回缓存的URL,如果没有缓存则返回默认URL* 同时在后台触发API请求更新缓存*/-export const getMainAppDownloadUrlSync = (lng?: string): string => {+export function getMainAppDownloadUrlSync(lng?: string): string {// 后台更新缓存- fetchLatestDownloadUrl().catch(console.error);+ fetchLatestDownloadUrl().catch(console.error)// 如果有缓存,返回缓存的URLif (cachedDownloadUrl) {- return cachedDownloadUrl;+ return cachedDownloadUrl}// 否则返回默认URL- const lang = (lng || useUserStore.getState().lang || "zh-CN").toLowerCase();- const isZh = lang.startsWith("zh");+ const lang = (lng || useUserStore.getState().lang || 'zh-CN').toLowerCase()+ const isZh = lang.startsWith('zh')return isZh- ? "https://docs.aitoearn.ai/zh/downloads"- : "https://docs.aitoearn.ai/en/downloads";-};+ ? 'https://docs.aitoearn.ai/zh/downloads'+ : 'https://docs.aitoearn.ai/en/downloads'+}export const APP_DOWNLOAD_CONFIGS: Record<string, AppDownloadConfig> = {xhs: {- platform: "小红书",- appName: "小红书App",- downloadUrl: "https://apps.apple.com/cn/app/id123456789", // 这里配置实际的下载链接- qrCodeUrl: "", // 这里配置实际的二维码图片URL- description: "小红书相关操作需要在移动端App中进行,请下载并安装小红书App后继续操作。",+ platform: '小红书',+ appName: '小红书App',+ downloadUrl: 'https://apps.apple.com/cn/app/id123456789', // 这里配置实际的下载链接+ qrCodeUrl: '', // 这里配置实际的二维码图片URL+ description: '小红书相关操作需要在移动端App中进行,请下载并安装小红书App后继续操作。',tips: [- "安装完成后,请在App中登录您的账号",- "确保账号已通过实名认证",- "在App中完成相关任务操作"- ]+ '安装完成后,请在App中登录您的账号',+ '确保账号已通过实名认证',+ '在App中完成相关任务操作',+ ],},douyin: {- platform: "抖音",- appName: "抖音App",- downloadUrl: "https://apps.apple.com/cn/app/douyin/id123456789",- qrCodeUrl: "",- description: "抖音相关操作需要在移动端App中进行,请下载并安装抖音App后继续操作。",+ platform: '抖音',+ appName: '抖音App',+ downloadUrl: 'https://apps.apple.com/cn/app/douyin/id123456789',+ qrCodeUrl: '',+ description: '抖音相关操作需要在移动端App中进行,请下载并安装抖音App后继续操作。',tips: [- "安装完成后,请在App中登录您的账号",- "确保账号已通过实名认证",- "在App中完成相关任务操作"- ]+ '安装完成后,请在App中登录您的账号',+ '确保账号已通过实名认证',+ '在App中完成相关任务操作',+ ],},// 可以继续添加其他平台的配置-};+}/*** 获取平台下载配置* @param platformKey 平台标识符,如 'xhs', 'douyin'* @returns 下载配置信息*/-export const getAppDownloadConfig = (platformKey: string): AppDownloadConfig | null => {- return APP_DOWNLOAD_CONFIGS[platformKey] || null;-};+export function getAppDownloadConfig(platformKey: string): AppDownloadConfig | null {+ return APP_DOWNLOAD_CONFIGS[platformKey] || null+}/*** 检查任务是否需要App操作* @param accountTypes 账号类型数组* @returns 需要App操作的平台列表*/-export const getTasksRequiringApp = (accountTypes: string[]): string[] => {- return accountTypes.filter(type => APP_DOWNLOAD_CONFIGS[type]);-};-+export function getTasksRequiringApp(accountTypes: string[]): string[] {+ return accountTypes.filter(type => APP_DOWNLOAD_CONFIGS[type])+}diff --git a/project/web/src/app/config/platConfig.ts b/project/web/src/app/config/platConfig.tsindex e15b89bf..1230ebaf 100644--- a/project/web/src/app/config/platConfig.ts+++ b/project/web/src/app/config/platConfig.ts@@ -1,49 +1,49 @@-import { PubType } from "@/app/config/publishConfig";-import ksSvg from "@/assets/svgs/plat/ks.svg";-import bilibiliSvg from "@/assets/svgs/plat/bilibili.svg";-import youtubeSvg from "@/assets/svgs/plat/youtube.png";-import douyinSvg from "@/assets/svgs/plat/douyin.svg";-import tiktokSvg from "@/assets/svgs/plat/tiktok.svg";-import twitterSvg from "@/assets/svgs/plat/twitter.png";-import facebookSvg from "@/assets/svgs/plat/facebook.png";-import instagramSvg from "@/assets/svgs/plat/instagram.png";-import threadsSvg from "@/assets/svgs/plat/threads.png";-import wxSphSvg from "@/assets/svgs/plat/wx-sph.svg";-import gongzhonghaoSvg from "@/assets/svgs/plat/gongzhonghao.png";-import pinterestSvg from "@/assets/svgs/plat/pinterest.png";-import xhsSvg from "@/assets/svgs/plat/xhs.svg";-import linkedinSvg from "@/assets/svgs/plat/linkedin.png";-import { directTrans } from "@/app/i18n/client";+import { PubType } from '@/app/config/publishConfig'+import { directTrans } from '@/app/i18n/client'+import bilibiliSvg from '@/assets/svgs/plat/bilibili.svg'+import douyinSvg from '@/assets/svgs/plat/douyin.svg'+import facebookSvg from '@/assets/svgs/plat/facebook.png'+import gongzhonghaoSvg from '@/assets/svgs/plat/gongzhonghao.png'+import instagramSvg from '@/assets/svgs/plat/instagram.png'+import ksSvg from '@/assets/svgs/plat/ks.svg'+import linkedinSvg from '@/assets/svgs/plat/linkedin.png'+import pinterestSvg from '@/assets/svgs/plat/pinterest.png'+import threadsSvg from '@/assets/svgs/plat/threads.png'+import tiktokSvg from '@/assets/svgs/plat/tiktok.svg'+import twitterSvg from '@/assets/svgs/plat/twitter.png'+import wxSphSvg from '@/assets/svgs/plat/wx-sph.svg'+import xhsSvg from '@/assets/svgs/plat/xhs.svg'+import youtubeSvg from '@/assets/svgs/plat/youtube.png'// 平台类型export enum PlatType {- Tiktok = "tiktok", // tiktok- Douyin = "douyin", // 抖音- Xhs = "xhs", // 小红书- WxSph = "wxSph", // 微信视频号- KWAI = "KWAI", // 快手- YouTube = "youtube", // YouTube- BILIBILI = "bilibili", // B站- Twitter = "twitter", // Twitter- WxGzh = "wxGzh", // 微信公众号- Facebook = "facebook", // Facebook- Instagram = "instagram", // Instagram- Threads = "threads", // Threads- Pinterest = "pinterest", // Pinterest- LinkedIn = "linkedin", // LinkedIn+ Tiktok = 'tiktok', // tiktok+ Douyin = 'douyin', // 抖音+ Xhs = 'xhs', // 小红书+ WxSph = 'wxSph', // 微信视频号+ KWAI = 'KWAI', // 快手+ YouTube = 'youtube', // YouTube+ BILIBILI = 'bilibili', // B站+ Twitter = 'twitter', // Twitter+ WxGzh = 'wxGzh', // 微信公众号+ Facebook = 'facebook', // Facebook+ Instagram = 'instagram', // Instagram+ Threads = 'threads', // Threads+ Pinterest = 'pinterest', // Pinterest+ LinkedIn = 'linkedin', // LinkedIn}export interface IAccountPlatInfo {// 平台主题颜色- themeColor: string;+ themeColor: string// 显示的icon- icon: string;+ icon: string// 平台中文名称- name: string;+ name: string// 平台url- url: string;+ url: string// 支持的发布类型- pubTypes: Set<PubType>;+ pubTypes: Set<PubType>/*** 通用发布参数配置,有两个地方用到* 1. 在设置通用发布参数的时候会根据当前选择的账户中的最小参数为基准设置参数限制@@ -51,25 +51,25 @@ export interface IAccountPlatInfo {*/commonPubParamsConfig: {// title限制字数,可以不填,不填表示该平台无标题参数- titleMax?: number;+ titleMax?: number// 话题数量限制- topicMax: number;+ topicMax: number// 描述字数限制- desMax: number;+ desMax: number// 图片数量限制- imagesMax?: number;- };+ imagesMax?: number+ }// 是否在PC端不显示- pcNoThis?: boolean;+ pcNoThis?: boolean// 是否需要内容安全检测- jiancha?: boolean;+ jiancha?: boolean// 平台提示tips?: {// 添加账号时候的提示- account: string;+ account: string// 在发布时添加账号时候的提示- publish: string;- };+ publish: string+ }}// 各个平台的信息@@ -77,10 +77,10 @@ export const AccountPlatInfoMap = new Map<PlatType, IAccountPlatInfo>([[PlatType.Xhs,{- name: "rednote",+ name: 'rednote',icon: xhsSvg,- url: "https://www.xiaohongshu.com/",- themeColor: "red",+ url: 'https://www.xiaohongshu.com/',+ themeColor: 'red',pubTypes: new Set([]),commonPubParamsConfig: {titleMax: 100,@@ -94,47 +94,47 @@ export const AccountPlatInfoMap = new Map<PlatType, IAccountPlatInfo>([[PlatType.KWAI,{- name: "kwai",+ name: 'kwai',icon: ksSvg,- url: "https://cp.kuaishou.com/profile",+ url: 'https://cp.kuaishou.com/profile',pubTypes: new Set([PubType.VIDEO]),commonPubParamsConfig: {topicMax: 4,desMax: 500,},- themeColor: "#FF4D00",+ themeColor: '#FF4D00',jiancha: true,},],[PlatType.BILIBILI,{- name: "bilibili",+ name: 'bilibili',icon: bilibiliSvg,- url: "https://cp.kuaishou.com/profile",+ url: 'https://cp.kuaishou.com/profile',pubTypes: new Set([PubType.VIDEO]),commonPubParamsConfig: {topicMax: 10,titleMax: 80,desMax: 2000,},- themeColor: "#F06198",+ themeColor: '#F06198',jiancha: true,},],[PlatType.WxGzh,{- name: "wxgzh",+ name: 'wxgzh',icon: gongzhonghaoSvg.src,- url: "https://mp.weixin.qq.com/",+ url: 'https://mp.weixin.qq.com/',pubTypes: new Set([PubType.ImageText, PubType.Article]),commonPubParamsConfig: {topicMax: 10,desMax: 2200,imagesMax: 20,},- themeColor: "green",+ themeColor: 'green',jiancha: true,},],@@ -142,16 +142,16 @@ export const AccountPlatInfoMap = new Map<PlatType, IAccountPlatInfo>([[PlatType.Douyin,{- name: "douyin",+ name: 'douyin',icon: douyinSvg,- url: "https://www.douyin.com/",+ url: 'https://www.douyin.com/',pubTypes: new Set([]),commonPubParamsConfig: {titleMax: 30,topicMax: 5,desMax: 1000,},- themeColor: "#FF4D00",+ themeColor: '#FF4D00',pcNoThis: true,jiancha: true,},@@ -159,16 +159,16 @@ export const AccountPlatInfoMap = new Map<PlatType, IAccountPlatInfo>([[PlatType.WxSph,{- name: "wxsph",+ name: 'wxsph',icon: wxSphSvg,- url: "https://mp.weixin.qq.com/",+ url: 'https://mp.weixin.qq.com/',pubTypes: new Set([PubType.VIDEO, PubType.ImageText]),commonPubParamsConfig: {titleMax: 100,topicMax: 100,desMax: 5000,},- themeColor: "green",+ themeColor: 'green',pcNoThis: true,jiancha: true,},@@ -176,73 +176,73 @@ export const AccountPlatInfoMap = new Map<PlatType, IAccountPlatInfo>([[PlatType.Tiktok,{- name: "TikTok",+ name: 'TikTok',icon: tiktokSvg,- url: "https://www.tiktok.com/",+ url: 'https://www.tiktok.com/',pubTypes: new Set([PubType.VIDEO, PubType.ImageText]),commonPubParamsConfig: {topicMax: 100,desMax: 4000,imagesMax: 10,},- themeColor: "black",+ themeColor: 'black',jiancha: false,},],[PlatType.YouTube,{- name: "YouTube",+ name: 'YouTube',icon: youtubeSvg.src,- url: "https://www.youtube.com/",+ url: 'https://www.youtube.com/',pubTypes: new Set([PubType.VIDEO]),commonPubParamsConfig: {titleMax: 100,topicMax: 100,desMax: 5000,},- themeColor: "#F07171",+ themeColor: '#F07171',jiancha: false,},],[PlatType.Twitter,{- name: "Twitter",+ name: 'Twitter',icon: twitterSvg.src,- url: "https://x.com/",+ url: 'https://x.com/',pubTypes: new Set([PubType.VIDEO, PubType.ImageText, PubType.Article]),commonPubParamsConfig: {topicMax: 100,desMax: 280,imagesMax: 4,},- themeColor: "blue",+ themeColor: 'blue',jiancha: false,},],[PlatType.Facebook,{- name: "Facebook",+ name: 'Facebook',icon: facebookSvg.src,- url: "https://www.facebook.com/",+ url: 'https://www.facebook.com/',pubTypes: new Set([PubType.VIDEO, PubType.ImageText]),commonPubParamsConfig: {topicMax: 100,desMax: 5000,imagesMax: 10,},- themeColor: "blue",+ themeColor: 'blue',jiancha: false,},],[PlatType.Instagram,{- name: "Instagram",+ name: 'Instagram',icon: instagramSvg.src,- url: "https://www.instagram.com/",+ url: 'https://www.instagram.com/',pubTypes: new Set([PubType.VIDEO, PubType.ImageText]),commonPubParamsConfig: {titleMax: 80,@@ -250,32 +250,32 @@ export const AccountPlatInfoMap = new Map<PlatType, IAccountPlatInfo>([desMax: 2200,imagesMax: 10,},- themeColor: "blue",+ themeColor: 'blue',jiancha: false,},],[PlatType.Threads,{- name: "Threads",+ name: 'Threads',icon: threadsSvg.src,- url: "https://www.threads.net/",+ url: 'https://www.threads.net/',pubTypes: new Set([PubType.VIDEO, PubType.ImageText, PubType.Article]),commonPubParamsConfig: {topicMax: 100,desMax: 500,imagesMax: 20,},- themeColor: "blue",+ themeColor: 'blue',jiancha: false,},],[PlatType.Pinterest,{- name: "Pinterest",+ name: 'Pinterest',icon: pinterestSvg.src,- url: "https://www.pinterest.com/",+ url: 'https://www.pinterest.com/',pubTypes: new Set([PubType.VIDEO, PubType.ImageText]),commonPubParamsConfig: {titleMax: 16,@@ -283,16 +283,16 @@ export const AccountPlatInfoMap = new Map<PlatType, IAccountPlatInfo>([desMax: 2200,imagesMax: 1,},- themeColor: "#CC2025",+ themeColor: '#CC2025',jiancha: false,},],[PlatType.LinkedIn,{- name: "LinkedIn",+ name: 'LinkedIn',icon: linkedinSvg.src,- url: "https://www.linkedin.com/",+ url: 'https://www.linkedin.com/',pubTypes: new Set([PubType.VIDEO, PubType.ImageText]),commonPubParamsConfig: {titleMax: 80,@@ -300,21 +300,21 @@ export const AccountPlatInfoMap = new Map<PlatType, IAccountPlatInfo>([desMax: 500,imagesMax: 20,},- themeColor: "blue",+ themeColor: 'blue',jiancha: false,},],-]);-export const AccountPlatInfoArr = Array.from(AccountPlatInfoMap);+])+export const AccountPlatInfoArr = Array.from(AccountPlatInfoMap)// 遍历设置 name getterAccountPlatInfoMap.forEach((info) => {- const rawName = info.name;- Object.defineProperty(info, "name", {+ const rawName = info.name+ Object.defineProperty(info, 'name', {get() {- return directTrans("account", rawName);+ return directTrans('account', rawName)},configurable: true,enumerable: true,- });-});+ })+})diff --git a/project/web/src/app/config/publishConfig.ts b/project/web/src/app/config/publishConfig.tsindex bba76ca7..0ee2e1a3 100644--- a/project/web/src/app/config/publishConfig.ts+++ b/project/web/src/app/config/publishConfig.ts@@ -1,6 +1,6 @@// 发布类型export enum PubType {- VIDEO = "video", // 视频- ImageText = "article", // 图文- Article = "article2", // 纯文字+ VIDEO = 'video', // 视频+ ImageText = 'article', // 图文+ Article = 'article2', // 纯文字}diff --git a/project/web/src/app/globals.css b/project/web/src/app/globals.cssindex cc498843..913bc9b8 100644--- a/project/web/src/app/globals.css+++ b/project/web/src/app/globals.css@@ -1,4 +1,4 @@-@import "../assets/fonts/font.css";+@import '../assets/fonts/font.css';/* 全局样式重置 */* {@@ -12,9 +12,9 @@ li {}body {- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,- 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',- 'Noto Color Emoji';+ font-family:+ -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif,+ 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;}diff --git a/project/web/src/app/globals.ts b/project/web/src/app/globals.tsindex b99ef751..5e8b3333 100644--- a/project/web/src/app/globals.ts+++ b/project/web/src/app/globals.ts@@ -1,3 +1,3 @@-export type PageParams = {- params: Promise<{ lng: string }>;-};+export interface PageParams {+ params: Promise<{ lng: string }>+}diff --git a/project/web/src/app/healthz/page.tsx b/project/web/src/app/healthz/page.tsxindex 4f418089..cec09908 100644--- a/project/web/src/app/healthz/page.tsx+++ b/project/web/src/app/healthz/page.tsx@@ -6,14 +6,15 @@ export default function HealthzPage() {<meta name="viewport" content="width=device-width, initial-scale=1" /></head><body style={{ margin: 0, padding: 0 }}>- <div style={{- display: 'flex',- justifyContent: 'center',- alignItems: 'center',+ <div style={{+ display: 'flex',+ justifyContent: 'center',+ alignItems: 'center',height: '100vh',fontFamily: 'Arial, sans-serif',- backgroundColor: '#fff'- }}>+ backgroundColor: '#fff',+ }}+ ><div style={{ textAlign: 'center' }}><h1 style={{ color: '#4CAF50', marginBottom: '20px' }}>OK</h1><p style={{ color: '#666', fontSize: '16px' }}>Service is healthy</p>@@ -21,5 +22,5 @@ export default function HealthzPage() {</div></body></html>- );+ )}diff --git a/project/web/src/app/hooks/useCssVariables.ts b/project/web/src/app/hooks/useCssVariables.tsindex 40fea41f..9eb636e3 100644--- a/project/web/src/app/hooks/useCssVariables.ts+++ b/project/web/src/app/hooks/useCssVariables.ts@@ -1,6 +1,6 @@-"use client";+'use client'-import { useState, useEffect } from "react";+import { useEffect, useState } from 'react'/*** 自定义 Hook,用于获取多个 CSS 变量的值。@@ -8,71 +8,69 @@ import { useState, useEffect } from "react";* @param element - 获取 CSS 变量的元素(默认为 document.documentElement)。* @returns 一个对象,其中 CSS 变量名称作为键,变量值作为值。*/-const useCssVariables = (- variableNames: string[] = [- "--theColor1",- "--theColor2",- "--theColor3",- "--theColor4",- "--theColor5",- "--theColor6",- "--theColor7",- "--theColor8",- "--theColor9",- "--colorPrimary1",- "--colorPrimary2",- "--colorPrimary3",- "--colorPrimary4",- "--colorPrimary5",- "--colorPrimary6",- "--colorPrimary7",- "--colorPrimary8",- "--colorPrimary9",- ],- element?: HTMLElement,-): Record<string, string> => {- const [variables, setVariables] = useState<Record<string, string>>({});+function useCssVariables(variableNames: string[] = [+ '--theColor1',+ '--theColor2',+ '--theColor3',+ '--theColor4',+ '--theColor5',+ '--theColor6',+ '--theColor7',+ '--theColor8',+ '--theColor9',+ '--colorPrimary1',+ '--colorPrimary2',+ '--colorPrimary3',+ '--colorPrimary4',+ '--colorPrimary5',+ '--colorPrimary6',+ '--colorPrimary7',+ '--colorPrimary8',+ '--colorPrimary9',+], element?: HTMLElement): Record<string, string> {+ const [variables, setVariables] = useState<Record<string, string>>({})- if (typeof window === "undefined") return variables;+ if (typeof window === 'undefined')+ return variables- element = element || document.documentElement;+ element = element || document.documentElementuseEffect(() => {const handleVariableChange = () => {- const computedStyle = getComputedStyle(element);+ const computedStyle = getComputedStyle(element)const newVariables = variableNames.reduce((acc, name) => {- acc[name] = computedStyle.getPropertyValue(name).trim();- return acc;+ acc[name] = computedStyle.getPropertyValue(name).trim()+ return acc},{} as Record<string, string>,- );+ )// 只有在变量值实际发生变化时才更新状态setVariables((prevVariables) => {const hasChanged = variableNames.some(- (name) => prevVariables[name] !== newVariables[name],- );- return hasChanged ? newVariables : prevVariables;- });- };+ name => prevVariables[name] !== newVariables[name],+ )+ return hasChanged ? newVariables : prevVariables+ })+ }// 初始获取- handleVariableChange();+ handleVariableChange()// 可选:观察元素样式的变化- const observer = new MutationObserver(handleVariableChange);+ const observer = new MutationObserver(handleVariableChange)observer.observe(element, {attributes: true,- attributeFilter: ["style", "class"],- });+ attributeFilter: ['style', 'class'],+ })return () => {- observer.disconnect();- };- }, [variableNames, element]);+ observer.disconnect()+ }+ }, [variableNames, element])- return variables;-};+ return variables+}-export default useCssVariables;+export default useCssVariablesdiff --git a/project/web/src/app/i18n/client.ts b/project/web/src/app/i18n/client.tsindex 27f7a713..314f2966 100644--- a/project/web/src/app/i18n/client.ts+++ b/project/web/src/app/i18n/client.ts@@ -1,21 +1,25 @@-"use client";+'use client'-import { useEffect, useState } from "react";-import i18next, { FlatNamespace, KeyPrefix } from "i18next";-import {- initReactI18next,+import type { FlatNamespace, KeyPrefix } from 'i18next'+import type {+ FallbackNs,UseTranslationOptions,UseTranslationResponse,- FallbackNs,-} from "react-i18next";-import resourcesToBackend from "i18next-resources-to-backend";-import LanguageDetector from "i18next-browser-languagedetector";-import { cookieName, getOptions, languages } from "./settings";-import { useTranslation } from "react-i18next";-import { getCookie, setCookie } from "cookies-next";-import { useGetClientLng } from "@/hooks/useSystem";+} from 'react-i18next'+import { getCookie, setCookie } from 'cookies-next'+import i18next from 'i18next'+import LanguageDetector from 'i18next-browser-languagedetector'+import resourcesToBackend from 'i18next-resources-to-backend'+import { useEffect, useState } from 'react'+import {+ initReactI18next,+ useTranslation,+} from 'react-i18next'++import { useGetClientLng } from '@/hooks/useSystem'+import { cookieName, getOptions, languages } from './settings'-const runsOnServerSide = typeof window === "undefined";+const runsOnServerSide = typeof window === 'undefined'// on client side the normal singleton is oki18next@@ -32,10 +36,10 @@ i18next...getOptions(undefined), // 不传递 lng 参数,让 i18next 自动检测lng: undefined, // let detect the language on client sidedetection: {- order: ["path", "htmlTag", "cookie", "navigator"],+ order: ['path', 'htmlTag', 'cookie', 'navigator'],},preload: runsOnServerSide ? languages : [],- });+ })export function useTransClient<Ns extends FlatNamespace,@@ -44,48 +48,53 @@ export function useTransClient<ns?: Ns,options?: UseTranslationOptions<KPrefix>,): UseTranslationResponse<FallbackNs<Ns>, KPrefix> {- const i18nextCookie = getCookie(cookieName);- const lng = useGetClientLng();- if (typeof lng !== "string")- throw new Error("useT is only available inside /app/[lng]");+ const i18nextCookie = getCookie(cookieName)+ const lng = useGetClientLng()+ if (typeof lng !== 'string')+ throw new Error('useT is only available inside /app/[lng]')if (runsOnServerSide && i18next.resolvedLanguage !== lng) {- i18next.changeLanguage(lng);- } else {- const [activeLng, setActiveLng] = useState(i18next.resolvedLanguage);+ i18next.changeLanguage(lng)+ }+ else {+ const [activeLng, setActiveLng] = useState(i18next.resolvedLanguage)// 监听 i18next 语言变化useEffect(() => {- if (activeLng === i18next.resolvedLanguage) return;- setActiveLng(i18next.resolvedLanguage);- }, [activeLng, i18next.resolvedLanguage]);+ if (activeLng === i18next.resolvedLanguage)+ return+ setActiveLng(i18next.resolvedLanguage)+ }, [activeLng, i18next.resolvedLanguage])// 强制同步 URL 参数中的语言到 i18nextuseEffect(() => {- if (!lng) return;+ if (!lng)+ return// 始终使用 URL 参数中的语言,忽略 i18next 的自动检测if (i18next.resolvedLanguage !== lng) {i18next.changeLanguage(lng).then(() => {// 语言切换完成后,强制重新渲染- setActiveLng(lng);- });- } else {+ setActiveLng(lng)+ })+ }+ else {// 即使语言相同,也确保状态同步- setActiveLng(lng);+ setActiveLng(lng)}- }, [lng]);+ }, [lng])// 同步 cookieuseEffect(() => {- if (i18nextCookie === lng) return;- setCookie(cookieName, lng, { path: "/" });- }, [lng, i18nextCookie]);+ if (i18nextCookie === lng)+ return+ setCookie(cookieName, lng, { path: '/' })+ }, [lng, i18nextCookie])}- return useTranslation(ns, options);+ return useTranslation(ns, options)}-export default i18next;+export default i18next// 静态方法,注意这个方法的国际化不会自动更新export function directTrans<Ns extends FlatNamespace>(@@ -93,7 +102,7 @@ export function directTrans<Ns extends FlatNamespace>(key: string,): string {// @ts-ignore- const t = (key: string) => i18next.t(key, { ns });+ const t = (key: string) => i18next.t(key, { ns })// @ts-ignore- return t(key);+ return t(key)}diff --git a/project/web/src/app/i18n/index.ts b/project/web/src/app/i18n/index.tsindex 23674612..c05f4f71 100644--- a/project/web/src/app/i18n/index.ts+++ b/project/web/src/app/i18n/index.ts@@ -1,12 +1,13 @@-import { createInstance, Namespace, FlatNamespace, KeyPrefix } from "i18next";-import resourcesToBackend from "i18next-resources-to-backend";-import { initReactI18next } from "react-i18next/initReactI18next";-import { FallbackNs } from "react-i18next";-import { getOptions } from "./settings";+import type { FlatNamespace, KeyPrefix, Namespace } from 'i18next'+import type { FallbackNs } from 'react-i18next'+import { createInstance } from 'i18next'+import resourcesToBackend from 'i18next-resources-to-backend'+import { initReactI18next } from 'react-i18next/initReactI18next'+import { getOptions } from './settings'-const initI18next = async (lng: string, ns: string | string[]) => {+async function initI18next(lng: string, ns: string | string[]) {// on server side we create a new instance for each render, because during compilation everything seems to be executed in parallel- const i18nInstance = createInstance();+ const i18nInstance = createInstance()await i18nInstance.use(initReactI18next).use(@@ -15,14 +16,14 @@ const initI18next = async (lng: string, ns: string | string[]) => {import(`./locales/${language}/${namespace}.json`),),)- .init(getOptions(lng, ns));- return i18nInstance;-};+ .init(getOptions(lng, ns))+ return i18nInstance+}-type $Tuple<T> = readonly [T?, ...T[]];+type $Tuple<T> = readonly [T?, ...T[]]type $FirstNamespace<Ns extends Namespace> = Ns extends readonly any[]? Ns[0]- : Ns;+ : Nsexport async function useTranslation<Ns extends FlatNamespace | $Tuple<FlatNamespace>,@@ -33,15 +34,15 @@ export async function useTranslation<> = undefined,>(lng: string, ns?: Ns, options: { keyPrefix?: KPrefix } = {}) {// @ts-ignore- ns = ns || "translation";+ ns = ns || 'translation'const i18nextInstance = await initI18next(lng,Array.isArray(ns) ? (ns as string[]) : (ns as string),- );+ )return {t: Array.isArray(ns)? i18nextInstance.getFixedT(lng, ns[0], options.keyPrefix): i18nextInstance.getFixedT(lng, ns as FlatNamespace, options.keyPrefix),i18n: i18nextInstance,- };+ }}diff --git a/project/web/src/app/i18n/locales/en/account.json b/project/web/src/app/i18n/locales/en/account.jsonindex 907fd156..2f467ba7 100644--- a/project/web/src/app/i18n/locales/en/account.json+++ b/project/web/src/app/i18n/locales/en/account.json@@ -148,4 +148,4 @@"content": "Your {{platformName}} account \"{{nickname}}\" (in {{spaceName}}) session has expired. Would you like to log in again?","loginAgain": "Reauthorize"}-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/en/common.json b/project/web/src/app/i18n/locales/en/common.jsonindex d1e3068d..1f714bfc 100644--- a/project/web/src/app/i18n/locales/en/common.json+++ b/project/web/src/app/i18n/locales/en/common.json@@ -127,4 +127,4 @@"importantNoteContent": "Data cannot be recovered after deletion. Please proceed with caution. Some data required by law may not be deletable."}}-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/en/dataStatistics.json b/project/web/src/app/i18n/locales/en/dataStatistics.jsonindex ed75e3dc..0f2c67f6 100644--- a/project/web/src/app/i18n/locales/en/dataStatistics.json+++ b/project/web/src/app/i18n/locales/en/dataStatistics.json@@ -20,4 +20,4 @@"likeCount": "Likes","collectCount": "Collections","forwardCount": "Shares"-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/en/engagement.json b/project/web/src/app/i18n/locales/en/engagement.jsonindex 8f5cb98e..db794f98 100644--- a/project/web/src/app/i18n/locales/en/engagement.json+++ b/project/web/src/app/i18n/locales/en/engagement.json@@ -24,5 +24,3 @@"reset": "Reset"}}--diff --git a/project/web/src/app/i18n/locales/en/home.json b/project/web/src/app/i18n/locales/en/home.jsonindex 9d0e1d4d..0986d847 100644--- a/project/web/src/app/i18n/locales/en/home.json+++ b/project/web/src/app/i18n/locales/en/home.json@@ -254,7 +254,7 @@"standardTitle": "Standard Procedure (Post-Launch):","standardSteps": ["Log in to your AiToEarn account",- "Navigate to Settings > Privacy",+ "Navigate to Settings > Privacy","Click \"Request Account Deletion\"","Confirmation will be sent to your registered email"],@@ -262,4 +262,4 @@"contactEmail": "Email: [email protected] (Pre-launch inquiries only)"}}-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/en/imageEditor.json b/project/web/src/app/i18n/locales/en/imageEditor.jsonindex 7e5342ac..9f41e195 100644--- a/project/web/src/app/i18n/locales/en/imageEditor.json+++ b/project/web/src/app/i18n/locales/en/imageEditor.json@@ -1,3 +1,3 @@{"imageEditing": "image editing"-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/en/interactive.json b/project/web/src/app/i18n/locales/en/interactive.jsonindex e488e0e1..ed2876d3 100644--- a/project/web/src/app/i18n/locales/en/interactive.json+++ b/project/web/src/app/i18n/locales/en/interactive.json@@ -39,7 +39,7 @@"stats": {"likes": "Likes","comments": "Comments",- "views": "Views",+ "views": "Views","shares": "Shares","clicks": "Clicks","impressions": "Impressions",diff --git a/project/web/src/app/i18n/locales/en/login.json b/project/web/src/app/i18n/locales/en/login.jsonindex 1d2599d1..2dbfa1c3 100644--- a/project/web/src/app/i18n/locales/en/login.json+++ b/project/web/src/app/i18n/locales/en/login.json@@ -30,7 +30,6 @@"emailLabel": "Email","emailRequired": "Please enter your email","emailInvalid": "Please enter a valid email address",- "emailPlaceholder": "Please enter your registered email","sendResetLink": "Send Reset Link","newPassword": "New Password","newPasswordRequired": "Please enter new password",@@ -53,4 +52,4 @@"verificationCodePlaceholder": "Please enter the verification code from your email","resetEmailSent": "Reset email sent, please check your inbox","sendEmailFailed": "Failed to send email"-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/en/material.json b/project/web/src/app/i18n/locales/en/material.jsonindex 3033fffc..d8ee6d4d 100644--- a/project/web/src/app/i18n/locales/en/material.json+++ b/project/web/src/app/i18n/locales/en/material.json@@ -80,7 +80,6 @@"videoDuration": "Video Duration","videoSize": "Video Size","videoMode": "Generation Mode",- "uploadImage": "Upload Image","firstFrame": "First Frame","tailFrame": "Tail Frame","imageUrlPlaceholder": "Select Add Image ",@@ -91,7 +90,6 @@"taskFailed": "Task Failed","checkStatus": "Check Status","videoGenerationFailed": "Video generation failed",- "videoGenerationSuccess": "Video generation successful","pleaseEnterVideoPrompt": "Please enter video description","pleaseSelectVideoModel": "Please select video model","videoUploadSuccess": "Video upload successful",@@ -134,44 +132,44 @@"imageEditFailed": "Image edit failed","imageEditSuccess": "Image edit success","pleaseUploadSourceImage": "Please upload source image",- "imageEditTaskSubmitted": "Image edit task submitted",- "imageEditTaskProcessing": "Image edit task processing",- "imageEditTaskCompleted": "Image edit task completed",- "imageEditTaskFailed": "Image edit task failed",- "advancedOptions": "Advanced Options",- "outputImageCount": "Output Image Count",- "low": "Low",- "sourceImage": "Source Image",- "deleteImage": "Delete Image",- "clearAllImages": "Clear All Images",- "maxUploadReached": "Max upload reached ({{count}} images)",- "maxUploadLimitReached": "Max upload limit reached: {{count}} images",- "autoSelectImages": "Can only upload {{count}} images, automatically selected first {{count}}",- "uploadSuccessCount": "Successfully uploaded {{count}} images",- "autoRemoveExcessImages": "Model supports max {{maxCount}} images, automatically removed {{removedCount}} images",- "imageEditCompleted": "Image edit completed",- "imageGenerationCompleted": "Image generation completed",- "noDefaultMediaGroup": "No default media group found",- "pleaseUploadAtLeastOneImage": "Please upload at least one image",- "uploadImage": "Upload Image",- "addImage": "Add Image",- "image": "Image",- "videoGenerationHistory": "Video Generation History",- "refresh": "Refresh",- "noHistoryRecords": "No history records",- "submitTime": "Submit Time",- "completeTime": "Complete Time",- "progress": "Progress",- "failReason": "Fail Reason",- "completed": "Completed",- "failed": "Failed",- "processing": "Processing",- "submitted": "Submitted",- "examplePrompt1": "Time-lapse Bloom",- "examplePrompt2": "Vibrant Flowers",- "examplePrompt3": "Underwater World",- "examplePrompt4": "Starry Journey",- "examplePrompt5": "Cyber City",+ "imageEditTaskSubmitted": "Image edit task submitted",+ "imageEditTaskProcessing": "Image edit task processing",+ "imageEditTaskCompleted": "Image edit task completed",+ "imageEditTaskFailed": "Image edit task failed",+ "advancedOptions": "Advanced Options",+ "outputImageCount": "Output Image Count",+ "low": "Low",+ "sourceImage": "Source Image",+ "deleteImage": "Delete Image",+ "clearAllImages": "Clear All Images",+ "maxUploadReached": "Max upload reached ({{count}} images)",+ "maxUploadLimitReached": "Max upload limit reached: {{count}} images",+ "autoSelectImages": "Can only upload {{count}} images, automatically selected first {{count}}",+ "uploadSuccessCount": "Successfully uploaded {{count}} images",+ "autoRemoveExcessImages": "Model supports max {{maxCount}} images, automatically removed {{removedCount}} images",+ "imageEditCompleted": "Image edit completed",+ "imageGenerationCompleted": "Image generation completed",+ "noDefaultMediaGroup": "No default media group found",+ "pleaseUploadAtLeastOneImage": "Please upload at least one image",+ "uploadImage": "Upload Image",+ "addImage": "Add Image",+ "image": "Image",+ "videoGenerationHistory": "Video Generation History",+ "refresh": "Refresh",+ "noHistoryRecords": "No history records",+ "submitTime": "Submit Time",+ "completeTime": "Complete Time",+ "progress": "Progress",+ "failReason": "Fail Reason",+ "completed": "Completed",+ "failed": "Failed",+ "processing": "Processing",+ "submitted": "Submitted",+ "examplePrompt1": "Time-lapse Bloom",+ "examplePrompt2": "Vibrant Flowers",+ "examplePrompt3": "Underwater World",+ "examplePrompt4": "Starry Journey",+ "examplePrompt5": "Cyber City","textToVideo": "Text to Video","imageToVideo": "Image to Video","seconds": "s",@@ -180,15 +178,15 @@"cardWidthPlaceholder": "Card width","cardHeightPlaceholder": "Card height","splitModePlaceholder": "Split mode",- "markdownToCard": "Markdown to Card",- "markdownCard": "Markdown Card",- "templateA": "Default",- "templateB": "Transparent",- "templateC": "Quote",- "templateJin": "Book",- "templateMemo": "Memo",- "templateEasy": "Border",- "templateWrite": "Handwriting",+ "markdownToCard": "Markdown to Card",+ "markdownCard": "Markdown Card",+ "templateA": "Default",+ "templateB": "Transparent",+ "templateC": "Quote",+ "templateJin": "Book",+ "templateMemo": "Memo",+ "templateEasy": "Border",+ "templateWrite": "Handwriting","pleaseUploadFirstFrame": "Please upload first frame image","pleaseUploadTailFrame": "Please upload tail frame image","imageRequirements": "Image Requirements",@@ -205,4 +203,4 @@"getImageModelsFailed": "Failed to get image generation models","getVideoModelsFailed": "Failed to get video generation models"}-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/en/notification.json b/project/web/src/app/i18n/locales/en/notification.jsonindex 9d338740..bec7625a 100644--- a/project/web/src/app/i18n/locales/en/notification.json+++ b/project/web/src/app/i18n/locales/en/notification.json@@ -82,7 +82,6 @@},"accountSelect": {"title": "Select Publisher Account",- "description": "Please select an account to publish the task:","noAccounts": "No eligible accounts found, please add an account first","redirectingToAccounts": "Redirecting to accounts page, please add eligible accounts","accountId": "Account ID",diff --git a/project/web/src/app/i18n/locales/en/pinterest.json b/project/web/src/app/i18n/locales/en/pinterest.jsonindex 8ad83e6b..0a0a1ddf 100644--- a/project/web/src/app/i18n/locales/en/pinterest.json+++ b/project/web/src/app/i18n/locales/en/pinterest.json@@ -117,4 +117,4 @@"ok": "OK","cancel": "Cancel"}-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/en/pricing.json b/project/web/src/app/i18n/locales/en/pricing.jsonindex 02f14103..039b7df9 100644--- a/project/web/src/app/i18n/locales/en/pricing.json+++ b/project/web/src/app/i18n/locales/en/pricing.json@@ -1,6 +1,5 @@{-"title": "Pricing & Plans","subtitle": "Choose the plan that best fits your needs and start your AI creation journey","monthly": "Monthly",diff --git a/project/web/src/app/i18n/locales/en/profile.json b/project/web/src/app/i18n/locales/en/profile.jsonindex 6bce2569..559dac55 100644--- a/project/web/src/app/i18n/locales/en/profile.json+++ b/project/web/src/app/i18n/locales/en/profile.json@@ -84,7 +84,6 @@"trialEndTime": "Trial End Time","willCancelAtPeriodEnd": "Will cancel at period end","subscriptionPastDue": "Past Due",- "copySuccess": "Copied","resumeSubscription": "Resume Subscription","resumeSuccess": "Resumed successfully","vipBenefits": {@@ -196,4 +195,4 @@"oneTime": "One-time","trial": "Trial"}-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/en/route.json b/project/web/src/app/i18n/locales/en/route.jsonindex bfbd32f8..62edebd1 100644--- a/project/web/src/app/i18n/locales/en/route.json+++ b/project/web/src/app/i18n/locales/en/route.json@@ -11,4 +11,4 @@"dataStatistics": "Data","navigation": "Navigation","aiRank": "AI Rank"-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/en/translation.json b/project/web/src/app/i18n/locales/en/translation.jsonindex dfaecf91..6f665d16 100644--- a/project/web/src/app/i18n/locales/en/translation.json+++ b/project/web/src/app/i18n/locales/en/translation.json@@ -1,4 +1,4 @@{"title": "Aitoearn: The Best Open Source Content AI Agent","content": "The best open-source matrix tool"-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/en/vip.json b/project/web/src/app/i18n/locales/en/vip.jsonindex edbaf0aa..c5b8045d 100644--- a/project/web/src/app/i18n/locales/en/vip.json+++ b/project/web/src/app/i18n/locales/en/vip.json@@ -200,4 +200,4 @@"range": "1K-50K","unit": "credits"}-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/en/wallet.json b/project/web/src/app/i18n/locales/en/wallet.jsonindex 6cb1441d..66976d7e 100644--- a/project/web/src/app/i18n/locales/en/wallet.json+++ b/project/web/src/app/i18n/locales/en/wallet.json@@ -49,4 +49,3 @@"deleteSuccess": "Deleted successfully"}}-diff --git a/project/web/src/app/i18n/locales/en/youtube.json b/project/web/src/app/i18n/locales/en/youtube.jsonindex bbe9fea9..fc5b2994 100644--- a/project/web/src/app/i18n/locales/en/youtube.json+++ b/project/web/src/app/i18n/locales/en/youtube.json@@ -14,4 +14,4 @@"uploadSuccess": "Upload Success","checkFailed": "Check Failed","alreadyAuthorized": "Already Authorized"-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/zh-CN/account.json b/project/web/src/app/i18n/locales/zh-CN/account.jsonindex dfcbe6f8..3e9818f4 100644--- a/project/web/src/app/i18n/locales/zh-CN/account.json+++ b/project/web/src/app/i18n/locales/zh-CN/account.json@@ -148,4 +148,4 @@"content": "您的 {{platformName}} 账号 \"{{nickname}}\"(位于 {{spaceName}})会话已过期。是否重新登录?","loginAgain": "重新登录"}-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/zh-CN/common.json b/project/web/src/app/i18n/locales/zh-CN/common.jsonindex e65e7f65..62a79987 100644--- a/project/web/src/app/i18n/locales/zh-CN/common.json+++ b/project/web/src/app/i18n/locales/zh-CN/common.json@@ -113,12 +113,12 @@"prelaunchNote": "对于预发布用户:","prelaunchContent": "我们目前处于预发布阶段,如需删除数据,请直接联系我们的支持团队。","standardProcedure": "标准删除流程:",- "steps": [- "登录您的账户并进入设置页面",- "点击「数据管理」选项",- "选择「删除我的数据」",- "确认删除操作并等待处理完成"- ],+ "steps": [+ "登录您的账户并进入设置页面",+ "点击「数据管理」选项",+ "选择「删除我的数据」",+ "确认删除操作并等待处理完成"+ ],"contactInfo": "联系方式:","contactEmail": "如需帮助,请发送邮件至:[email protected]","processingTime": "处理时间:",@@ -127,4 +127,4 @@"importantNoteContent": "数据删除后无法恢复,请谨慎操作。某些法律要求保留的数据可能无法删除。"}}-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/zh-CN/dataStatistics.json b/project/web/src/app/i18n/locales/zh-CN/dataStatistics.jsonindex 1b190e48..9fcfa927 100644--- a/project/web/src/app/i18n/locales/zh-CN/dataStatistics.json+++ b/project/web/src/app/i18n/locales/zh-CN/dataStatistics.json@@ -20,4 +20,4 @@"likeCount": "点赞数","collectCount": "收藏数","forwardCount": "分享数"-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/zh-CN/engagement.json b/project/web/src/app/i18n/locales/zh-CN/engagement.jsonindex 5c31e430..4483f432 100644--- a/project/web/src/app/i18n/locales/zh-CN/engagement.json+++ b/project/web/src/app/i18n/locales/zh-CN/engagement.json@@ -24,5 +24,3 @@"reset": "重置"}}--diff --git a/project/web/src/app/i18n/locales/zh-CN/home.json b/project/web/src/app/i18n/locales/zh-CN/home.jsonindex d715d746..629aa925 100644--- a/project/web/src/app/i18n/locales/zh-CN/home.json+++ b/project/web/src/app/i18n/locales/zh-CN/home.json@@ -245,7 +245,7 @@"twitter": "Twitter"},"bigText": "Let's Use AI To",- "copyright": "© 2025 AITOEARN, Corp.",+ "copyright": "© 2025 AITOEARN, Corp.","tagline": "","dataDeletion": {"title": "Data Deletion Instructions",@@ -253,7 +253,7 @@"standardTitle": "Standard Procedure (Post-Launch):","standardSteps": ["Log in to your AiToEarn account",- "Navigate to Settings > Privacy",+ "Navigate to Settings > Privacy","Click \"Request Account Deletion\"","Confirmation will be sent to your registered email"],@@ -261,4 +261,4 @@"contactEmail": "Email: [email protected] (Pre-launch inquiries only)"}}-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/zh-CN/imageEditor.json b/project/web/src/app/i18n/locales/zh-CN/imageEditor.jsonindex f1837ec4..4869ab81 100644--- a/project/web/src/app/i18n/locales/zh-CN/imageEditor.json+++ b/project/web/src/app/i18n/locales/zh-CN/imageEditor.json@@ -76,4 +76,4 @@"DeleteAll": "全部去除","Blend": "混合","imageEditing": "图像编辑"-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/zh-CN/interactive.json b/project/web/src/app/i18n/locales/zh-CN/interactive.jsonindex bffa8bf7..11e77b20 100644--- a/project/web/src/app/i18n/locales/zh-CN/interactive.json+++ b/project/web/src/app/i18n/locales/zh-CN/interactive.json@@ -38,7 +38,7 @@},"stats": {"likes": "点赞",- "comments": "评论",+ "comments": "评论","views": "浏览","shares": "分享","clicks": "点击",diff --git a/project/web/src/app/i18n/locales/zh-CN/login.json b/project/web/src/app/i18n/locales/zh-CN/login.jsonindex 00013e9d..c9c6fdd7 100644--- a/project/web/src/app/i18n/locales/zh-CN/login.json+++ b/project/web/src/app/i18n/locales/zh-CN/login.json@@ -30,7 +30,6 @@"emailLabel": "邮箱","emailRequired": "请输入邮箱","emailInvalid": "请输入有效的邮箱地址",- "emailPlaceholder": "请输入注册邮箱","sendResetLink": "发送重置链接","newPassword": "新密码","newPasswordRequired": "请输入新密码",@@ -53,4 +52,4 @@"verificationCodePlaceholder": "请输入邮箱中的验证码","resetEmailSent": "重置邮件已发送,请查收","sendEmailFailed": "发送邮件失败"-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/zh-CN/material.json b/project/web/src/app/i18n/locales/zh-CN/material.jsonindex c4e6c06d..e6f93ad6 100644--- a/project/web/src/app/i18n/locales/zh-CN/material.json+++ b/project/web/src/app/i18n/locales/zh-CN/material.json@@ -118,14 +118,8 @@"fireflyCardGenerationFailed": "生成流光卡片失败","pleaseEnterContentAndTitle": "请输入内容和标题","taskSubmittedSuccess": "任务已提交",- "videoGenerationSuccess": "视频生成成功","checkVideoTaskStatusFailed": "检查视频任务状态失败","pleaseEnterVideoDescription": "请输入视频描述",- "pleaseSelectVideoModel": "请选择视频模型",- "videoUploadSuccess": "视频上传成功",- "videoUploadFailed": "视频上传失败",- "cardUploadSuccess": "卡片上传成功",- "cardUploadFailed": "卡片上传失败","selectSizePlaceholder": "选择尺寸","generateCountPlaceholder": "生成数量","imageQualityPlaceholder": "图片质量",@@ -139,44 +133,43 @@"imageEditFailed": "图片编辑失败","imageEditSuccess": "图片编辑成功","pleaseUploadSourceImage": "请上传源图片",- "imageEditTaskSubmitted": "图片编辑任务已提交",- "imageEditTaskProcessing": "图片编辑任务处理中",- "imageEditTaskCompleted": "图片编辑任务完成",- "imageEditTaskFailed": "图片编辑任务失败",- "advancedOptions": "高级选项",- "outputImageCount": "输出图像数量",- "low": "低",- "sourceImage": "源图片",- "deleteImage": "删除图片",- "clearAllImages": "清空所有图片",- "maxUploadReached": "已达到最大上传数量({{count}}张)",- "maxUploadLimitReached": "已达到最大上传数量限制:{{count}}张图片",- "autoSelectImages": "只能上传{{count}}张图片,已自动选择前{{count}}张",- "uploadSuccessCount": "成功上传 {{count}} 张图片",- "autoRemoveExcessImages": "模型最多支持{{maxCount}}张图片,已自动移除{{removedCount}}张图片",- "imageEditCompleted": "图片编辑完成",- "imageGenerationCompleted": "图片生成完成",- "noDefaultMediaGroup": "未找到默认素材库组",- "pleaseUploadAtLeastOneImage": "请上传至少一张图片",- "uploadImage": "上传图片",- "addImage": "添加图片",- "image": "图片",- "videoGenerationHistory": "视频生成历史",- "refresh": "刷新",- "noHistoryRecords": "暂无历史记录",- "submitTime": "提交时间",- "completeTime": "完成时间",- "progress": "进度",- "failReason": "失败原因",- "completed": "已完成",- "failed": "失败",- "processing": "处理中",- "submitted": "已提交",- "examplePrompt1": "延时绽放",- "examplePrompt2": "绚丽花朵",- "examplePrompt3": "海底世界",- "examplePrompt4": "星空漫游",- "examplePrompt5": "赛博城市",+ "imageEditTaskSubmitted": "图片编辑任务已提交",+ "imageEditTaskProcessing": "图片编辑任务处理中",+ "imageEditTaskCompleted": "图片编辑任务完成",+ "imageEditTaskFailed": "图片编辑任务失败",+ "advancedOptions": "高级选项",+ "outputImageCount": "输出图像数量",+ "low": "低",+ "sourceImage": "源图片",+ "deleteImage": "删除图片",+ "clearAllImages": "清空所有图片",+ "maxUploadReached": "已达到最大上传数量({{count}}张)",+ "maxUploadLimitReached": "已达到最大上传数量限制:{{count}}张图片",+ "autoSelectImages": "只能上传{{count}}张图片,已自动选择前{{count}}张",+ "uploadSuccessCount": "成功上传 {{count}} 张图片",+ "autoRemoveExcessImages": "模型最多支持{{maxCount}}张图片,已自动移除{{removedCount}}张图片",+ "imageEditCompleted": "图片编辑完成",+ "imageGenerationCompleted": "图片生成完成",+ "noDefaultMediaGroup": "未找到默认素材库组",+ "pleaseUploadAtLeastOneImage": "请上传至少一张图片",+ "addImage": "添加图片",+ "image": "图片",+ "videoGenerationHistory": "视频生成历史",+ "refresh": "刷新",+ "noHistoryRecords": "暂无历史记录",+ "submitTime": "提交时间",+ "completeTime": "完成时间",+ "progress": "进度",+ "failReason": "失败原因",+ "completed": "已完成",+ "failed": "失败",+ "processing": "处理中",+ "submitted": "已提交",+ "examplePrompt1": "延时绽放",+ "examplePrompt2": "绚丽花朵",+ "examplePrompt3": "海底世界",+ "examplePrompt4": "星空漫游",+ "examplePrompt5": "赛博城市","textToVideo": "文本转视频","imageToVideo": "图文转视频","seconds": "秒",@@ -185,15 +178,15 @@"cardWidthPlaceholder": "卡片宽度","cardHeightPlaceholder": "卡片高度","splitModePlaceholder": "分割模式",- "markdownToCard": "Markdown转卡片",- "markdownCard": "Markdown卡片",- "templateA": "默认",- "templateB": "透明",- "templateC": "金句",- "templateJin": "书摘",- "templateMemo": "便当",- "templateEasy": "边框",- "templateWrite": "手写",+ "markdownToCard": "Markdown转卡片",+ "markdownCard": "Markdown卡片",+ "templateA": "默认",+ "templateB": "透明",+ "templateC": "金句",+ "templateJin": "书摘",+ "templateMemo": "便当",+ "templateEasy": "边框",+ "templateWrite": "手写","pleaseUploadFirstFrame": "请上传首帧图片","pleaseUploadTailFrame": "请上传尾帧图片","imageRequirements": "图片要求",@@ -210,4 +203,4 @@"getImageModelsFailed": "获取图片生成模型失败","getVideoModelsFailed": "获取视频生成模型失败"}-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/zh-CN/notification.json b/project/web/src/app/i18n/locales/zh-CN/notification.jsonindex ba361af3..fef5803d 100644--- a/project/web/src/app/i18n/locales/zh-CN/notification.json+++ b/project/web/src/app/i18n/locales/zh-CN/notification.json@@ -82,7 +82,6 @@},"accountSelect": {"title": "选择发布账号",- "description": "请选择用于发布任务的账号:","noAccounts": "没有符合条件的账号,请先添加账号","redirectingToAccounts": "正在跳转到账户界面,请添加符合条件的账号","accountId": "账号ID",diff --git a/project/web/src/app/i18n/locales/zh-CN/pinterest.json b/project/web/src/app/i18n/locales/zh-CN/pinterest.jsonindex ef035704..fa86c59f 100644--- a/project/web/src/app/i18n/locales/zh-CN/pinterest.json+++ b/project/web/src/app/i18n/locales/zh-CN/pinterest.json@@ -117,4 +117,4 @@"ok": "确定","cancel": "取消"}-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/zh-CN/profile.json b/project/web/src/app/i18n/locales/zh-CN/profile.jsonindex bc1f3477..83e629d6 100644--- a/project/web/src/app/i18n/locales/zh-CN/profile.json+++ b/project/web/src/app/i18n/locales/zh-CN/profile.json@@ -162,7 +162,6 @@"inviteCode": "邀请码","edit": "编辑","copy": "复制",- "copySuccess": "已复制","cancelAccount": "注销账户","cancelAccountWarning": "注销账户是不可逆的操作,一旦注销,您的所有数据将被永久删除,包括:","cancelAccountDataList": "个人资料和设置,所有发布的内容,积分和会员权益,订单和支付记录",@@ -196,4 +195,4 @@"oneTime": "一次性","trial": "试用"}-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/zh-CN/route.json b/project/web/src/app/i18n/locales/zh-CN/route.jsonindex 4b31c3fb..e60b5057 100644--- a/project/web/src/app/i18n/locales/zh-CN/route.json+++ b/project/web/src/app/i18n/locales/zh-CN/route.json@@ -12,4 +12,4 @@"dataStatistics": "数据统计","navigation": "导航","aiRank": "AI热榜"-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/zh-CN/translation.json b/project/web/src/app/i18n/locales/zh-CN/translation.jsonindex 947951f2..21e31351 100644--- a/project/web/src/app/i18n/locales/zh-CN/translation.json+++ b/project/web/src/app/i18n/locales/zh-CN/translation.json@@ -1,4 +1,4 @@{"title": "AIToEarn官方网站","content": "最好用的开源矩阵工具"-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/zh-CN/vip.json b/project/web/src/app/i18n/locales/zh-CN/vip.jsonindex 0533dbb6..0ff5d350 100644--- a/project/web/src/app/i18n/locales/zh-CN/vip.json+++ b/project/web/src/app/i18n/locales/zh-CN/vip.json@@ -14,7 +14,7 @@"description": "选择连续包月或连续包年,可享受7天免费试用期!"},"trialText": {- "month": "前7天免费,之后$15/月",+ "month": "前7天免费,之后$15/月","year": "前7天免费,之后$120/年"},"badge": {@@ -92,7 +92,7 @@"singleMonth": "单月会员","trial": "试用中","cancelled": "已退订",- "expireTime": "到期时间",+ "expireTime": "到期时间","xufeiTime": "续费时间","remainingPoints": "剩余积分","buyPoints": "购买积分"@@ -200,4 +200,4 @@"range": "1K-50K","unit": "积分"}-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/locales/zh-CN/wallet.json b/project/web/src/app/i18n/locales/zh-CN/wallet.jsonindex 68760c09..25e05ee6 100644--- a/project/web/src/app/i18n/locales/zh-CN/wallet.json+++ b/project/web/src/app/i18n/locales/zh-CN/wallet.json@@ -49,5 +49,3 @@"deleteSuccess": "删除成功"}}--diff --git a/project/web/src/app/i18n/locales/zh-CN/youtube.json b/project/web/src/app/i18n/locales/zh-CN/youtube.jsonindex adaf4801..818047f1 100644--- a/project/web/src/app/i18n/locales/zh-CN/youtube.json+++ b/project/web/src/app/i18n/locales/zh-CN/youtube.json@@ -15,4 +15,4 @@"uploadSuccess": "上传成功","checkFailed": "检查失败","alreadyAuthorized": "已授权"-}\ No newline at end of file+}diff --git a/project/web/src/app/i18n/settings.ts b/project/web/src/app/i18n/settings.tsindex 6d181a25..4c2c6ddc 100644--- a/project/web/src/app/i18n/settings.ts+++ b/project/web/src/app/i18n/settings.ts@@ -1,11 +1,11 @@-export const fallbackLng = "en";-export const languages = [fallbackLng, "zh-CN"];-export const defaultNS = "common";-export const cookieName = "i18next";+export const fallbackLng = 'en'+export const languages = [fallbackLng, 'zh-CN']+export const defaultNS = 'common'+export const cookieName = 'i18next'export function getOptions(lng = fallbackLng,- ns: string | string[] = [defaultNS, "route"],+ ns: string | string[] = [defaultNS, 'route'],) {return {// debug: true,@@ -19,5 +19,5 @@ export function getOptions(// backend: {// projectId: '01b2e5e8-6243-47d1-b36f-963dbb8bcae3'// }- };+ }}diff --git a/project/web/src/app/layout/ConditionalHeader.tsx b/project/web/src/app/layout/ConditionalHeader.tsxindex b542104d..032b1367 100644--- a/project/web/src/app/layout/ConditionalHeader.tsx+++ b/project/web/src/app/layout/ConditionalHeader.tsx@@ -1,26 +1,29 @@-"use client";+'use client'-import { usePathname } from "next/navigation";-import LyaoutHeader from "@/app/layout/LyaoutHeader";-import HomeHeader from "@/app/layout/HomeHeader";-import { homeHeaderRouterData } from "@/app/layout/routerData";-import { removeLocalePrefix } from "@/app/layout/layout.utils";+import { usePathname } from 'next/navigation'+import HomeHeader from '@/app/layout/HomeHeader'+import { removeLocalePrefix } from '@/app/layout/layout.utils'+import LyaoutHeader from '@/app/layout/LyaoutHeader'+import { homeHeaderRouterData } from '@/app/layout/routerData'export default function ConditionalHeader() {- const pathname = usePathname();- const currentPath = removeLocalePrefix(pathname).replace(/\/+$/, "") || "/";+ const pathname = usePathname()+ const currentPath = removeLocalePrefix(pathname).replace(/\/+$/, '') || '/'const isActive = (href: string) => {- if (!href.startsWith("/")) return false;- const normalizedHref = href.replace(/\/+$/, "") || "/";- if (normalizedHref === "/") return currentPath === "/";- if (currentPath === normalizedHref) return true;- return currentPath.startsWith(normalizedHref + "/");- };+ if (!href.startsWith('/'))+ return false+ const normalizedHref = href.replace(/\/+$/, '') || '/'+ if (normalizedHref === '/')+ return currentPath === '/'+ if (currentPath === normalizedHref)+ return true+ return currentPath.startsWith(`${normalizedHref}/`)+ }- if (homeHeaderRouterData.value.some((v) => isActive(v.href))) {- return <HomeHeader />;+ if (homeHeaderRouterData.value.some(v => isActive(v.href))) {+ return <HomeHeader />}- return <LyaoutHeader />;+ return <LyaoutHeader />}diff --git a/project/web/src/app/layout/HomeHeader.tsx b/project/web/src/app/layout/HomeHeader.tsxindex faeb90d7..e22d9572 100644--- a/project/web/src/app/layout/HomeHeader.tsx+++ b/project/web/src/app/layout/HomeHeader.tsx@@ -1,55 +1,58 @@-import { ForwardedRef, forwardRef, memo, useState } from "react";-import { useTransClient } from "@/app/i18n/client";-import { usePathname, useRouter } from "next/navigation";-import { useUserStore } from "@/store/user";-import styles from "@/app/[lng]/styles/difyHome.module.scss";-import Image from "next/image";-import logo from "@/assets/images/logo.png";-import Link from "next/link";-import { Button } from "antd";-import { MenuOutlined, CloseOutlined } from "@ant-design/icons";-import { removeLocalePrefix } from "@/app/layout/layout.utils";-import { homeHeaderRouterData } from "@/app/layout/routerData";-import LanguageSwitcher from "@/components/common/LanguageSwitcher";+import type { ForwardedRef } from 'react'+import { CloseOutlined, MenuOutlined } from '@ant-design/icons'+import { Button } from 'antd'+import Image from 'next/image'+import Link from 'next/link'+import { usePathname, useRouter } from 'next/navigation'+import { forwardRef, memo, useState } from 'react'+import styles from '@/app/[lng]/styles/difyHome.module.scss'+import { useTransClient } from '@/app/i18n/client'+import { removeLocalePrefix } from '@/app/layout/layout.utils'+import { homeHeaderRouterData } from '@/app/layout/routerData'+import logo from '@/assets/images/logo.png'+import LanguageSwitcher from '@/components/common/LanguageSwitcher'+import { useUserStore } from '@/store/user'export interface IHomeHeaderRef { }export interface IHomeHeaderProps { }const HomeHeader = memo(- forwardRef(({ }: IHomeHeaderProps, ref: ForwardedRef<IHomeHeaderRef>) => {- const pathname = usePathname();- const { t } = useTransClient("home");- const router = useRouter();- const userStore = useUserStore();- const currentPath = removeLocalePrefix(pathname).replace(/\/+$/, "") || "/";- const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false);-+ forwardRef((_: IHomeHeaderProps, ref: ForwardedRef<IHomeHeaderRef>) => {+ const pathname = usePathname()+ const { t } = useTransClient('home')+ const router = useRouter()+ const userStore = useUserStore()+ const currentPath = removeLocalePrefix(pathname).replace(/\/+$/, '') || '/'+ const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false)/*** 切换移动端菜单显示状态*/const toggleMobileMenu = () => {- setIsMobileMenuOpen(!isMobileMenuOpen);- };+ setIsMobileMenuOpen(!isMobileMenuOpen)+ }/*** 关闭移动端菜单*/const closeMobileMenu = () => {- setIsMobileMenuOpen(false);- };+ setIsMobileMenuOpen(false)+ }/*** 判断链接是否为当前激活状态*/const isActive = (href: string) => {- if (!href.startsWith("/")) return false;- const normalizedHref = href.replace(/\/+$/, "") || "/";- if (normalizedHref === "/") return currentPath === "/";- if (currentPath === normalizedHref) return true;- return currentPath.startsWith(normalizedHref + "/");- };+ if (!href.startsWith('/'))+ return false+ const normalizedHref = href.replace(/\/+$/, '') || '/'+ if (normalizedHref === '/')+ return currentPath === '/'+ if (currentPath === normalizedHref)+ return true+ return currentPath.startsWith(`${normalizedHref}/`)+ }return (<>@@ -57,31 +60,31 @@ const HomeHeader = memo(<div className={styles.headerContainer}><divclassName={styles.logo}- style={{ cursor: "pointer" }}- onClick={() => router.push("/")}+ style={{ cursor: 'pointer' }}+ onClick={() => router.push('/')}><Image src={logo} alt="logo" width={50} />- <span className={styles.logoText}>{t("header.logo")}</span>+ <span className={styles.logoText}>{t('header.logo')}</span></div>{/* 桌面端导航 */}<nav className={styles.nav}>{homeHeaderRouterData.value.map((v) => {- if (v.href === "/") {- return null;+ if (v.href === '/') {+ return null}return (<Linkkey={v.title}- className={`${styles.navLink} ${isActive(v.href) ? styles.active : ""}`}+ className={`${styles.navLink} ${isActive(v.href) ? styles.active : ''}`}href={v.href}target="_blank"rel="noopener noreferrer"- style={{ paddingTop: "3px" }}+ style={{ paddingTop: '3px' }}>{v.title}</Link>- );+ )})}</nav>@@ -102,11 +105,11 @@ const HomeHeader = memo(<buttononClick={() => {- router.push("/accounts");+ router.push('/accounts')}}className={styles.getStartedBtn}>- {t("header.getStarted")}+ {t('header.getStarted')}</button></div></div>@@ -118,10 +121,10 @@ const HomeHeader = memo()}{/* 移动端侧边菜单 */}- <div className={`${styles.mobileMenu} ${isMobileMenuOpen ? styles.mobileMenuOpen : ""}`}>+ <div className={`${styles.mobileMenu} ${isMobileMenuOpen ? styles.mobileMenuOpen : ''}`}><div className={styles.mobileMenuHeader}><Image src={logo} alt="logo" width={40} />- <span className={styles.mobileMenuTitle}>{t("header.logo")}</span>+ <span className={styles.mobileMenuTitle}>{t('header.logo')}</span><buttonclassName={styles.mobileMenuClose}onClick={closeMobileMenu}@@ -133,13 +136,13 @@ const HomeHeader = memo(<nav className={styles.mobileMenuNav}>{homeHeaderRouterData.value.map((v) => {- if (v.href === "/") {- return null;+ if (v.href === '/') {+ return null}return (<Linkkey={v.title}- className={`${styles.mobileNavLink} ${isActive(v.href) ? styles.active : ""}`}+ className={`${styles.mobileNavLink} ${isActive(v.href) ? styles.active : ''}`}href={v.href}target="_blank"rel="noopener noreferrer"@@ -147,7 +150,7 @@ const HomeHeader = memo(>{v.title}</Link>- );+ )})}</nav>@@ -159,8 +162,8 @@ const HomeHeader = memo(</div></div></>- );+ )}),-);+)-export default HomeHeader;+export default HomeHeaderdiff --git a/project/web/src/app/layout/LyaoutHeader.tsx b/project/web/src/app/layout/LyaoutHeader.tsxindex ea75f0bf..347acb09 100644--- a/project/web/src/app/layout/LyaoutHeader.tsx+++ b/project/web/src/app/layout/LyaoutHeader.tsx@@ -1,79 +1,79 @@-"use client";+'use client'-import {+import type {ForwardedRef,- forwardRef,- memo,- useMemo,- useRef,- useState,-} from "react";-import styles from "./styles/lyaoutHeader.module.scss";-import { useUserStore } from "@/store/user";-import Link from "next/link";-import Image from "next/image";-import LayoutNav from "@/app/layout/layoutNav";-import { NoSSR } from "@kwooshung/react-no-ssr";-import { Button, Badge, Popover } from "antd";+} from 'react'import {ArrowLeftOutlined,BellOutlined,BookOutlined,CrownOutlined,-} from "@ant-design/icons";-import { useRouter } from "next/navigation";-import { useTransClient } from "@/app/i18n/client";-import { useGetClientLng } from "@/hooks/useSystem";-import NotificationPanel from "@/components/notification/NotificationPanel";-import { useNotification } from "@/hooks/useNotification";-import SignInCalendar from "@/components/SignInCalendar";-import VipContentModal from "@/components/modals/VipContentModal";-import PointsDetailModal from "@/components/modals/PointsDetailModal";-import LanguageSwitcher from "@/components/common/LanguageSwitcher";-import {- UserOutlined,FileTextOutlined,GithubOutlined,LogoutOutlined,QuestionCircleOutlined,-} from "@ant-design/icons";+ UserOutlined,+} from '@ant-design/icons'+import { NoSSR } from '@kwooshung/react-no-ssr'+import { Badge, Button, Popover } from 'antd'+import Image from 'next/image'+import Link from 'next/link'+import { useRouter } from 'next/navigation'+import {+ forwardRef,+ memo,+ useMemo,+ useRef,+ useState,+} from 'react'+import { useTransClient } from '@/app/i18n/client'+import LayoutNav from '@/app/layout/layoutNav'+import logo from '@/assets/images/logo.png'+import LanguageSwitcher from '@/components/common/LanguageSwitcher'+import PointsDetailModal from '@/components/modals/PointsDetailModal'+import VipContentModal from '@/components/modals/VipContentModal'+import NotificationPanel from '@/components/notification/NotificationPanel'+import SignInCalendar from '@/components/SignInCalendar'+import { useNotification } from '@/hooks/useNotification'+import { useGetClientLng } from '@/hooks/useSystem'+import { useUserStore } from '@/store/user'-import logo from "@/assets/images/logo.png";+import styles from './styles/lyaoutHeader.module.scss'export interface ILyaoutHeaderRef { }export interface ILyaoutHeaderProps { }function UserInfo() {- const userInfo = useUserStore((state) => state.userInfo)!;- const router = useRouter();- const { t } = useTransClient("common");+ const userInfo = useUserStore(state => state.userInfo)!+ const router = useRouter()+ const { t } = useTransClient('common')const menuItems = useMemo(() => {return [{href: `/profile`,- label: t("profile"),+ label: t('profile'),icon: <UserOutlined />,},{href: `/income`,- label: t("header.income"),+ label: t('header.income'),icon: <FileTextOutlined />,border: true,},{href: `https://docs.aitoearn.ai/`,- label: t("docs"),+ label: t('docs'),icon: <BookOutlined />,},{- label: t("support"),+ label: t('support'),icon: <QuestionCircleOutlined />,- href: "https://github.com/yikart/AiToEarn/issues",+ href: 'https://github.com/yikart/AiToEarn/issues',},{- label: "Github",+ label: 'Github',icon: <GithubOutlined />,href: `https://github.com/yikart/AiToEarn`,subtitle: (@@ -82,42 +82,42 @@ function UserInfo() {},{onClick: () => {- useUserStore.getState().logout();- router.push(`/`);+ useUserStore.getState().logout()+ router.push(`/`)},- label: t("logout"),+ label: t('logout'),icon: <LogoutOutlined />,},- ];- }, [router, t]);+ ]+ }, [router, t])const avatar = (<Image- className={styles["layoutHeader-userinfo-avatar"]}+ className={styles['layoutHeader-userinfo-avatar']}src={userInfo?.avatar || logo}- alt={t("profile")}+ alt={t('profile')}width={35}height={35}style={{- borderRadius: "50%",- backgroundColor: "#e9d5ff",- padding: "3px",+ borderRadius: '50%',+ backgroundColor: '#e9d5ff',+ padding: '3px',}}/>- );+ )return (- <div className={styles["layoutHeader-userinfo__wrapper"]}>+ <div className={styles['layoutHeader-userinfo__wrapper']}><Popoverplacement="bottomLeft"arrow={false}- styles={{ body: { padding: "0" } }}- content={+ styles={{ body: { padding: '0' } }}+ content={(<div className={styles.layoutHeaderMenu}><div className="layoutHeaderMenu-head"><div className="layoutHeaderMenu-head-info"><span className="layoutHeaderMenu-head-info-name">- {userInfo?.name || t("unknownUser")}+ {userInfo?.name || t('unknownUser')}</span><span className="layoutHeaderMenu-head-info-mail">{userInfo.mail}@@ -129,11 +129,11 @@ function UserInfo() {{menuItems.map((v) => {return (<a- className={`layoutHeaderMenu-item ${v.border ? "layoutHeaderMenu-item--border" : ""}`}+ className={`layoutHeaderMenu-item ${v.border ? 'layoutHeaderMenu-item--border' : ''}`}href={v.href}key={v.label}title={v.label}- target={v.href?.includes("https://") ? "_blank" : "_self"}+ target={v.href?.includes('https://') ? '_blank' : '_self'}onClick={v.onClick}><p className="layoutHeaderMenu-item-label">@@ -146,56 +146,55 @@ function UserInfo() {: v.href && (<ArrowLeftOutlinedstyle={{- transform: "rotate(140deg)",- fontSize: "12px",+ transform: 'rotate(140deg)',+ fontSize: '12px',}}/>)}</div></a>- );+ )})}</div></div>- }+ )}>- <div className={styles["layoutHeader-userinfo"]}>{avatar}</div>+ <div className={styles['layoutHeader-userinfo']}>{avatar}</div></Popover></div>- );+ )}-const LyaoutHeader = memo(- forwardRef(({ }: ILyaoutHeaderProps, ref: ForwardedRef<ILyaoutHeaderRef>) => {- const userStore = useUserStore();- const layoutHeader = useRef<HTMLDivElement>(null);- const router = useRouter();- const { t } = useTransClient("common");- const { t: tVip } = useTransClient("vip");- const lng = useGetClientLng();- const [notificationVisible, setNotificationVisible] = useState(false);- const [vipModalVisible, setVipModalVisible] = useState(false);- const [pointsModalVisible, setPointsModalVisible] = useState(false);- const { unreadCount } = useNotification();+ forwardRef((_: ILyaoutHeaderProps, ref: ForwardedRef<ILyaoutHeaderRef>) => {+ const userStore = useUserStore()+ const layoutHeader = useRef<HTMLDivElement>(null)+ const router = useRouter()+ const { t } = useTransClient('common')+ const { t: tVip } = useTransClient('vip')+ const lng = useGetClientLng()+ const [notificationVisible, setNotificationVisible] = useState(false)+ const [vipModalVisible, setVipModalVisible] = useState(false)+ const [pointsModalVisible, setPointsModalVisible] = useState(false)+ const { unreadCount } = useNotification()- const [isVisible, setIsVisible] = useState(true);- const [isClosing, setIsClosing] = useState(false);+ const [isVisible, setIsVisible] = useState(true)+ const [isClosing, setIsClosing] = useState(false)const handleClose = (e: React.MouseEvent) => {- e.stopPropagation();- setIsClosing(true);+ e.stopPropagation()+ setIsClosing(true)// 等待动画完成后再隐藏元素setTimeout(() => {- setIsVisible(false);- }, 300);- };+ setIsVisible(false)+ }, 300)+ }return (<><div ref={layoutHeader} className={styles.layoutHeader}><div className={styles.layoutHeader_wrapper}>- <div className={styles["layoutHeader_wrapper-left"]}>- <h1 className={styles["layoutHeader_wrapper-logo"]}>+ <div className={styles['layoutHeader_wrapper-left']}>+ <h1 className={styles['layoutHeader_wrapper-logo']}><Link href="/"><Image src={logo} alt="AIToEarn" width={50} /></Link>@@ -204,18 +203,18 @@ const LyaoutHeader = memo(</div><div- className={styles["layoutHeader_wrapper-right"]}+ className={styles['layoutHeader_wrapper-right']}suppressHydrationWarning={true}><LanguageSwitcherclassName={styles.languageButton}style={{- display: "flex",- alignItems: "center",- gap: "8px",- padding: "4px 8px",- height: "auto",- fontSize: "12px",+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ padding: '4px 8px',+ height: 'auto',+ fontSize: '12px',}}/><NoSSR>@@ -223,52 +222,52 @@ const LyaoutHeader = memo(<SignInCalendar className={styles.signInCalendarButton} />)}{/* 会员状态显示 */}- {userStore.token &&- (() => {+ {userStore.token+ && (() => {// 判断是否为有效会员:有vipInfo且未过期- const isVip =- userStore.userInfo?.vipInfo &&- userStore.userInfo.vipInfo.expireTime &&- new Date(userStore.userInfo.vipInfo.expireTime) >- new Date();+ const isVip+ = userStore.userInfo?.vipInfo+ && userStore.userInfo.vipInfo.expireTime+ && new Date(userStore.userInfo.vipInfo.expireTime)+ > new Date()return (<Buttontype="text"- icon={+ icon={(<CrownOutlinedstyle={{fontSize: 18,- color: isVip ? "#F5AB03" : "#999",+ color: isVip ? '#F5AB03' : '#999',}}/>- }+ )}onClick={() => setVipModalVisible(true)}- style={{ position: "relative", marginTop: -14 }}+ style={{ position: 'relative', marginTop: -14 }}><spanstyle={{- position: "absolute",- top: "28px",- width: "55px",- right: "-4px",- background: "rgb(245, 171, 3)",- color: "white",- fontSize: "8px",- fontWeight: "bold",- padding: "1px 4px",- borderRadius: "8px",- lineHeight: "10px",- minWidth: "16px",- textAlign: "center",+ position: 'absolute',+ top: '28px',+ width: '55px',+ right: '-4px',+ background: 'rgb(245, 171, 3)',+ color: 'white',+ fontSize: '8px',+ fontWeight: 'bold',+ padding: '1px 4px',+ borderRadius: '8px',+ lineHeight: '10px',+ minWidth: '16px',+ textAlign: 'center',}}>{isVip- ? tVip("membership" as any) || "Membership"- : tVip("upgrade" as any) || "Upgrade"}+ ? tVip('membership' as any) || 'Membership'+ : tVip('upgrade' as any) || 'Upgrade'}</span></Button>- );+ )})()}{/* 通知 */}{userStore.token && (@@ -281,36 +280,40 @@ const LyaoutHeader = memo(/></Badge>)}- {userStore.token ? (- <UserInfo />- ) : (- <Button- onClick={() => {- router.push(`/${lng}/login`);- }}- >- {t("login")}- </Button>- )}+ {userStore.token+ ? (+ <UserInfo />+ )+ : (+ <Button+ onClick={() => {+ router.push(`/${lng}/login`)+ }}+ >+ {t('login')}+ </Button>+ )}</NoSSR></div></div></div><div className={`${styles.releaseBanner} ${isClosing ? styles.bannerClosing : ''}`}>- <div className={styles.bannerContent} onClick={() => setVipModalVisible(true)}> {/* 点击横幅打开VIP弹窗,而不是跳转 */}- <span className={styles.releaseText}>Join Plus — Enjoy Unlimited Free Sora-2, Nano Banana!</span>- </div>- <button- className={styles.closeButton}- onClick={handleClose}- aria-label="关闭横幅"- >- <svg width="14" height="14" viewBox="0 0 14 14" fill="none">- <path d="M1 1l12 12M13 1L1 13" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />- </svg>- </button>- </div>+ <div className={styles.bannerContent} onClick={() => setVipModalVisible(true)}>+ {' '}+ {/* 点击横幅打开VIP弹窗,而不是跳转 */}+ <span className={styles.releaseText}>Join Plus — Enjoy Unlimited Free Sora-2, Nano Banana!</span>+ </div>+ <button+ className={styles.closeButton}+ onClick={handleClose}+ aria-label="关闭横幅"+ >+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none">+ <path d="M1 1l12 12M13 1L1 13" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />+ </svg>+ </button>+ </div>{/* Notification Panel */}<NotificationPanel@@ -328,8 +331,8 @@ const LyaoutHeader = memo(onClose={() => setPointsModalVisible(false)}/></>- );+ )}),-);+)-export default LyaoutHeader;+export default LyaoutHeaderdiff --git a/project/web/src/app/layout/Providers.tsx b/project/web/src/app/layout/Providers.tsxindex 6c032d52..f6c2508f 100644--- a/project/web/src/app/layout/Providers.tsx+++ b/project/web/src/app/layout/Providers.tsx@@ -1,60 +1,60 @@-"use client";+'use client'-import { GoogleOAuthProvider } from "@react-oauth/google";-import { ConfigProvider, App, notification } from "antd";-import { AntdRegistry } from "@ant-design/nextjs-registry";-import { Suspense, useEffect } from "react";-import type { Locale } from "antd/es/locale";-import zh_CN from "antd/es/locale/zh_CN";-import en_US from "antd/es/locale/en_US";-import { fallbackLng } from "@/app/i18n/settings";-import useCssVariables from "@/app/hooks/useCssVariables";-import { useAccountStore } from "@/store/account";-import { useUserStore } from "@/store/user";-import { useCommontStore } from "@/store/commont";+import type { Locale } from 'antd/es/locale'+import { AntdRegistry } from '@ant-design/nextjs-registry'+import { GoogleOAuthProvider } from '@react-oauth/google'+import { App, ConfigProvider, notification } from 'antd'+import en_US from 'antd/es/locale/en_US'+import zh_CN from 'antd/es/locale/zh_CN'+import { Suspense, useEffect } from 'react'+import useCssVariables from '@/app/hooks/useCssVariables'+import { fallbackLng } from '@/app/i18n/settings'+import { useAccountStore } from '@/store/account'+import { useCommontStore } from '@/store/commont'+import { useUserStore } from '@/store/user'// antd 语言获取-const getAntdLang = (lang: string): Locale => {+function getAntdLang(lang: string): Locale {switch (lang) {- case "zh-CN":- return zh_CN;- case "en":- return en_US;+ case 'zh-CN':+ return zh_CN+ case 'en':+ return en_US}- return getAntdLang(fallbackLng);-};+ return getAntdLang(fallbackLng)+}export function Providers({children,lng,}: {- children: React.ReactNode;- lng: string;+ children: React.ReactNode+ lng: string}) {- const cssVariables = useCssVariables();+ const cssVariables = useCssVariables()const [api, contextHolder] = notification.useNotification({top: 74,- });+ })useEffect(() => {- const urlParams = new URLSearchParams(window.location.search);- const queryToken = urlParams.get("token");+ const urlParams = new URLSearchParams(window.location.search)+ const queryToken = urlParams.get('token')if (queryToken) {- useUserStore.getState().setToken(queryToken);+ useUserStore.getState().setToken(queryToken)}if (useUserStore.getState().token) {- useUserStore.getState().getUserInfo();- useAccountStore.getState().accountInit();+ useUserStore.getState().getUserInfo()+ useAccountStore.getState().accountInit()}- }, []);+ }, [])useEffect(() => {- useCommontStore.getState().setNotification(api);- }, [api]);+ useCommontStore.getState().setNotification(api)+ }, [api])useEffect(() => {- useUserStore.getState().setLang(lng);- }, [lng]);+ useUserStore.getState().setLang(lng)+ }, [lng])return (<GoogleOAuthProvider clientId="1094109734611-flskoscgp609mecqk9ablvc6i3205vqk.apps.googleusercontent.com">@@ -62,7 +62,7 @@ export function Providers({locale={getAntdLang(lng)}theme={{token: {- colorPrimary: cssVariables["--theColor5"],+ colorPrimary: cssVariables['--theColor5'],},}}>@@ -76,5 +76,5 @@ export function Providers({</App></ConfigProvider></GoogleOAuthProvider>- );+ )}diff --git a/project/web/src/app/layout/layout.utils.ts b/project/web/src/app/layout/layout.utils.tsindex 64745fee..5e3c57c4 100644--- a/project/web/src/app/layout/layout.utils.ts+++ b/project/web/src/app/layout/layout.utils.ts@@ -1,3 +1,3 @@export function removeLocalePrefix(path: string): string {- return path.replace(/^\/[a-z]{2}(-[A-Z]{2})?/, "") || "/";+ return path.replace(/^\/[a-z]{2}(-[A-Z]{2})?/, '') || '/'}diff --git a/project/web/src/app/layout/layoutNav.tsx b/project/web/src/app/layout/layoutNav.tsxindex 369b7241..5ad20726 100644--- a/project/web/src/app/layout/layoutNav.tsx+++ b/project/web/src/app/layout/layoutNav.tsx@@ -1,21 +1,23 @@-"use client";+'use client'-import styles from "@/app/layout/styles/layoutNav.module.scss";-import {+import type {IRouterDataItem,+} from '@/app/layout/routerData'+import { MenuFoldOutlined, RightOutlined, UpOutlined } from '@ant-design/icons'+import { Badge, Drawer, Menu } from 'antd'+import Image from 'next/image'+import Link from 'next/link'+import { useRouter, useSelectedLayoutSegments } from 'next/navigation'+import React, { useEffect, useRef, useState } from 'react'+import { apiGetNotViewCount } from '@/api/task'+import { useTransClient } from '@/app/i18n/client'+import {peRouterData,routerData,-} from "@/app/layout/routerData";-import Link from "next/link";-import { MenuFoldOutlined, RightOutlined, UpOutlined } from "@ant-design/icons";-import Image from "next/image";-import React, { useEffect, useRef, useState } from "react";-import { Drawer, Menu, Badge } from "antd";-import { useRouter, useSelectedLayoutSegments } from "next/navigation";-import { useTransClient } from "@/app/i18n/client";-import { useGetClientLng } from "@/hooks/useSystem";-import { apiGetNotViewCount } from "@/api/task";-import { useUserStore } from "@/store/user";+} from '@/app/layout/routerData'+import styles from '@/app/layout/styles/layoutNav.module.scss'+import { useGetClientLng } from '@/hooks/useSystem'+import { useUserStore } from '@/store/user'/***@@ -24,28 +26,30 @@ import { useUserStore } from "@/store/user";* @param unreadCount 未读任务数量*/function getNameTag(child: IRouterDataItem, iconLoca: number = 1, unreadCount?: number) {- const { t } = useTransClient("route");- const lng = useGetClientLng();- const path = child.path || "/";+ const { t } = useTransClient('route')+ const lng = useGetClientLng()+ const path = child.path || '/'// 确保路径包含语言前缀- const fullPath = path.startsWith('/') ? `/${lng}${path}` : `/${lng}/${path}`;+ const fullPath = path.startsWith('/') ? `/${lng}${path}` : `/${lng}/${path}`// 判断是否是任务中心- const isTasksRoute = child.path === '/tasks';- const showBadge = isTasksRoute && unreadCount && unreadCount > 0;+ const isTasksRoute = child.path === '/tasks'+ const showBadge = isTasksRoute && unreadCount && unreadCount > 0return (<>{!child.children ? (- <Link href={fullPath} target={path[0] === "/" ? "_self" : "_blank"}>- {showBadge ? (- <Badge count={unreadCount} offset={[10, 0]} style={{ backgroundColor: '#ff4d4f' }}>- <span>{t(child.translationKey as any)}</span>- </Badge>- ) : (- t(child.translationKey as any)- )}+ <Link href={fullPath} target={path[0] === '/' ? '_self' : '_blank'}>+ {showBadge+ ? (+ <Badge count={unreadCount} offset={[10, 0]} style={{ backgroundColor: '#ff4d4f' }}>+ <span>{t(child.translationKey as any)}</span>+ </Badge>+ )+ : (+ t(child.translationKey as any)+ )}</Link>) : (<span>@@ -56,12 +60,12 @@ function getNameTag(child: IRouterDataItem, iconLoca: number = 1, unreadCount?:) : (t(child.translationKey as any))}- {child.children &&- (iconLoca === 0 ? <UpOutlined /> : <RightOutlined />)}+ {child.children+ && (iconLoca === 0 ? <UpOutlined /> : <RightOutlined />)}</span>)}</>- );+ )}/**@@ -69,37 +73,38 @@ function getNameTag(child: IRouterDataItem, iconLoca: number = 1, unreadCount?:* @param child* @param unreadCount 未读任务数量*/-function RecursionNav({ child, unreadCount }: { child: IRouterDataItem; unreadCount?: number }) {+function RecursionNav({ child, unreadCount }: { child: IRouterDataItem, unreadCount?: number }) {return (child.children && (- <ul className={styles["recursionNav"]}>+ <ul className={styles.recursionNav}>{child.children.map((v) => {return (<li key={v.name}>{getNameTag(v, 1, unreadCount)}{v.children && <RecursionNav child={v} unreadCount={unreadCount} />}</li>- );+ )})}</ul>)- );+ )}function ParcelTag({child,children,}: {- child: IRouterDataItem;- children: React.ReactNode;+ child: IRouterDataItem+ children: React.ReactNode}) {if (child.children) {- return <>{children}</>;- } else {- const lng = useGetClientLng();- const path = child.path || "/";- const fullPath = path.startsWith('/') ? `/${lng}${path}` : `/${lng}/${path}`;- return <Link href={fullPath}>{children}</Link>;+ return <>{children}</>+ }+ else {+ const lng = useGetClientLng()+ const path = child.path || '/'+ const fullPath = path.startsWith('/') ? `/${lng}${path}` : `/${lng}/${path}`+ return <Link href={fullPath}>{children}</Link>}}@@ -114,52 +119,56 @@ function ChildNav({visible,unreadCount,}: {- child: IRouterDataItem;- visible: boolean;- unreadCount?: number;+ child: IRouterDataItem+ visible: boolean+ unreadCount?: number}) {- const elRef = useRef<HTMLUListElement | null>(null);- const [height, setHeight] = useState("auto");- const animaTime = 0.3;- const timer = useRef<NodeJS.Timeout>();- const { t } = useTransClient("route");+ const elRef = useRef<HTMLUListElement | null>(null)+ const [height, setHeight] = useState('auto')+ const animaTime = 0.3+ const timer = useRef<NodeJS.Timeout>()+ const { t } = useTransClient('route')useEffect(() => {- if (!elRef.current) return;- const h = elRef.current!.offsetHeight;- if (h === 0) return;- setHeight(`${h}px`);- }, []);+ if (!elRef.current)+ return+ const h = elRef.current!.offsetHeight+ if (h === 0)+ return+ setHeight(`${h}px`)+ }, [])useEffect(() => {- if (height !== "auto") {+ if (height !== 'auto') {setTimeout(() => {- elRef.current!.style.visibility = "visible";- elRef.current!.style.transition = animaTime + "s";- }, 1);+ elRef.current!.style.visibility = 'visible'+ elRef.current!.style.transition = `${animaTime}s`+ }, 1)}- }, [height]);+ }, [height])useEffect(() => {- if (!elRef.current) return;+ if (!elRef.current)+ returnif (visible) {timer.current = setTimeout(() => {- elRef.current!.style.overflow = "visible";- }, animaTime * 1000);- } else {- elRef.current!.style.overflow = "hidden";- clearTimeout(timer.current);+ elRef.current!.style.overflow = 'visible'+ }, animaTime * 1000)}- }, [visible]);+ else {+ elRef.current!.style.overflow = 'hidden'+ clearTimeout(timer.current)+ }+ }, [visible])return (child.children && (<ulref={elRef}- className={styles["layoutNavPC-one"]}+ className={styles['layoutNavPC-one']}style={- visible || height === "auto"- ? { height: height }+ visible || height === 'auto'+ ? { height }: { height: 0, padding: 0 }}>@@ -167,18 +176,20 @@ function ChildNav({return (<li key={v1.name}><div- className={styles["layoutNavPC-one-item"]}+ className={styles['layoutNavPC-one-item']}style={{ backgroundImage: v1.backColor }}><ParcelTag child={v1}>- <div className={styles["layoutNavPC-one-icon"]}>- {v1.icon ? (- <Image src={v1.icon!} alt="icon" width={20} />- ) : (- ""- )}+ <div className={styles['layoutNavPC-one-icon']}>+ {v1.icon+ ? (+ <Image src={v1.icon!} alt="icon" width={20} />+ )+ : (+ ''+ )}</div>- <span className={styles["layoutNavPC-one-text"]}>+ <span className={styles['layoutNavPC-one-text']}>{t(v1.translationKey as any)}</span>{v1.children && <RightOutlined />}@@ -186,49 +197,52 @@ function ChildNav({</div><RecursionNav child={v1} unreadCount={unreadCount} /></li>- );+ )})}</ul>)- );+ )}function NavPC() {- const [activeNav, setActiveNav] = useState("");- const [unreadCount, setUnreadCount] = useState(0);- const timer = useRef<NodeJS.Timeout>();- const route = useSelectedLayoutSegments();- const { t } = useTransClient("route");- const token = useUserStore((state) => state.token);+ const [activeNav, setActiveNav] = useState('')+ const [unreadCount, setUnreadCount] = useState(0)+ const timer = useRef<NodeJS.Timeout>()+ const route = useSelectedLayoutSegments()+ const { t } = useTransClient('route')+ const token = useUserStore(state => state.token)// 获取未读任务数量useEffect(() => {const fetchUnreadCount = async () => {- if (!token) return;+ if (!token)+ returntry {- const response: any = await apiGetNotViewCount();+ const response: any = await apiGetNotViewCount()if (response) {- setUnreadCount(response.data || 0);+ setUnreadCount(response.data || 0)}- } catch (error) {- console.error("获取未读任务数量失败:", error);}- };+ catch (error) {+ console.error('获取未读任务数量失败:', error)+ }+ }++ fetchUnreadCount()- fetchUnreadCount();-// 每30秒刷新一次未读数量- const interval = setInterval(fetchUnreadCount, 30000);-- return () => clearInterval(interval);- }, [token]);+ const interval = setInterval(fetchUnreadCount, 30000)++ return () => clearInterval(interval)+ }, [token])- let currRouter = "/";+ let currRouter = '/'if (route.length === 1) {- currRouter = route[0];- currRouter = currRouter === "/" ? currRouter : "/" + currRouter;- } else {- currRouter = "/" + route.slice(0, 2).join("/");+ currRouter = route[0]+ currRouter = currRouter === '/' ? currRouter : `/${currRouter}`+ }+ else {+ currRouter = `/${route.slice(0, 2).join('/')}`}return (@@ -239,17 +253,17 @@ function NavPC() {key={v1.name}className={activeNav === v1.name || v1.path === currRouter- ? styles["layoutNavPC-item-active"]- : ""+ ? styles['layoutNavPC-item-active']+ : ''}onMouseEnter={() => {- setActiveNav(v1.children ? v1.name : "");- clearTimeout(timer.current);+ setActiveNav(v1.children ? v1.name : '')+ clearTimeout(timer.current)}}onMouseLeave={() => {timer.current = setTimeout(() => {- setActiveNav("");- }, 300);+ setActiveNav('')+ }, 300)}}>{getNameTag(v1, 0, unreadCount)}@@ -260,67 +274,71 @@ function NavPC() {unreadCount={unreadCount}/></li>- );+ )})}</ul>- );+ )}function NavPE() {- const [open, setOpen] = useState(false);- const [unreadCount, setUnreadCount] = useState(0);- const router = useRouter();- const { t } = useTransClient("route");- const lng = useGetClientLng();- const token = useUserStore((state) => state.token);+ const [open, setOpen] = useState(false)+ const [unreadCount, setUnreadCount] = useState(0)+ const router = useRouter()+ const { t } = useTransClient('route')+ const lng = useGetClientLng()+ const token = useUserStore(state => state.token)// 获取未读任务数量useEffect(() => {const fetchUnreadCount = async () => {- if (!token) return;+ if (!token)+ returntry {- const response: any = await apiGetNotViewCount();+ const response: any = await apiGetNotViewCount()if (response && response.code === 0 && response.data) {- setUnreadCount(response.data || 0);+ setUnreadCount(response.data || 0)}- } catch (error) {- console.error("获取未读任务数量失败:", error);}- };+ catch (error) {+ console.error('获取未读任务数量失败:', error)+ }+ }// fetchUnreadCount();-+// 每30秒刷新一次未读数量- const interval = setInterval(fetchUnreadCount, 50000);-- return () => clearInterval(interval);- }, [token]);+ const interval = setInterval(fetchUnreadCount, 50000)++ return () => clearInterval(interval)+ }, [token])const translatedMenuItems = routerData.map((item) => {// 判断是否是任务中心,需要显示徽章- const isTasksRoute = item.path === '/tasks';- const showBadge = isTasksRoute && unreadCount > 0;+ const isTasksRoute = item.path === '/tasks'+ const showBadge = isTasksRoute && unreadCount > 0return {key: item.path || item.name,- label: showBadge ? (- <Badge count={unreadCount} style={{ backgroundColor: '#ff4d4f' }}>- <span style={{ marginRight: '20px' }}>{t(item.translationKey as any)}</span>- </Badge>- ) : (- t(item.translationKey as any)- ),- children: item.children?.map((child) => ({+ label: showBadge+ ? (+ <Badge count={unreadCount} style={{ backgroundColor: '#ff4d4f' }}>+ <span style={{ marginRight: '20px' }}>{t(item.translationKey as any)}</span>+ </Badge>+ )+ : (+ t(item.translationKey as any)+ ),+ children: item.children?.map(child => ({key: child.path || child.name,label: t(child.translationKey as any),})),- };- });+ }+ })const handleMenuClick = (e: { key: string }) => {// 确保使用当前语言前缀- const targetPath = e.key.startsWith('/') ? e.key : `/${e.key}`;- const fullPath = `/${lng}${targetPath}`;+ const targetPath = e.key.startsWith('/') ? e.key : `/${e.key}`+ const fullPath = `/${lng}${targetPath}`// 调试信息console.log('Menu click debug:', {@@ -328,24 +346,24 @@ function NavPE() {lng,targetPath,fullPath,- currentPath: window.location.pathname- });+ currentPath: window.location.pathname,+ })// 先关闭菜单- setOpen(false);+ setOpen(false)// 使用 window.location.href 进行跳转,确保完全重新加载页面// 这样可以避免路由状态混乱的问题- window.location.href = fullPath;- };+ window.location.href = fullPath+ }return (<div className={styles.layoutNavPE}>- <div onClick={() => setOpen(true)} className={styles["layoutNavPE-menu"]}>+ <div onClick={() => setOpen(true)} className={styles['layoutNavPE-menu']}><MenuFoldOutlined /></div><Drawer- title={t("navigation")}+ title={t('navigation')}placement="right"onClose={() => setOpen(false)}width="85%"@@ -355,13 +373,13 @@ function NavPE() {className="layoutNavPE-menu"selectable={false}onClick={handleMenuClick}- style={{ width: "100%" }}+ style={{ width: '100%' }}mode="inline"items={translatedMenuItems}/></Drawer></div>- );+ )}function LayoutNav() {@@ -370,7 +388,7 @@ function LayoutNav() {<NavPC /><NavPE /></div>- );+ )}-export default LayoutNav;+export default LayoutNavdiff --git a/project/web/src/app/layout/routerData.ts b/project/web/src/app/layout/routerData.tsindex 094cc2b4..4c7c7cba 100644--- a/project/web/src/app/layout/routerData.ts+++ b/project/web/src/app/layout/routerData.ts@@ -1,21 +1,21 @@-import { StaticImageData } from "next/image";-import { MenuItemType } from "antd/es/menu/interface";-import { directTrans } from "@/app/i18n/client";-import { useUserStore } from "@/store/user";+import type { MenuItemType } from 'antd/es/menu/interface'+import type { StaticImageData } from 'next/image'+import { directTrans } from '@/app/i18n/client'+import { useUserStore } from '@/store/user'export interface IRouterDataItem {// 导航标题- name: string;+ name: string// 翻译键- translationKey: string;+ translationKey: string// 跳转链接- path?: string;+ path?: string// icon- icon?: StaticImageData;+ icon?: StaticImageData// 导航背景颜色- backColor?: string;+ backColor?: string// 子导航- children?: IRouterDataItem[];+ children?: IRouterDataItem[]}export const routerData: IRouterDataItem[] = [@@ -25,14 +25,14 @@ export const routerData: IRouterDataItem[] = [// path: "/",// },{- name: "发布",- translationKey: "accounts",- path: "/accounts",+ name: '发布',+ translationKey: 'accounts',+ path: '/accounts',},{- name: "互动数据",- translationKey: "interactive",- path: "/interactive",+ name: '互动数据',+ translationKey: 'interactive',+ path: '/interactive',},// {// name: "热门内容",@@ -40,49 +40,48 @@ export const routerData: IRouterDataItem[] = [// path: "/hotContent",// },{- name: "AI工具",- translationKey: "aiTools",- path: "/material/ai-generate",+ name: 'AI工具',+ translationKey: 'aiTools',+ path: '/material/ai-generate',},{- name: "任务中心",- translationKey: "tasks",- path: "/tasks",+ name: '任务中心',+ translationKey: 'tasks',+ path: '/tasks',},{- name: "数据统计",- translationKey: "dataStatistics",- path: "/dataStatistics",+ name: '数据统计',+ translationKey: 'dataStatistics',+ path: '/dataStatistics',},{- name: "素材库",- translationKey: "header.materialLibrary",- path: "/material",+ name: '素材库',+ translationKey: 'header.materialLibrary',+ path: '/material',},{- name: "草稿箱",- translationKey: "header.draftBox",- path: "/cgmaterial",+ name: '草稿箱',+ translationKey: 'header.draftBox',+ path: '/cgmaterial',},-];+]-const recursion = (- child: IRouterDataItem[] | undefined,-): MenuItemType[] | null => {- if (!child) return null;+function recursion(child: IRouterDataItem[] | undefined): MenuItemType[] | null {+ if (!child)+ return nullreturn child.map((v) => {return {label: v.name,key: v.path || v.name,children: recursion(v.children),- };- });-};+ }+ })+}-export const peRouterData = recursion(routerData);+export const peRouterData = recursion(routerData)/*** 首页头部导航数据(根据语言动态生成)@@ -91,43 +90,43 @@ export const peRouterData = recursion(routerData);*/export const homeHeaderRouterData = {get value() {- const lang = useUserStore.getState().lang;- const downloadHref = lang === "en"- ? "https://docs.aitoearn.ai/en/downloads"- : "https://docs.aitoearn.ai/zh/downloads";+ const lang = useUserStore.getState().lang+ const downloadHref = lang === 'en'+ ? 'https://docs.aitoearn.ai/en/downloads'+ : 'https://docs.aitoearn.ai/zh/downloads'return [{- href: "/",- title: directTrans("home", "header.nav.home"),+ href: '/',+ title: directTrans('home', 'header.nav.home'),},{- href: "/pricing",- title: directTrans("home", "header.nav.pricing"),+ href: '/pricing',+ title: directTrans('home', 'header.nav.pricing'),},{- href: "https://status.aitoearn.ai/",- title: directTrans("home", "header.nav.status"),+ href: 'https://status.aitoearn.ai/',+ title: directTrans('home', 'header.nav.status'),},{- href: "https://docs.aitoearn.ai/",- title: directTrans("home", "header.nav.docs"),+ href: 'https://docs.aitoearn.ai/',+ title: directTrans('home', 'header.nav.docs'),},{- href: "https://blog.aitoearn.ai/",- title: directTrans("home", "header.nav.blog"),+ href: 'https://blog.aitoearn.ai/',+ title: directTrans('home', 'header.nav.blog'),},{href: downloadHref,- title: directTrans("home", "header.nav.download"),+ title: directTrans('home', 'header.nav.download'),},{- href: "/hotContent",- title: directTrans("route", "hotContent"),+ href: '/hotContent',+ title: directTrans('route', 'hotContent'),},{- href: "/aiRank",- title: directTrans("route", "aiRank"),+ href: '/aiRank',+ title: directTrans('route', 'aiRank'),},- ];+ ]},-};+}diff --git a/project/web/src/app/layout/styles/layoutNav.module.scss b/project/web/src/app/layout/styles/layoutNav.module.scssindex cfd239ef..a80776a7 100644--- a/project/web/src/app/layout/styles/layoutNav.module.scss+++ b/project/web/src/app/layout/styles/layoutNav.module.scss@@ -2,7 +2,6 @@border: 1px solid #ccc;}-.layoutNavPC {display: flex;align-items: center;@@ -27,7 +26,8 @@margin-right: 30px;}&:hover {- & > span, & > a {+ & > span,+ & > a {color: var(--theColor4);}}@@ -75,7 +75,7 @@visibility: hidden;li {padding: 0 15px;- &:hover {+ &:hover {.layoutNavPC-one-item {span {color: var(--theColor4) !important;@@ -102,7 +102,8 @@justify-content: left;}}- .layoutNavPC-one-item, .layoutNavPC-one-item a {+ .layoutNavPC-one-item,+ .layoutNavPC-one-item a {display: flex;align-items: center;position: relative;@@ -139,11 +140,13 @@//width: 100px;position: relative;&:hover {- & > span, & > a {+ & > span,+ & > a {color: var(--theColor4) !important;}}- & > span, a {+ & > span,+ a {display: flex;align-items: center;justify-content: space-between;@@ -184,4 +187,3 @@color: #1890ff;}}-diff --git a/project/web/src/app/layout/styles/lyaoutFooter.module.scss b/project/web/src/app/layout/styles/lyaoutFooter.module.scssindex 98e6d268..b7a2dd37 100644--- a/project/web/src/app/layout/styles/lyaoutFooter.module.scss+++ b/project/web/src/app/layout/styles/lyaoutFooter.module.scss@@ -70,4 +70,4 @@}}}-}\ No newline at end of file+}diff --git a/project/web/src/app/layout/styles/lyaoutHeader.module.scss b/project/web/src/app/layout/styles/lyaoutHeader.module.scssindex 7f6840cd..e5df963e 100644--- a/project/web/src/app/layout/styles/lyaoutHeader.module.scss+++ b/project/web/src/app/layout/styles/lyaoutHeader.module.scss@@ -18,7 +18,7 @@transition: all 0.3s ease;max-height: 100px;opacity: 1;-+&:hover {background: linear-gradient(90deg, #4338ca 0%, #6d28d9 100%);}@@ -30,7 +30,10 @@padding-top: 0 !important;padding-bottom: 0 !important;opacity: 0 !important;- transition: max-height 0.3s ease, opacity 0.3s ease, padding 0.3s ease !important;+ transition:+ max-height 0.3s ease,+ opacity 0.3s ease,+ padding 0.3s ease !important;}.bannerContent {@@ -56,22 +59,22 @@border-radius: 4px;transition: all 0.2s ease;opacity: 0.8;-+&:hover {opacity: 1;background: rgba(255, 255, 255, 0.15);transform: translateY(-50%) rotate(90deg);}-+&:active {transform: translateY(-50%) scale(0.9) rotate(90deg);}-+svg {display: block;transition: transform 0.2s ease;}-+@media (max-width: 768px) {right: 8px;}@@ -178,7 +181,7 @@background-color: #f5f5f5;transform: scale(1.05);}-+.anticon {font-size: 18px;color: #666;@@ -189,16 +192,16 @@display: flex;align-items: center;justify-content: center;- border: 1px solid #EBEDEC;+ border: 1px solid #ebedec;height: 60px;border-radius: 30px;transition: all 0.3s ease;-+&:hover {background-color: #f5f5f5;transform: scale(1.05);}-+.anticon {font-size: 16px;color: #666;@@ -213,12 +216,12 @@height: 30px;border-radius: 50%;transition: all 0.3s ease;-+&:hover {background-color: #f5f5f5;transform: scale(1.05);}-+.anticon {font-size: 18px;color: #666;@@ -235,7 +238,7 @@position: relative;padding-left: 12.5px;&:after {- content: "";+ content: '';display: block;position: absolute;width: 5px;@@ -285,10 +288,12 @@min-width: 0;overflow: hidden;text-overflow: ellipsis;- &-name, &-mail {+ &-name,+ &-mail {@include omitText(1);}- &-name {}+ &-name {+ }&-mail {font-size: var(--fs-xs);color: var(--grayColor8);@@ -325,7 +330,7 @@&--border {position: relative;&:after {- content: "";+ content: '';display: block;position: absolute;width: 100%;@@ -348,11 +353,11 @@.languageButton {color: #333;- border: 1px solid #EBEDEC;+ border: 1px solid #ebedec;border-radius: 6px;box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);background: #fff;-+&:hover {color: #1890ff;border-color: #40a9ff;@@ -362,21 +367,21 @@.languageDropdown {:global {.ant-dropdown-menu {- border: 1px solid #EBEDEC;+ border: 1px solid #ebedec;border-radius: 6px;box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);padding: 4px 0;min-width: 140px;}-+.ant-dropdown-menu-item {padding: 8px 12px;border-radius: 4px;margin: 2px 4px;-+&:hover {background-color: #f5f5f5;}}}-}\ No newline at end of file+}diff --git a/project/web/src/app/styles/mixin.scss b/project/web/src/app/styles/mixin.scssindex 1668ff36..a26a8e10 100644--- a/project/web/src/app/styles/mixin.scss+++ b/project/web/src/app/styles/mixin.scss@@ -75,4 +75,4 @@border-top-color: $active-color;bottom: 0;}-}\ No newline at end of file+}diff --git a/project/web/src/app/styles/page.module.scss b/project/web/src/app/styles/page.module.scssindex e3a28c1c..4d243f66 100644--- a/project/web/src/app/styles/page.module.scss+++ b/project/web/src/app/styles/page.module.scss@@ -1,3 +1,3 @@.page {min-height: 80vh;-}\ No newline at end of file+}diff --git a/project/web/src/app/var.css b/project/web/src/app/var.cssindex 1d0e3378..ffcead9b 100644--- a/project/web/src/app/var.css+++ b/project/web/src/app/var.css@@ -2,19 +2,19 @@:root {/* 中性面板色组---------------------------------------------------- */--whiteColor: #fff;- --grayColor0: rgb(247,250,250);- --grayColor1: #F3F3F3;- --grayColor2: #EEEEEE;- --grayColor3: #E7E7E7;- --grayColor4: #DCDCDC;- --grayColor5: #C5C5C5;- --grayColor6: #A6A6A6;- --grayColor7: #8B8B8B;+ --grayColor0: rgb(247, 250, 250);+ --grayColor1: #f3f3f3;+ --grayColor2: #eeeeee;+ --grayColor3: #e7e7e7;+ --grayColor4: #dcdcdc;+ --grayColor5: #c5c5c5;+ --grayColor6: #a6a6a6;+ --grayColor7: #8b8b8b;--grayColor8: #777777;- --grayColor9: #5E5E5E;- --grayColor10: #4B4B4B;+ --grayColor9: #5e5e5e;+ --grayColor10: #4b4b4b;--grayColor11: #383838;- --grayColor12: #2C2C2C;+ --grayColor12: #2c2c2c;--grayColor13: #242424;--grayColor14: #181818;diff --git a/project/web/src/assets/fonts/font.css b/project/web/src/assets/fonts/font.cssindex b82f5a59..c86b7fec 100644--- a/project/web/src/assets/fonts/font.css+++ b/project/web/src/assets/fonts/font.css@@ -3,4 +3,4 @@src: url('./DIN-Medium.otf') format('opentype');font-weight: normal;font-style: normal;-}\ No newline at end of file+}diff --git a/project/web/src/components/AvatarPlat/avatarPlat.module.scss b/project/web/src/components/AvatarPlat/avatarPlat.module.scssindex 382d8c4c..62bbebe8 100644--- a/project/web/src/components/AvatarPlat/avatarPlat.module.scss+++ b/project/web/src/components/AvatarPlat/avatarPlat.module.scss@@ -10,14 +10,14 @@transform: translate(-10%, 20%);border-radius: 50%;}-+&.disabled {filter: grayscale(100%);opacity: 0.6;-+&:hover {filter: grayscale(100%);opacity: 0.6;}}-}\ No newline at end of file+}diff --git a/project/web/src/components/AvatarPlat/index.tsx b/project/web/src/components/AvatarPlat/index.tsxindex 21a51e01..a5dfcff7 100644--- a/project/web/src/components/AvatarPlat/index.tsx+++ b/project/web/src/components/AvatarPlat/index.tsx@@ -1,36 +1,38 @@-import { ForwardedRef, forwardRef, memo } from "react";-import styles from "./avatarPlat.module.scss";-import { AvatarSize } from "antd/es/avatar/AvatarContext";-import { SocialAccount } from "@/api/types/account.type";-import { Avatar } from "antd";-import { AccountPlatInfoMap } from "@/app/config/platConfig";-import { OSS_URL } from "@/constant";+import type { AvatarSize } from 'antd/es/avatar/AvatarContext'+import type { ForwardedRef } from 'react'+import type { SocialAccount } from '@/api/types/account.type'+import { Avatar } from 'antd'+import { forwardRef, memo } from 'react'+import { AccountPlatInfoMap } from '@/app/config/platConfig'+import { OSS_URL } from '@/constant'+import styles from './avatarPlat.module.scss'export interface IAvatarPlatRef {}export interface IAvatarPlatProps {- account?: SocialAccount;- size?: AvatarSize;- className?: string;- width?: number;- avatarWidth?: number;- disabled?: boolean;+ account?: SocialAccount+ size?: AvatarSize+ className?: string+ width?: number+ avatarWidth?: number+ disabled?: boolean}-const getAvatar = (url: string) => {- if (url?.includes("https://")) {- return url;- } else {- return `${OSS_URL}/` + url;+function getAvatar(url: string) {+ if (url?.includes('https://')) {+ return url}-};+ else {+ return `${OSS_URL}/${url}`+ }+}const AvatarPlat = memo(forwardRef(({account,- size = "default",+ size = 'default',className,width,avatarWidth,@@ -40,14 +42,14 @@ const AvatarPlat = memo() => {// 添加防护检查if (!account || !account.type) {- console.warn('AvatarPlat: account or account.type is undefined', account);- return null;+ console.warn('AvatarPlat: account or account.type is undefined', account)+ return null}- const plat = AccountPlatInfoMap.get(account.type);+ const plat = AccountPlatInfoMap.get(account.type)if (!plat) {- console.warn('AvatarPlat: platform not found for type', account.type);- return null;+ console.warn('AvatarPlat: platform not found for type', account.type)+ return null}return (@@ -55,7 +57,7 @@ const AvatarPlat = memo(<div className={`${styles.avatarPlat} ${className} ${disabled ? styles.disabled : ''}`}><Avatarsrc={getAvatar(account.avatar)}- size={avatarWidth ? avatarWidth : size}+ size={avatarWidth || size}style={disabled ? { opacity: 0.5 } : undefined}/><img@@ -64,7 +66,7 @@ const AvatarPlat = memo(!width? {width:- size === "large" ? 16 : size === "default" ? 12.5 : 10,+ size === 'large' ? 16 : size === 'default' ? 12.5 : 10,opacity: disabled ? 0.5 : 1,}: {@@ -75,9 +77,9 @@ const AvatarPlat = memo(/></div></>- );+ )},),-);+)-export default AvatarPlat;+export default AvatarPlatdiff --git a/project/web/src/components/Chat/index.tsx b/project/web/src/components/Chat/index.tsxindex 7fcedcba..f4932568 100644--- a/project/web/src/components/Chat/index.tsx+++ b/project/web/src/components/Chat/index.tsx@@ -1,40 +1,43 @@-import { ForwardedRef, forwardRef, memo, useEffect, useState } from "react";-import * as React from "react";-import { useGetClientLng } from "@/hooks/useSystem";+import type { ForwardedRef } from 'react'+import { forwardRef, memo, useEffect, useState } from 'react'+import * as React from 'react'+import { useGetClientLng } from '@/hooks/useSystem'export interface IChatRef {}export interface IChatProps {- defaultMask?: string;+ defaultMask?: string}const Chat = memo(forwardRef(({ defaultMask }: IChatProps, ref: ForwardedRef<IChatRef>) => {- const [iframeUrl, setIframeUrl] = useState("");- const lng = useGetClientLng();+ const [iframeUrl, setIframeUrl] = useState('')+ const lng = useGetClientLng()useEffect(() => {- const base = location.origin.includes("localhost")- ? "https://aitoearn.ai"- : location.origin;+ const base = location.origin.includes('localhost')+ ? 'https://aitoearn.ai'+ : location.origin- const params = new URLSearchParams();- if (defaultMask) params.set("mask", defaultMask);- if (lng) params.set("lang", lng);+ const params = new URLSearchParams()+ if (defaultMask)+ params.set('mask', defaultMask)+ if (lng)+ params.set('lang', lng)- const qs = params.toString();+ const qs = params.toString()setIframeUrl(- `${base}/chat${qs ? `?${qs}` : ""}${defaultMask ? "#/new-chat" : "#/chat"}`,- );- }, [defaultMask, lng]);+ `${base}/chat${qs ? `?${qs}` : ''}${defaultMask ? '#/new-chat' : '#/chat'}`,+ )+ }, [defaultMask, lng])return (<iframesrc={iframeUrl}- style={{ height: "100%", border: "none", width: "100%" }}+ style={{ height: '100%', border: 'none', width: '100%' }}/>- );+ )}),-);+)-export default Chat;+export default Chatdiff --git a/project/web/src/components/ChooseAccountModule/ChooseAccountModule.tsx b/project/web/src/components/ChooseAccountModule/ChooseAccountModule.tsxindex 1ae0e8a5..31f65989 100644--- a/project/web/src/components/ChooseAccountModule/ChooseAccountModule.tsx+++ b/project/web/src/components/ChooseAccountModule/ChooseAccountModule.tsx@@ -1,32 +1,35 @@-import {+import type {ForwardedRef,+} from 'react'+import type { SocialAccount } from '@/api/types/account.type'+import type {+ ISimpleAccountChooseProps,+ ISimpleAccountChooseRef,+} from '@/components/ChooseAccountModule/components/SimpleAccountChoose'+import { Modal } from 'antd'+import {forwardRef,memo,useEffect,useImperativeHandle,useRef,useState,-} from "react";-import { Modal } from "antd";-import SimpleAccountChoose, {- ISimpleAccountChooseProps,- ISimpleAccountChooseRef,-} from "@/components/ChooseAccountModule/components/SimpleAccountChoose";-import { SocialAccount } from "@/api/types/account.type";+} from 'react'+import SimpleAccountChoose from '@/components/ChooseAccountModule/components/SimpleAccountChoose'export interface IChooseAccountModuleRef {- getSimpleAccountChooseRef: () => ISimpleAccountChooseRef | null;+ getSimpleAccountChooseRef: () => ISimpleAccountChooseRef | null}export interface IChooseAccountModuleProps {- open: boolean;- onClose: (open: boolean) => void;+ open: boolean+ onClose: (open: boolean) => void// 简化账户选择props- simpleAccountChooseProps?: ISimpleAccountChooseProps;+ simpleAccountChooseProps?: ISimpleAccountChooseProps// 账户选择确认- onAccountConfirm?: (accounts: SocialAccount[]) => void;+ onAccountConfirm?: (accounts: SocialAccount[]) => void// 账户选择change- onAccountChange?: (accounts: SocialAccount[], account: SocialAccount) => void;+ onAccountChange?: (accounts: SocialAccount[], account: SocialAccount) => void}const ChooseAccountModule = memo(@@ -43,37 +46,38 @@ const ChooseAccountModule = memo() => {const [newChoosedAccounts, setNewChoosedAccounts] = useState<SocialAccount[]- >([]);- const simpleAccountChooseRef = useRef<ISimpleAccountChooseRef>(null);+ >([])+ const simpleAccountChooseRef = useRef<ISimpleAccountChooseRef>(null)const handleOk = () => {- if (onAccountConfirm) onAccountConfirm(newChoosedAccounts);- close();- };+ if (onAccountConfirm)+ onAccountConfirm(newChoosedAccounts)+ close()+ }const handleCancel = () => {- setNewChoosedAccounts(simpleAccountChooseProps?.choosedAccounts || []);- close();- };+ setNewChoosedAccounts(simpleAccountChooseProps?.choosedAccounts || [])+ close()+ }const close = () => {- onClose(false);- };+ onClose(false)+ }useEffect(() => {- setTimeout(() => simpleAccountChooseRef.current?.recover(), 1);- }, [simpleAccountChooseProps?.choosedAccounts]);+ setTimeout(() => simpleAccountChooseRef.current?.recover(), 1)+ }, [simpleAccountChooseProps?.choosedAccounts])useEffect(() => {- simpleAccountChooseRef.current?.init();- }, [open]);+ simpleAccountChooseRef.current?.init()+ }, [open])const ImperativeHandle: IChooseAccountModuleRef = {getSimpleAccountChooseRef() {- return simpleAccountChooseRef.current;+ return simpleAccountChooseRef.current},- };- useImperativeHandle(ref, () => ImperativeHandle);+ }+ useImperativeHandle(ref, () => ImperativeHandle)return (<Modal@@ -91,16 +95,17 @@ const ChooseAccountModule = memo(}ref={simpleAccountChooseRef}onChange={(accounts: SocialAccount[], account: SocialAccount) => {- setNewChoosedAccounts(accounts);- if (onAccountChange) onAccountChange(accounts, account);+ setNewChoosedAccounts(accounts)+ if (onAccountChange)+ onAccountChange(accounts, account)}}/>)}</Modal>- );+ )},),-);-ChooseAccountModule.displayName = "ChooseAccountModule";+)+ChooseAccountModule.displayName = 'ChooseAccountModule'-export default ChooseAccountModule;+export default ChooseAccountModulediff --git a/project/web/src/components/ChooseAccountModule/chooseAccountModule.module.scss b/project/web/src/components/ChooseAccountModule/chooseAccountModule.module.scssindex c0d536f7..ac66d377 100644--- a/project/web/src/components/ChooseAccountModule/chooseAccountModule.module.scss+++ b/project/web/src/components/ChooseAccountModule/chooseAccountModule.module.scss@@ -157,7 +157,7 @@}.ant-collapse-expand-icon {- color: #625BF2;+ color: #625bf2;}}@@ -205,7 +205,7 @@gap: 12px;&:hover {- border-color: #625BF2;+ border-color: #625bf2;box-shadow: 0 2px 8px rgba(98, 91, 242, 0.1);}@@ -268,8 +268,8 @@}&--active {- background: linear-gradient(135deg, #625BF2 0%, #925BF2 100%);- border-color: #625BF2;+ background: linear-gradient(135deg, #625bf2 0%, #925bf2 100%);+ border-color: #625bf2;color: #fff;.simpleAccountChoose-accounts-item-nickname {@@ -278,7 +278,7 @@.simpleAccountChoose-accounts-item-choose {background: #fff;- color: #625BF2;+ color: #625bf2;opacity: 1;}@@ -335,4 +335,4 @@}}}-}\ No newline at end of file+}diff --git a/project/web/src/components/ChooseAccountModule/components/PlatChoose.tsx b/project/web/src/components/ChooseAccountModule/components/PlatChoose.tsxindex 22b3f27a..5cd1a1aa 100644--- a/project/web/src/components/ChooseAccountModule/components/PlatChoose.tsx+++ b/project/web/src/components/ChooseAccountModule/components/PlatChoose.tsx@@ -1,14 +1,10 @@-import {+import type {ForwardedRef,- forwardRef,- memo,- useEffect,- useImperativeHandle,- useMemo,- useRef,- useState,-} from "react";-import styles from "../chooseAccountModule.module.scss";+} from 'react'+import type { SocialAccount } from '@/api/types/account.type'+import type { PlatType } from '@/app/config/platConfig'+import type { PubType } from '@/app/config/publishConfig'+import { CheckOutlined } from '@ant-design/icons'import {Avatar,Badge,@@ -17,44 +13,51 @@ import {Empty,Segmented,Tooltip,-} from "antd";-import { CheckOutlined } from "@ant-design/icons";-import { useShallow } from "zustand/react/shallow";-import useCssVariables from "@/app/hooks/useCssVariables";-import { AccountPlatInfoMap, PlatType } from "@/app/config/platConfig";-import { PubType } from "@/app/config/publishConfig";-import { useAccountStore } from "@/store/account";-import Link from "next/link";-import { SocialAccount } from "@/api/types/account.type";+} from 'antd'+import Link from 'next/link'+import {+ forwardRef,+ memo,+ useEffect,+ useImperativeHandle,+ useMemo,+ useRef,+ useState,+} from 'react'+import { useShallow } from 'zustand/react/shallow'+import { AccountPlatInfoMap } from '@/app/config/platConfig'+import useCssVariables from '@/app/hooks/useCssVariables'+import { useAccountStore } from '@/store/account'+import styles from '../chooseAccountModule.module.scss'export interface IPlatChooseRef {/*** 恢复选中状态* @param choosedAccounts*/- recover: () => void;+ recover: () => void// 每次关闭弹框的时候需要初始化一些状态- init: () => void;+ init: () => void// 设置选中平台- setActivePlat: (activePlat: PlatType) => void;+ setActivePlat: (activePlat: PlatType) => void}export interface IPlatChooseProps {- pubType: PubType;+ pubType: PubType// 默认选择的平台- defaultPlat?: PlatType;+ defaultPlat?: PlatTypeonChange?: (choosedAcounts: SocialAccount[],choosedAcount: SocialAccount,- ) => void;+ ) => void// 外部传入的已经选中的数据,这个值只有在确认更改才会更新- choosedAccounts?: SocialAccount[];+ choosedAccounts?: SocialAccount[]// 按平台 是否禁用多选,true=禁用,false=不禁用- disableAllSelect?: boolean;+ disableAllSelect?: boolean// 可选择的平台,默认为全部- allowPlatSet?: Set<PlatType>;+ allowPlatSet?: Set<PlatType>// 是否可以取消已经选择的账户,默认为 false- isCancelChooseAccount?: boolean;+ isCancelChooseAccount?: boolean}const PlatChoose = memo(@@ -71,147 +74,152 @@ const PlatChoose = memo(}: IPlatChooseProps,ref: ForwardedRef<IPlatChooseRef>,) => {- const cssVars = useCssVariables();+ const cssVars = useCssVariables()// 所有账户数据const [accountMap, setAccountMap] = useState<Map<PlatType, SocialAccount[]>- >(new Map());+ >(new Map())// 当前选择的平台- const [activePlat, setActivePlat] = useState<PlatType | undefined>();+ const [activePlat, setActivePlat] = useState<PlatType | undefined>()// 当前选择的账户数据const [choosedAcountMap, setChoosedAcountMap] = useState<Map<PlatType, SocialAccount[]>- >(new Map());+ >(new Map())// 每次change操作的数据- const recentData = useRef<SocialAccount>();+ const recentData = useRef<SocialAccount>()const { accountList } = useAccountStore(- useShallow((state) => ({+ useShallow(state => ({accountList: state.accountList,})),- );+ )// 经过 allowPlatSet 过滤后的账户数据const accountMapLast = useMemo(() => {- const newVal = new Map<PlatType, SocialAccount[]>();+ const newVal = new Map<PlatType, SocialAccount[]>()for (const [accountType, accountList] of accountMap) {if (!allowPlatSet ? true : allowPlatSet.has(accountType)) {- newVal.set(accountType, accountList);+ newVal.set(accountType, accountList)}}- return newVal;- }, [accountMap, allowPlatSet]);+ return newVal+ }, [accountMap, allowPlatSet])// 默认平台设置useEffect(() => {const defaultPlatData = Array.from(accountMapLast).find(([plat, data]) => data.length !== 0,- );+ )setActivePlat(- defaultPlat ||- (defaultPlatData- ? defaultPlatData[0]- : Array.from(accountMapLast.keys())[0]),- );- }, [accountMapLast]);+ defaultPlat+ || (defaultPlatData+ ? defaultPlatData[0]+ : Array.from(accountMapLast.keys())[0]),+ )+ }, [accountMapLast])// 所有平台的账户数据const getAllAccountList = useMemo(() => {- const allAccountList = [];+ const allAccountList = []for (const [_, accountList] of accountMapLast) {- allAccountList.push(...accountList);+ allAccountList.push(...accountList)}- return allAccountList;- }, [accountMapLast]);+ return allAccountList+ }, [accountMapLast])// 当前选择的所有平台的账户数据const getChoosedAllAccountList = useMemo(() => {- const allAccountList = [];+ const allAccountList = []for (const [_, accountList] of choosedAcountMap) {- allAccountList.push(...accountList);+ allAccountList.push(...accountList)}- return allAccountList;- }, [choosedAcountMap]);+ return allAccountList+ }, [choosedAcountMap])// 当前平台的所有用户数据const currAccountList = useMemo(() => (activePlat && accountMapLast.get(activePlat)) || [],[activePlat, accountMapLast],- );+ )// 当前平台的选择账户的数据const currChoosedAcount = useMemo(() => (activePlat && choosedAcountMap.get(activePlat)) || [],[activePlat, choosedAcountMap],- );+ )useEffect(() => {setAccountMap((prevMap) => {- const newMap = new Map(prevMap);+ const newMap = new Map(prevMap)Array.from(AccountPlatInfoMap).map(([key, value]) => {if (value.pubTypes.has(pubType)) {- newMap.set(key, []);+ newMap.set(key, [])}- });+ })// 添加渲染账户数据值accountList.map((v) => {- newMap.get(v.type)?.push(v);- });- return newMap;- });- }, [accountList]);+ newMap.get(v.type)?.push(v)+ })+ return newMap+ })+ }, [accountList])useEffect(() => {return () => {- setAccountMap(new Map());- setChoosedAcountMap(new Map());- init();- };- }, []);+ setAccountMap(new Map())+ setChoosedAcountMap(new Map())+ init()+ }+ }, [])// change事件useEffect(() => {- if (!recentData.current) return;- let accounts: SocialAccount[] = [];+ if (!recentData.current)+ return+ let accounts: SocialAccount[] = []Array.from(choosedAcountMap).map(([key, value]) => {- accounts = [...accounts, ...value];- });- if (onChange) onChange(accounts, recentData.current!);- }, [choosedAcountMap]);+ accounts = [...accounts, ...value]+ })+ if (onChange)+ onChange(accounts, recentData.current!)+ }, [choosedAcountMap])const init = () => {- recentData.current = undefined;- };+ recentData.current = undefined+ }useImperativeHandle(ref, () => ({// 恢复到本次操作之前的状态recover() {if (!choosedAccounts || choosedAccounts.length === 0)- return setChoosedAcountMap(new Map());+ return setChoosedAcountMap(new Map())setChoosedAcountMap(() => {- const newV = new Map();+ const newV = new Map()choosedAccounts.map((v) => {- if (!newV.has(v.type)) newV.set(v.type, []);- newV.get(v.type)!.push(v);- });- return newV;- });+ if (!newV.has(v.type))+ newV.set(v.type, [])+ newV.get(v.type)!.push(v)+ })+ return newV+ })},setActivePlat,init,- }));+ }))return (<div className={styles.platChoose}>{getAllAccountList.length === 0 ? (<div className="platChoose-empty"><Empty- description={+ description={(<>- 无账户数据,请前往 <Link href="/accounts">账户</Link>+ 无账户数据,请前往+ {' '}+ <Link href="/accounts">账户</Link>添加数据</>- }+ )}/></div>) : (@@ -220,31 +228,32 @@ const PlatChoose = memo({!disableAllSelect && (<Checkboxindeterminate={- getChoosedAllAccountList.length > 0 &&- getChoosedAllAccountList.length < getAllAccountList.length+ getChoosedAllAccountList.length > 0+ && getChoosedAllAccountList.length < getAllAccountList.length}onChange={(e) => {- const { checked } = e.target;+ const { checked } = e.targetsetChoosedAcountMap((v) => {- const newMap = new Map(v);- recentData.current = currAccountList[0];+ const newMap = new Map(v)+ recentData.current = currAccountList[0]for (const [accountType,accountList,] of accountMapLast) {if (checked) {- newMap.set(accountType, accountList);- } else {- newMap.set(accountType, []);+ newMap.set(accountType, accountList)+ }+ else {+ newMap.set(accountType, [])}}- return newMap;- });+ return newMap+ })}}checked={- getAllAccountList.length ===- getChoosedAllAccountList.length+ getAllAccountList.length+ === getChoosedAllAccountList.length}>选择所有平台账户@@ -254,11 +263,11 @@ const PlatChoose = memo(theme={{components: {Segmented: {- trackBg: "#fff",- itemSelectedBg: cssVars["--colorPrimary1"],- itemHoverBg: cssVars["--colorPrimary2"],- itemActiveBg: cssVars["--colorPrimary3"],- itemSelectedColor: cssVars["--colorPrimary9"],+ trackBg: '#fff',+ itemSelectedBg: cssVars['--colorPrimary1'],+ itemHoverBg: cssVars['--colorPrimary2'],+ itemActiveBg: cssVars['--colorPrimary3'],+ itemSelectedColor: cssVars['--colorPrimary9'],},},}}@@ -269,8 +278,9 @@ const PlatChoose = memo(value={activePlat}options={Array.from(accountMapLast).map(([key, value]) => {- if (value.length === 0) return undefined;- const platInfo = AccountPlatInfoMap.get(key)!;+ if (value.length === 0)+ return undefined+ const platInfo = AccountPlatInfoMap.get(key)!return {value: key,label: platInfo.name,@@ -280,15 +290,15 @@ const PlatChoose = memo(size="small"><img- style={{ width: "25px" }}+ style={{ width: '25px' }}src={platInfo.icon}/></Badge>),- };+ }})- .filter((v) => v !== undefined)- .filter((v) =>+ .filter(v => v !== undefined)+ .filter(v =>allowPlatSet ? allowPlatSet.has(v.value) : true,)}onChange={setActivePlat}@@ -299,74 +309,90 @@ const PlatChoose = memo(<div className="platChoose-con">{currAccountList && (<div className="platChoose-con-wrapper">- {!disableAllSelect ? (- <Checkbox- indeterminate={- currChoosedAcount.length > 0 &&- currChoosedAcount.length < currAccountList.length- }- onChange={(e) => {- setChoosedAcountMap((v) => {- recentData.current = currAccountList[0];- return new Map(v).set(- activePlat!,- e.target.checked ? currAccountList : [],- );- });- }}- checked={- currChoosedAcount.length === currAccountList.length- }- >- 全选 已选择 {currChoosedAcount.length} 个- </Checkbox>- ) : (- <span>已选择 {currChoosedAcount.length} 个</span>- )}+ {!disableAllSelect+ ? (+ <Checkbox+ indeterminate={+ currChoosedAcount.length > 0+ && currChoosedAcount.length < currAccountList.length+ }+ onChange={(e) => {+ setChoosedAcountMap((v) => {+ recentData.current = currAccountList[0]+ return new Map(v).set(+ activePlat!,+ e.target.checked ? currAccountList : [],+ )+ })+ }}+ checked={+ currChoosedAcount.length === currAccountList.length+ }+ >+ 全选 已选择+ {' '}+ {currChoosedAcount.length}+ {' '}+ 个+ </Checkbox>+ )+ : (+ <span>+ 已选择+ {currChoosedAcount.length}+ {' '}+ 个+ </span>+ )}<div className="platChoose-accounts">{currAccountList.map((v) => {// true=禁用- const isDisable =- choosedAccounts?.find((k) => k.id === v.id) &&- isCancelChooseAccount;+ const isDisable+ = choosedAccounts?.find(k => k.id === v.id)+ && isCancelChooseAccountreturn (<divkey={v.id}className={[- "platChoose-accounts-item",- currChoosedAcount.find((k) => k.id === v.id) &&- "platChoose-accounts-item--active",- isDisable && "platChoose-accounts-item--disable",- ].join(" ")}+ 'platChoose-accounts-item',+ currChoosedAcount.find(k => k.id === v.id)+ && 'platChoose-accounts-item--active',+ isDisable && 'platChoose-accounts-item--disable',+ ].join(' ')}onClick={() => {- if (isDisable) return;- recentData.current = v;+ if (isDisable)+ return+ recentData.current = vsetChoosedAcountMap((prevV) => {- const newV = new Map(prevV);- let list = newV.get(activePlat!);+ const newV = new Map(prevV)+ let list = newV.get(activePlat!)if (!list) {- list = [];- newV.set(activePlat!, list);+ list = []+ newV.set(activePlat!, list)}// 是否存在- if (list.some((k) => k.id === v.id)) {+ if (list.some(k => k.id === v.id)) {// 有、去掉- list = list.filter((k) => k.id !== v.id);- } else {+ list = list.filter(k => k.id !== v.id)+ }+ else {// 无、添加- list.push(v);+ list.push(v)}- newV.set(activePlat!, list);- return newV;- });+ newV.set(activePlat!, list)+ return newV+ })}}><Tooltip- title={+ title={(<>- <p>昵称:{v.nickname}</p>+ <p>+ 昵称:+ {v.nickname}+ </p></>- }+ )}><Avatar src={v.avatar} /><span className="platChoose-accounts-item-nickname">@@ -378,7 +404,7 @@ const PlatChoose = memo(<CheckOutlined /></div></div>- );+ )})}</div></div>@@ -393,10 +419,10 @@ const PlatChoose = memo(</>)}</div>- );+ )},),-);-PlatChoose.displayName = "PlatChoose";+)+PlatChoose.displayName = 'PlatChoose'-export default PlatChoose;+export default PlatChoosediff --git a/project/web/src/components/ChooseAccountModule/components/SimpleAccountChoose.tsx b/project/web/src/components/ChooseAccountModule/components/SimpleAccountChoose.tsxindex 2d02ba57..efaf889f 100644--- a/project/web/src/components/ChooseAccountModule/components/SimpleAccountChoose.tsx+++ b/project/web/src/components/ChooseAccountModule/components/SimpleAccountChoose.tsx@@ -1,5 +1,17 @@-import {+import type {ForwardedRef,+} from 'react'+import type { AccountGroupItem, SocialAccount } from '@/api/types/account.type'+import { CheckOutlined } from '@ant-design/icons'+import {+ Avatar,+ Checkbox,+ Collapse,+ Empty,+ Tooltip,+} from 'antd'+import Link from 'next/link'+import {forwardRef,memo,useEffect,@@ -7,56 +19,45 @@ import {useMemo,useRef,useState,-} from "react";-import styles from "../chooseAccountModule.module.scss";-import {- Avatar,- Checkbox,- Empty,- Tooltip,- Collapse,-} from "antd";-import DownloadAppModal from "@/components/common/DownloadAppModal";-import { CheckOutlined } from "@ant-design/icons";-import { useShallow } from "zustand/react/shallow";-import { AccountPlatInfoMap } from "@/app/config/platConfig";-import { useAccountStore } from "@/store/account";-import Link from "next/link";-import { SocialAccount } from "@/api/types/account.type";-import { getAccountGroupApi } from "@/api/account";-import { AccountGroupItem } from "@/api/types/account.type";+} from 'react'+import { useShallow } from 'zustand/react/shallow'+import { getAccountGroupApi } from '@/api/account'+import { AccountPlatInfoMap } from '@/app/config/platConfig'+import DownloadAppModal from '@/components/common/DownloadAppModal'+import { useAccountStore } from '@/store/account'+import styles from '../chooseAccountModule.module.scss'// 分组类型定义interface AccountGroup {- id: string;- name: string;- rank: number;- isDefault: boolean;- children?: SocialAccount[];+ id: string+ name: string+ rank: number+ isDefault: boolean+ children?: SocialAccount[]}export interface ISimpleAccountChooseRef {/*** 恢复选中状态*/- recover: () => void;+ recover: () => void// 每次关闭弹框的时候需要初始化一些状态- init: () => void;+ init: () => void}export interface ISimpleAccountChooseProps {onChange?: (choosedAcounts: SocialAccount[],choosedAcount: SocialAccount,- ) => void;+ ) => void// 外部传入的已经选中的数据,这个值只有在确认更改才会更新- choosedAccounts?: SocialAccount[];+ choosedAccounts?: SocialAccount[]// 是否禁用多选,true=禁用,false=不禁用- disableAllSelect?: boolean;+ disableAllSelect?: boolean// 是否可以取消已经选择的账户,默认为 false- isCancelChooseAccount?: boolean;+ isCancelChooseAccount?: boolean// 是否显示分组,默认为 true- showGroup?: boolean;+ showGroup?: boolean}const SimpleAccountChoose = memo(@@ -72,166 +73,188 @@ const SimpleAccountChoose = memo(ref: ForwardedRef<ISimpleAccountChooseRef>,) => {// 当前选择的账户数据- const [choosedAccountsList, setChoosedAccountsList] = useState<SocialAccount[]>([]);+ const [choosedAccountsList, setChoosedAccountsList] = useState<SocialAccount[]>([])// 分组数据- const [accountGroupList, setAccountGroupList] = useState<AccountGroup[]>([]);+ const [accountGroupList, setAccountGroupList] = useState<AccountGroup[]>([])// 每次change操作的数据- const recentData = useRef<SocialAccount>();+ const recentData = useRef<SocialAccount>()// 下载App弹窗状态- const [downloadModalVisible, setDownloadModalVisible] = useState(false);- const [currentPlatform, setCurrentPlatform] = useState<string>('');+ const [downloadModalVisible, setDownloadModalVisible] = useState(false)+ const [currentPlatform, setCurrentPlatform] = useState<string>('')const { accountList } = useAccountStore(- useShallow((state) => ({+ useShallow(state => ({accountList: state.accountList,})),- );+ )// 获取分组数据const fetchAccountGroups = async () => {try {- const res = await getAccountGroupApi();- const groupList = res?.data;+ const res = await getAccountGroupApi()+ const groupList = res?.data- if (!groupList || groupList.length === 0) return;+ if (!groupList || groupList.length === 0)+ return- const accountGroupList: AccountGroup[] = [];+ const accountGroupList: AccountGroup[] = []// key=组ID,val=账户组- const accountGroupMap = new Map<string, AccountGroup>();+ const accountGroupMap = new Map<string, AccountGroup>()- const defaultGroup = groupList.find((v:any) => v.isDefault)!;+ const defaultGroup = groupList.find((v: any) => v.isDefault)!- groupList.map((v:any) => {+ groupList.map((v: any) => {const accountGroupItem = {...v,children: [],- };- accountGroupList.push(accountGroupItem);- accountGroupMap.set(v.id, accountGroupItem);- });+ }+ accountGroupList.push(accountGroupItem)+ accountGroupMap.set(v.id, accountGroupItem)+ })accountList.map((v) => {(- accountGroupMap.get(v.groupId!) ||- accountGroupMap.get(defaultGroup.id)!- ).children?.push(v);- });+ accountGroupMap.get(v.groupId!)+ || accountGroupMap.get(defaultGroup.id)!+ ).children?.push(v)+ })accountGroupList.sort((a, b) => {- return a.rank - b.rank;- });+ return a.rank - b.rank+ })- setAccountGroupList(accountGroupList);- } catch (error) {- console.error('获取账户分组失败:', error);+ setAccountGroupList(accountGroupList)+ }+ catch (error) {+ console.error('获取账户分组失败:', error)}- };+ }// 初始化分组数据useEffect(() => {if (showGroup && accountList.length > 0) {- fetchAccountGroups();+ fetchAccountGroups()}- }, [showGroup, accountList]);+ }, [showGroup, accountList])// change事件useEffect(() => {- if (!recentData.current) return;- if (onChange) onChange(choosedAccountsList, recentData.current!);- }, [choosedAccountsList, onChange]);+ if (!recentData.current)+ return+ if (onChange)+ onChange(choosedAccountsList, recentData.current!)+ }, [choosedAccountsList, onChange])const init = () => {- recentData.current = undefined;- };+ recentData.current = undefined+ }useImperativeHandle(ref, () => ({// 恢复到本次操作之前的状态recover() {- setChoosedAccountsList(choosedAccounts || []);+ setChoosedAccountsList(choosedAccounts || [])},init,- }));+ }))// 全选/取消全选const handleSelectAll = (checked: boolean) => {- recentData.current = accountList[0];- setChoosedAccountsList(checked ? [...accountList] : []);- };+ recentData.current = accountList[0]+ setChoosedAccountsList(checked ? [...accountList] : [])+ }// 选择/取消选择单个账户const handleSelectAccount = (account: SocialAccount) => {- recentData.current = account;- setChoosedAccountsList(prev => {- const isSelected = prev.some(item => item.id === account.id);+ recentData.current = account+ setChoosedAccountsList((prev) => {+ const isSelected = prev.some(item => item.id === account.id)if (isSelected) {- return prev.filter(item => item.id !== account.id);- } else {- return [...prev, account];+ return prev.filter(item => item.id !== account.id)}- });- };+ else {+ return [...prev, account]+ }+ })+ }// 选择/取消选择分组内所有账户const handleSelectGroup = (group: AccountGroup, checked: boolean) => {- if (!group.children || group.children.length === 0) return;-- recentData.current = group.children[0];- setChoosedAccountsList(prev => {- const groupAccountIds = group.children!.map(account => account.id);- const selectedInGroup = prev.filter(account => groupAccountIds.includes(account.id));-+ if (!group.children || group.children.length === 0)+ return++ recentData.current = group.children[0]+ setChoosedAccountsList((prev) => {+ const groupAccountIds = group.children!.map(account => account.id)+ const selectedInGroup = prev.filter(account => groupAccountIds.includes(account.id))+if (checked) {// 选择分组内所有账户- const otherAccounts = prev.filter(account => !groupAccountIds.includes(account.id));- return [...otherAccounts, ...group.children!];- } else {+ const otherAccounts = prev.filter(account => !groupAccountIds.includes(account.id))+ return [...otherAccounts, ...group.children!]+ }+ else {// 取消选择分组内所有账户- return prev.filter(account => !groupAccountIds.includes(account.id));+ return prev.filter(account => !groupAccountIds.includes(account.id))}- });- };+ })+ }// 渲染单个账户const renderAccount = (account: SocialAccount) => {- const platInfo = AccountPlatInfoMap.get(account.type);- const isSelected = choosedAccountsList.some(item => item.id === account.id);- const isDisable = choosedAccounts?.find((k) => k.id === account.id) && isCancelChooseAccount;- const isPcNotSupported = platInfo && platInfo.pcNoThis === true;+ const platInfo = AccountPlatInfoMap.get(account.type)+ const isSelected = choosedAccountsList.some(item => item.id === account.id)+ const isDisable = choosedAccounts?.find(k => k.id === account.id) && isCancelChooseAccount+ const isPcNotSupported = platInfo && platInfo.pcNoThis === trueconst handleAccountClick = () => {- if (isDisable) return;+ if (isDisable)+ returnif (isPcNotSupported) {- setCurrentPlatform(platInfo?.name || '');- setDownloadModalVisible(true);- return;+ setCurrentPlatform(platInfo?.name || '')+ setDownloadModalVisible(true)+ return}- handleSelectAccount(account);- };+ handleSelectAccount(account)+ }return (<divkey={account.id}className={[- "simpleAccountChoose-accounts-item",- isSelected && "simpleAccountChoose-accounts-item--active",- isDisable && "simpleAccountChoose-accounts-item--disable",- isPcNotSupported && "simpleAccountChoose-accounts-item--pc-not-supported",- ].join(" ")}+ 'simpleAccountChoose-accounts-item',+ isSelected && 'simpleAccountChoose-accounts-item--active',+ isDisable && 'simpleAccountChoose-accounts-item--disable',+ isPcNotSupported && 'simpleAccountChoose-accounts-item--pc-not-supported',+ ].join(' ')}onClick={handleAccountClick}><Tooltiptitle={- isPcNotSupported ? (- <>- <p>昵称:{account.nickname}</p>- <p>平台:{platInfo?.name}</p>- <p style={{ color: '#ff4d4f' }}>Web不支持该平台,请下载App</p>- </>- ) : (- <>- <p>昵称:{account.nickname}</p>- <p>平台:{platInfo?.name}</p>- </>- )+ isPcNotSupported+ ? (+ <>+ <p>+ 昵称:+ {account.nickname}+ </p>+ <p>+ 平台:+ {platInfo?.name}+ </p>+ <p style={{ color: '#ff4d4f' }}>Web不支持该平台,请下载App</p>+ </>+ )+ : (+ <>+ <p>+ 昵称:+ {account.nickname}+ </p>+ <p>+ 平台:+ {platInfo?.name}+ </p>+ </>+ )}><div className="simpleAccountChoose-accounts-item-avatar">@@ -247,18 +270,20 @@ const SimpleAccountChoose = memo(</span></Tooltip>- {isPcNotSupported ? (- <div className="simpleAccountChoose-accounts-item-overlay">- <span className="simpleAccountChoose-accounts-item-overlay-text">APP</span>- </div>- ) : (- <div className="simpleAccountChoose-accounts-item-choose">- <CheckOutlined />- </div>- )}+ {isPcNotSupported+ ? (+ <div className="simpleAccountChoose-accounts-item-overlay">+ <span className="simpleAccountChoose-accounts-item-overlay-text">APP</span>+ </div>+ )+ : (+ <div className="simpleAccountChoose-accounts-item-choose">+ <CheckOutlined />+ </div>+ )}</div>- );- };+ )+ }// 渲染分组内容const renderGroupContent = () => {@@ -267,7 +292,7 @@ const SimpleAccountChoose = memo(<div className="simpleAccountChoose-accounts">{accountList.map(renderAccount)}</div>- );+ )}return (@@ -276,75 +301,87 @@ const SimpleAccountChoose = memo(className="simpleAccountChoose-groups">{accountGroupList.map((group) => {- const groupAccountIds = group.children?.map(account => account.id) || [];- const selectedInGroup = choosedAccountsList.filter(account =>- groupAccountIds.includes(account.id)- );- const isGroupSelected = selectedInGroup.length === group.children?.length;- const isGroupIndeterminate = selectedInGroup.length > 0 && selectedInGroup.length < (group.children?.length || 0);+ const groupAccountIds = group.children?.map(account => account.id) || []+ const selectedInGroup = choosedAccountsList.filter(account =>+ groupAccountIds.includes(account.id),+ )+ const isGroupSelected = selectedInGroup.length === group.children?.length+ const isGroupIndeterminate = selectedInGroup.length > 0 && selectedInGroup.length < (group.children?.length || 0)return (<Collapse.Panelkey={group.id}- header={+ header={(<div className="simpleAccountChoose-group-header"><Checkboxindeterminate={isGroupIndeterminate}checked={isGroupSelected}- onChange={(e) => handleSelectGroup(group, e.target.checked)}- onClick={(e) => e.stopPropagation()}+ onChange={e => handleSelectGroup(group, e.target.checked)}+ onClick={e => e.stopPropagation()}>- {group.name} ({group.children?.length || 0})+ {group.name}+ {' '}+ (+ {group.children?.length || 0}+ )</Checkbox></div>- }+ )}><div className="simpleAccountChoose-accounts">{group.children?.map(renderAccount)}</div></Collapse.Panel>- );+ )})}</Collapse>- );- };+ )+ }return (<div className={styles.simpleAccountChoose}>- {accountList.length === 0 ? (- <div className="simpleAccountChoose-empty">- <Empty- description={- <>- 无账户数据,请前往 <Link href="/accounts">账户</Link>- 添加数据- </>- }- />- </div>- ) : (- <>- <div className="simpleAccountChoose-header">- {!disableAllSelect && (- <Checkbox- indeterminate={- choosedAccountsList.length > 0 &&- choosedAccountsList.length < accountList.length- }- onChange={(e) => handleSelectAll(e.target.checked)}- checked={choosedAccountsList.length === accountList.length}- >- 选择所有账户- </Checkbox>- )}- <span className="simpleAccountChoose-count">- 已选择 {choosedAccountsList.length} 个- </span>- </div>+ {accountList.length === 0+ ? (+ <div className="simpleAccountChoose-empty">+ <Empty+ description={(+ <>+ 无账户数据,请前往+ {' '}+ <Link href="/accounts">账户</Link>+ 添加数据+ </>+ )}+ />+ </div>+ )+ : (+ <>+ <div className="simpleAccountChoose-header">+ {!disableAllSelect && (+ <Checkbox+ indeterminate={+ choosedAccountsList.length > 0+ && choosedAccountsList.length < accountList.length+ }+ onChange={e => handleSelectAll(e.target.checked)}+ checked={choosedAccountsList.length === accountList.length}+ >+ 选择所有账户+ </Checkbox>+ )}+ <span className="simpleAccountChoose-count">+ 已选择+ {' '}+ {choosedAccountsList.length}+ {' '}+ 个+ </span>+ </div>- {renderGroupContent()}- </>- )}+ {renderGroupContent()}+ </>+ )}{/* 下载App弹窗 */}<DownloadAppModal@@ -354,10 +391,10 @@ const SimpleAccountChoose = memo(appName="Aitoearn App"/></div>- );+ )},),-);-SimpleAccountChoose.displayName = "SimpleAccountChoose";+)+SimpleAccountChoose.displayName = 'SimpleAccountChoose'-export default SimpleAccountChoose;\ No newline at end of file+export default SimpleAccountChoosediff --git a/project/web/src/components/FacebookPagesModal/index.module.scss b/project/web/src/components/FacebookPagesModal/index.module.scssindex 62e8aca0..20f20649 100644--- a/project/web/src/components/FacebookPagesModal/index.module.scss+++ b/project/web/src/components/FacebookPagesModal/index.module.scss@@ -61,7 +61,7 @@font-weight: 500;color: #1890ff;text-decoration: none;-+&:hover {color: #40a9ff;text-decoration: underline;@@ -77,4 +77,4 @@.refreshButton {margin-top: 8px;}-}\ No newline at end of file+}diff --git a/project/web/src/components/FacebookPagesModal/index.tsx b/project/web/src/components/FacebookPagesModal/index.tsxindex 136ead3c..a37444ee 100644--- a/project/web/src/components/FacebookPagesModal/index.tsx+++ b/project/web/src/components/FacebookPagesModal/index.tsx@@ -1,23 +1,23 @@-import React, { useState, useEffect } from 'react';-import { Modal, Checkbox, List, Button, message, Spin, Avatar, Typography } from 'antd';-import { ReloadOutlined } from '@ant-design/icons';-import { apiGetFacebookPages, apiSubmitFacebookPages } from '@/api/plat/facebook';-import { useAccountStore } from '@/store/account';-import { useTranslation } from 'react-i18next';-import styles from './index.module.scss';+import { ReloadOutlined } from '@ant-design/icons'+import { Avatar, Button, Checkbox, List, message, Modal, Spin, Typography } from 'antd'+import React, { useEffect, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { apiGetFacebookPages, apiSubmitFacebookPages } from '@/api/plat/facebook'+import { useAccountStore } from '@/store/account'+import styles from './index.module.scss'-const { Link } = Typography;+const { Link } = Typographyexport interface FacebookPageItem {- id: string;- name: string;- profile_picture_url?: string;+ id: string+ name: string+ profile_picture_url?: string}interface FacebookPagesModalProps {- open: boolean;- onClose: () => void;- onSuccess: () => void;+ open: boolean+ onClose: () => void+ onSuccess: () => void}const FacebookPagesModal: React.FC<FacebookPagesModalProps> = ({@@ -25,82 +25,90 @@ const FacebookPagesModal: React.FC<FacebookPagesModalProps> = ({onClose,onSuccess,}) => {- const { t } = useTranslation('account');- const [pages, setPages] = useState<FacebookPageItem[]>([]);- const [selectedPageIds, setSelectedPageIds] = useState<string[]>([]);- const [loading, setLoading] = useState(false);- const [submitting, setSubmitting] = useState(false);- const accountStore = useAccountStore();+ const { t } = useTranslation('account')+ const [pages, setPages] = useState<FacebookPageItem[]>([])+ const [selectedPageIds, setSelectedPageIds] = useState<string[]>([])+ const [loading, setLoading] = useState(false)+ const [submitting, setSubmitting] = useState(false)+ const accountStore = useAccountStore()// 获取Facebook页面列表const fetchPages = async () => {- setLoading(true);+ setLoading(true)try {- const res: any = await apiGetFacebookPages('');+ const res: any = await apiGetFacebookPages('')if (res?.code === 0) {- setPages(res.data || []);- } else {- message.error(t('facebookPages.fetchError' as any));+ setPages(res.data || [])}- } catch (error) {- console.error('获取Facebook页面列表失败:', error);- message.error(t('facebookPages.fetchError' as any));- } finally {- setLoading(false);+ else {+ message.error(t('facebookPages.fetchError' as any))+ }+ }+ catch (error) {+ console.error('获取Facebook页面列表失败:', error)+ message.error(t('facebookPages.fetchError' as any))}- };+ finally {+ setLoading(false)+ }+ }// 提交选择的页面const handleSubmit = async () => {if (selectedPageIds.length === 0) {- message.warning(t('facebookPages.selectAtLeastOne' as any));- return;+ message.warning(t('facebookPages.selectAtLeastOne' as any))+ return}- setSubmitting(true);+ setSubmitting(true)try {- const res = await apiSubmitFacebookPages(selectedPageIds);+ const res = await apiSubmitFacebookPages(selectedPageIds)if (res?.code === 0) {- message.success(t('facebookPages.submitSuccess' as any));+ message.success(t('facebookPages.submitSuccess' as any))// 刷新账户列表- await accountStore.getAccountList();- onSuccess();- onClose();- } else {- message.error(t('facebookPages.submitError' as any));+ await accountStore.getAccountList()+ onSuccess()+ onClose()+ }+ else {+ message.error(t('facebookPages.submitError' as any))}- } catch (error) {- console.error('提交页面选择失败:', error);- message.error(t('facebookPages.submitError' as any));- } finally {- setSubmitting(false);}- };+ catch (error) {+ console.error('提交页面选择失败:', error)+ message.error(t('facebookPages.submitError' as any))+ }+ finally {+ setSubmitting(false)+ }+ }// 处理页面选择变化const handlePageChange = (pageId: string, checked: boolean) => {if (checked) {- setSelectedPageIds(prev => [...prev, pageId]);- } else {- setSelectedPageIds(prev => prev.filter(id => id !== pageId));+ setSelectedPageIds(prev => [...prev, pageId])+ }+ else {+ setSelectedPageIds(prev => prev.filter(id => id !== pageId))}- };+ }// 全选/取消全选const handleSelectAll = (checked: boolean) => {if (checked) {- setSelectedPageIds(pages.map(page => page.id));- } else {- setSelectedPageIds([]);+ setSelectedPageIds(pages.map(page => page.id))}- };+ else {+ setSelectedPageIds([])+ }+ }useEffect(() => {if (open) {- fetchPages();- setSelectedPageIds([]);+ fetchPages()+ setSelectedPageIds([])}- }, [open]);+ }, [open])return (<Modal@@ -127,69 +135,71 @@ const FacebookPagesModal: React.FC<FacebookPagesModalProps> = ({<Checkboxchecked={selectedPageIds.length === pages.length && pages.length > 0}indeterminate={selectedPageIds.length > 0 && selectedPageIds.length < pages.length}- onChange={(e) => handleSelectAll(e.target.checked)}+ onChange={e => handleSelectAll(e.target.checked)}>{t('facebookPages.selectAll' as any)}</Checkbox></div><Spin spinning={loading}>- {pages.length > 0 ? (- <List- className={styles.pageList}- dataSource={pages}- renderItem={(page) => (- <List.Item className={styles.pageItem}>- <Checkbox- checked={selectedPageIds.includes(page.id)}- onChange={(e) => handlePageChange(page.id, e.target.checked)}- >- <div className={styles.pageInfo}>- <Avatar- src={page.profile_picture_url}- size={32}- className={styles.pageAvatar}+ {pages.length > 0+ ? (+ <List+ className={styles.pageList}+ dataSource={pages}+ renderItem={page => (+ <List.Item className={styles.pageItem}>+ <Checkbox+ checked={selectedPageIds.includes(page.id)}+ onChange={e => handlePageChange(page.id, e.target.checked)}>- {page.name?.charAt(0)}- </Avatar>- <span className={styles.pageName}>{page.name}</span>+ <div className={styles.pageInfo}>+ <Avatar+ src={page.profile_picture_url}+ size={32}+ className={styles.pageAvatar}+ >+ {page.name?.charAt(0)}+ </Avatar>+ <span className={styles.pageName}>{page.name}</span>+ </div>+ </Checkbox>+ </List.Item>+ )}+ />+ )+ : (+ !loading && (+ <div className={styles.noPagesContainer}>+ <div className={styles.noPagesMessage}>+ {t('facebookPages.noPagesMessage' as any)}+ </div>+ <div className={styles.createPageSection}>+ <Link+ href="https://www.facebook.com/pages/create"+ target="_blank"+ className={styles.createPageLink}+ >+ {t('facebookPages.createPageLink' as any)}+ </Link>+ <div className={styles.createPageTip}>+ {t('facebookPages.createPageTip' as any)}+ </div>+ <Button+ type="primary"+ icon={<ReloadOutlined />}+ onClick={fetchPages}+ className={styles.refreshButton}+ >+ {t('facebookPages.refresh' as any)}+ </Button></div>- </Checkbox>- </List.Item>- )}- />- ) : (- !loading && (- <div className={styles.noPagesContainer}>- <div className={styles.noPagesMessage}>- {t('facebookPages.noPagesMessage' as any)}- </div>- <div className={styles.createPageSection}>- <Link- href="https://www.facebook.com/pages/create"- target="_blank"- className={styles.createPageLink}- >- {t('facebookPages.createPageLink' as any)}- </Link>- <div className={styles.createPageTip}>- {t('facebookPages.createPageTip' as any)}</div>- <Button- type="primary"- icon={<ReloadOutlined />}- onClick={fetchPages}- className={styles.refreshButton}- >- {t('facebookPages.refresh' as any)}- </Button>- </div>- </div>- )- )}+ )+ )}</Spin></Modal>- );-};+ )+}-export default FacebookPagesModal;\ No newline at end of file+export default FacebookPagesModaldiff --git a/project/web/src/components/GetCode/GetCode.tsx b/project/web/src/components/GetCode/GetCode.tsxindex 23ad9484..6280f09a 100644--- a/project/web/src/components/GetCode/GetCode.tsx+++ b/project/web/src/components/GetCode/GetCode.tsx@@ -1,63 +1,66 @@-import { useRef, useState } from "react";-import { Statistic } from "antd";-import styles from "./getCode.module.scss";+import { Statistic } from 'antd'+import { useRef, useState } from 'react'+import styles from './getCode.module.scss'-const { Timer } = Statistic;+const { Timer } = Statisticfunction GetCode({onGetCode,codeSendTime = 60,}: {- onGetCode: (unlock: () => void) => void;- codeSendTime?: number;+ onGetCode: (unlock: () => void) => void+ codeSendTime?: number}) {- const [isCode, setIsCode] = useState(false);- const currTime = useRef(0);+ const [isCode, setIsCode] = useState(false)+ const currTime = useRef(0)const lockCode = () => {- setIsCode(true);- currTime.current = codeSendTime * 1000;- };+ setIsCode(true)+ currTime.current = codeSendTime * 1000+ }return (<labelclassName={- styles["loginForm-getCode"] +- ` ${isCode ? styles["loginForm-getCode--disable"] : ""}`+ `${styles['loginForm-getCode']+ } ${isCode ? styles['loginForm-getCode--disable'] : ''}`}onClick={() => {- if (isCode) return;- lockCode();+ if (isCode)+ return+ lockCode()onGetCode(() => {- setIsCode(false);- });+ setIsCode(false)+ })}}>获取验证码- {isCode ? (- <>- (- <Timer- type="countdown"- format="ss"- value={Date.now() + currTime.current}- precision={1}- onFinish={() => {- setIsCode(false);- }}- onChange={(e) => {- if (typeof e === "number") {- currTime.current = e;- }- }}- />- s)- </>- ) : (- ""- )}+ {isCode+ ? (+ <>+ (+ <Timer+ type="countdown"+ format="ss"+ value={Date.now() + currTime.current}+ precision={1}+ onFinish={() => {+ setIsCode(false)+ }}+ onChange={(e) => {+ if (typeof e === 'number') {+ currTime.current = e+ }+ }}+ />+ s)+ </>+ )+ : (+ ''+ )}</label>- );+ )}-export default GetCode;+export default GetCodediff --git a/project/web/src/components/GetCode/getCode.module.scss b/project/web/src/components/GetCode/getCode.module.scssindex a5504708..69bd61f7 100644--- a/project/web/src/components/GetCode/getCode.module.scss+++ b/project/web/src/components/GetCode/getCode.module.scss@@ -31,4 +31,4 @@.loginForm-getCode--disable {cursor: no-drop;-}\ No newline at end of file+}diff --git a/project/web/src/components/ImageEditorModal/imageEditorModal.module.scss b/project/web/src/components/ImageEditorModal/imageEditorModal.module.scssindex c1f5765a..5596b2bb 100644--- a/project/web/src/components/ImageEditorModal/imageEditorModal.module.scss+++ b/project/web/src/components/ImageEditorModal/imageEditorModal.module.scss@@ -3,7 +3,8 @@.tui-image-editor-container {width: 100% !important;}- .tui-image-editor-download-btn, .tui-image-editor-header-logo {+ .tui-image-editor-download-btn,+ .tui-image-editor-header-logo {display: none !important;}.tui-colorpicker-palette-container {@@ -23,4 +24,4 @@}}}-}\ No newline at end of file+}diff --git a/project/web/src/components/ImageEditorModal/index.tsx b/project/web/src/components/ImageEditorModal/index.tsxindex 2880cca0..d21d8788 100644--- a/project/web/src/components/ImageEditorModal/index.tsx+++ b/project/web/src/components/ImageEditorModal/index.tsx@@ -1,32 +1,34 @@-import {+import type {ForwardedRef,+} from 'react'+import type { IImgFile } from '@/components/PublishDialog/publishDialog.type'+// @ts-ignore+import ImageEditor from '@toast-ui/react-image-editor'+import { Button, Modal } from 'antd'+import {forwardRef,memo,useEffect,useMemo,useRef,useState,-} from "react";-// @ts-ignore-import ImageEditor from "@toast-ui/react-image-editor";-import "tui-image-editor/dist/tui-image-editor.css";-import { Button, Modal } from "antd";-import styles from "./imageEditorModal.module.scss";-import { IImgFile } from "@/components/PublishDialog/publishDialog.type";-import { useGetClientLng } from "@/hooks/useSystem";-import { useTransClient } from "@/app/i18n/client";-import zhCNImageEditor from "@/app/i18n/locales/zh-CN/imageEditor.json";-import { formatImg } from "@/components/PublishDialog/PublishDialog.util";-import { dataURLToBlob } from "@/utils";-import { uploadToOss } from "@/api/oss";-import { getOssUrl } from "@/utils/oss";+} from 'react'+import { uploadToOss } from '@/api/oss'+import { useTransClient } from '@/app/i18n/client'+import zhCNImageEditor from '@/app/i18n/locales/zh-CN/imageEditor.json'+import { formatImg } from '@/components/PublishDialog/PublishDialog.util'+import { useGetClientLng } from '@/hooks/useSystem'+import { dataURLToBlob } from '@/utils'+import { getOssUrl } from '@/utils/oss'+import styles from './imageEditorModal.module.scss'+import 'tui-image-editor/dist/tui-image-editor.css'export interface IImageEditorModalRef {}export interface IImageEditorModalProps {- open: boolean;- onCancel: () => void;- imgFile?: IImgFile;- onOk: (editedImg: IImgFile) => void;+ open: boolean+ onCancel: () => void+ imgFile?: IImgFile+ onOk: (editedImg: IImgFile) => void}const ImageEditorModal = memo(@@ -35,113 +37,116 @@ const ImageEditorModal = memo({ open, onCancel, imgFile, onOk }: IImageEditorModalProps,ref: ForwardedRef<IImageEditorModalRef>,) => {- const lng = useGetClientLng();- const { t } = useTransClient("imageEditor");- const account = useTransClient("account");- const imageEditorRef = useRef<any>();- const [uploadLoading, setUploadLoading] = useState(false);- const isInit = useRef(false);+ const lng = useGetClientLng()+ const { t } = useTransClient('imageEditor')+ const account = useTransClient('account')+ const imageEditorRef = useRef<any>()+ const [uploadLoading, setUploadLoading] = useState(false)+ const isInit = useRef(false)const imageEditorLocale = useMemo(() => {- if (lng === "en") return null;+ if (lng === 'en')+ return null// 这里用 zhCNImageEditor 的 key 列表动态生成return Object.keys(zhCNImageEditor).reduce<Record<string, string>>((acc, key) => {- acc[key] = t(key as any); // 若缺失则 i18n 会回退为 key- return acc;+ acc[key] = t(key as any) // 若缺失则 i18n 会回退为 key+ return acc},{},- );- }, [lng, t]);+ )+ }, [lng, t])useEffect(() => {if (open && imgFile) {- const inst = imageEditorRef.current?.getInstance();+ const inst = imageEditorRef.current?.getInstance()if (inst) {- inst.loadImageFromURL(imgFile?.imgUrl, "lena").then(() => {- inst.ui.resizeEditor();- });+ inst.loadImageFromURL(imgFile?.imgUrl, 'lena').then(() => {+ inst.ui.resizeEditor()+ })}}- }, [imgFile, open]);+ }, [imgFile, open])// 添加裁剪预设function addCropPreset(newClass: string, label: string, mode: number) {- if (document.querySelector(`.${newClass}`)) return;- const originClass = "preset-16-9";- const cropCon = document.querySelector(".tie-crop-preset-button")!;- const originPreset = cropCon.querySelector(`.${originClass}`)!;+ if (document.querySelector(`.${newClass}`))+ return+ const originClass = 'preset-16-9'+ const cropCon = document.querySelector('.tie-crop-preset-button')!+ const originPreset = cropCon.querySelector(`.${originClass}`)!// 克隆节点并清除所有事件- const cleanPreset = originPreset.cloneNode(true) as HTMLElement;- const newPreset = cleanPreset.cloneNode(true) as HTMLElement;- newPreset.querySelector("label")!.innerText = label;- newPreset.classList.remove(originClass);- newPreset.classList.add(newClass);- cropCon.appendChild(newPreset);+ const cleanPreset = originPreset.cloneNode(true) as HTMLElement+ const newPreset = cleanPreset.cloneNode(true) as HTMLElement+ newPreset.querySelector('label')!.textContent = label+ newPreset.classList.remove(originClass)+ newPreset.classList.add(newClass)+ cropCon.appendChild(newPreset)newPreset.onclick = () => {setTimeout(() => {- const inst = imageEditorRef.current?.getInstance();- inst.stopDrawingMode();- inst.startDrawingMode("CROPPER");- inst.setCropzoneRect(mode);- }, 10);- };+ const inst = imageEditorRef.current?.getInstance()+ inst.stopDrawingMode()+ inst.startDrawingMode('CROPPER')+ inst.setCropzoneRect(mode)+ }, 10)+ }}useEffect(() => {- isInit.current = false;+ isInit.current = falseconst timeId = setInterval(() => {if (- !isInit.current &&- document.querySelector(".tie-crop-preset-button")+ !isInit.current+ && document.querySelector('.tie-crop-preset-button')) {- addCropPreset("preset-4-5", "4:5", 4 / 5);- addCropPreset("preset-1-1", "1:1", 1);- addCropPreset("preset-9_1-1", "1.91:1", 1.91);- clearInterval(timeId);+ addCropPreset('preset-4-5', '4:5', 4 / 5)+ addCropPreset('preset-1-1', '1:1', 1)+ addCropPreset('preset-9_1-1', '1.91:1', 1.91)+ clearInterval(timeId)}- }, 100);- }, [imgFile?.imgUrl]);+ }, 100)+ }, [imgFile?.imgUrl])return (<Modal- title={t("imageEditing")}+ title={t('imageEditing')}open={open}onCancel={onCancel}getContainer={() => document.body}width={1100}- footer={+ footer={(<><Button size="large" onClick={onCancel}>- {account.t("deleteConfirm.cancel")}+ {account.t('deleteConfirm.cancel')}</Button><Buttontype="primary"size="large"loading={uploadLoading}onClick={async () => {- const inst = imageEditorRef.current?.getInstance();- if (!inst) return "";- setUploadLoading(true);- const base64 = inst.toDataURL({ format: "png", quality: 1 });- const blob = dataURLToBlob(base64);+ const inst = imageEditorRef.current?.getInstance()+ if (!inst)+ return ''+ setUploadLoading(true)+ const base64 = inst.toDataURL({ format: 'png', quality: 1 })+ const blob = dataURLToBlob(base64)const image = await formatImg({- blob: blob,+ blob,path:- imgFile?.filename ||- `aitoearn_edited_image_${Date.now()}.png`,- });- const uploadCoverRes = await uploadToOss(image.file);- image["ossUrl"] = getOssUrl(uploadCoverRes);- setUploadLoading(false);- onOk(image);- onCancel();+ imgFile?.filename+ || `aitoearn_edited_image_${Date.now()}.png`,+ })+ const uploadCoverRes = await uploadToOss(image.file)+ image.ossUrl = getOssUrl(uploadCoverRes)+ setUploadLoading(false)+ onOk(image)+ onCancel()}}>- {account.t("createSpace.save")}+ {account.t('createSpace.save')}</Button></>- }+ )}><div className={styles.imageEditorModal}><ImageEditor@@ -151,20 +156,20 @@ const ImageEditorModal = memo(...(imageEditorLocale ? { locale: imageEditorLocale } : {}),loadImage: {path: imgFile?.imgUrl,- name: "SampleImage",+ name: 'SampleImage',},menu: [- "crop",- "flip",- "rotate",- "draw",- "shape",- "icon",- "text",- "filter",+ 'crop',+ 'flip',+ 'rotate',+ 'draw',+ 'shape',+ 'icon',+ 'text',+ 'filter',],- uiSize: { width: "1000px", height: "700px" },- menuBarPosition: "bottom",+ uiSize: { width: '1000px', height: '700px' },+ menuBarPosition: 'bottom',}}cssMaxHeight={430}cssMaxWidth={800}@@ -173,9 +178,9 @@ const ImageEditorModal = memo(/></div></Modal>- );+ )},),-);+)-export default ImageEditorModal;+export default ImageEditorModaldiff --git a/project/web/src/components/PublishDialog/PublishDialog.util.ts b/project/web/src/components/PublishDialog/PublishDialog.util.tsindex 96fb84b7..4d64b713 100644--- a/project/web/src/components/PublishDialog/PublishDialog.util.ts+++ b/project/web/src/components/PublishDialog/PublishDialog.util.ts@@ -1,98 +1,98 @@-import { RcFile } from "antd/es/upload";-import {+import type { RcFile } from 'antd/es/upload'+import type {IImgFile,IVideoFile,-} from "@/components/PublishDialog/publishDialog.type";-import { generateUUID, getFilePathName } from "@/utils";+} from '@/components/PublishDialog/publishDialog.type'+import { generateUUID, getFilePathName } from '@/utils'-export const formatVideo = async (file: RcFile): Promise<IVideoFile> => {- const videoUrl = URL.createObjectURL(file);- const videoInfo = await VideoGrabFrame(videoUrl, 0);+export async function formatVideo(file: RcFile): Promise<IVideoFile> {+ const videoUrl = URL.createObjectURL(file)+ const videoInfo = await VideoGrabFrame(videoUrl, 0)return {filename: file.name,videoUrl,size: file.size!,- file: file,+ file,...videoInfo,- };-};+ }+}export function VideoGrabFrame(videoUrl: string,currentTime: number,): Promise<{- width: number;- height: number;+ width: number+ height: number// 下取整的时长- duration: number;+ duration: number// 视频首帧- cover: IImgFile;+ cover: IImgFile}> {return new Promise((resolve) => {- const video = document.createElement("video");- video.src = videoUrl;+ const video = document.createElement('video')+ video.src = videoUrl// 当视频元数据加载完毕时执行回调- video.addEventListener("loadedmetadata", () => {- video.currentTime = currentTime;- });+ video.addEventListener('loadedmetadata', () => {+ video.currentTime = currentTime+ })- video.addEventListener("seeked", function () {+ video.addEventListener('seeked', () => {// 获取视频的宽度和高度- const width = video.videoWidth;- const height = video.videoHeight;+ const width = video.videoWidth+ const height = video.videoHeight// 获取视频的时长- const duration = video.duration;+ const duration = video.duration// 获取视频首帧- const canvas = document.createElement("canvas");- canvas.width = width;- canvas.height = height;- const context = canvas.getContext("2d")!;- context.fillStyle = "white";- context.fillRect(0, 0, width, height);- context.drawImage(video, 0, 0);+ const canvas = document.createElement('canvas')+ canvas.width = width+ canvas.height = height+ const context = canvas.getContext('2d')!+ context.fillStyle = 'white'+ context.fillRect(0, 0, width, height)+ context.drawImage(video, 0, 0)canvas.toBlob(async (blob) => {const cover = await formatImg({blob: blob!,- path: `cover.${blob!.type.split("/")[1]}`,- });+ path: `cover.${blob!.type.split('/')[1]}`,+ })resolve({width,height,duration: Math.floor(duration),cover,- });- video.remove();- });- });+ })+ video.remove()+ })+ })// 加载视频- video.load();- });+ video.load()+ })}-export const formatImg = async ({+export async function formatImg({path,file,blob,}: {- path: string;- file?: Uint8Array;- blob?: Blob;-}): Promise<IImgFile> => {+ path: string+ file?: Uint8Array+ blob?: Blob+}): Promise<IImgFile> {return new Promise((resolve) => {- const { filename, suffix } = getFilePathName(path);+ const { filename, suffix } = getFilePathName(path)if (!blob) {// @ts-ignoreblob = new Blob([file!], {type: `image/${suffix}`,- });+ })}- const imgUrl = URL.createObjectURL(blob);+ const imgUrl = URL.createObjectURL(blob)- const img = new Image();+ const img = new Image()img.onload = () => {resolve({id: generateUUID(),@@ -103,11 +103,11 @@ export const formatImg = async ({filename,file: new File([blob!], filename, { type: blob!.type }),imgUrl,- });- };- img.src = imgUrl;- });-};+ })+ }+ img.src = imgUrl+ })+}/*** 判断宽高是否属于指定比例(带缓冲阈值)@@ -122,9 +122,10 @@ export function isAspectRatioMatch(ratio: number,threshold: number = 0.02,): boolean {- if (height === 0) return false;- const actualRatio = width / height;- return Math.abs(actualRatio - ratio) <= threshold;+ if (height === 0)+ return false+ const actualRatio = width / height+ return Math.abs(actualRatio - ratio) <= threshold}/**@@ -142,7 +143,8 @@ export function isAspectRatioInRange(maxRatio: number,threshold: number = 0.02,): boolean {- if (height === 0) return false;- const actualRatio = width / height;- return actualRatio >= minRatio - threshold && actualRatio <= maxRatio + threshold;-}\ No newline at end of file+ if (height === 0)+ return false+ const actualRatio = width / height+ return actualRatio >= minRatio - threshold && actualRatio <= maxRatio + threshold+}diff --git a/project/web/src/components/PublishDialog/compoents/Choose/ImgChoose.tsx b/project/web/src/components/PublishDialog/compoents/Choose/ImgChoose.tsxindex b0bd1e6a..8478ba51 100644--- a/project/web/src/components/PublishDialog/compoents/Choose/ImgChoose.tsx+++ b/project/web/src/components/PublishDialog/compoents/Choose/ImgChoose.tsx@@ -1,17 +1,18 @@-import { Button, message, Upload } from "antd";-import { FC, useRef } from "react";-import { RcFile } from "antd/es/upload";-import { formatImg } from "@/components/PublishDialog/PublishDialog.util";-import { IImgFile } from "@/components/PublishDialog/publishDialog.type";+import type { RcFile } from 'antd/es/upload'+import type { FC } from 'react'+import type { IImgFile } from '@/components/PublishDialog/publishDialog.type'+import { Button, message, Upload } from 'antd'+import { useRef } from 'react'+import { formatImg } from '@/components/PublishDialog/PublishDialog.util'interface ImgChooseProps {// 单选就使用单选方法,多选就使用单选方法// 单选返回- onChoose?: (_: IImgFile) => void;+ onChoose?: (_: IImgFile) => void// 多选返回方法- onMultipleChoose?: (_: IImgFile[]) => void;- children?: React.ReactNode;+ onMultipleChoose?: (_: IImgFile[]) => void+ children?: React.ReactNode}const ImgChoose: FC<ImgChooseProps> = ({@@ -19,61 +20,65 @@ const ImgChoose: FC<ImgChooseProps> = ({onMultipleChoose,children,}) => {- const chooseCount = useRef<number>(0);- const fileListRef = useRef<RcFile[]>([]);+ const chooseCount = useRef<number>(0)+ const fileListRef = useRef<RcFile[]>([])/*** 发送上传的事件*/const handleUploadImg = async () => {try {- const tasks: Promise<IImgFile>[] = [];+ const tasks: Promise<IImgFile>[] = []for (const file of fileListRef.current) {tasks.push(formatImg({path: file.name,blob: file,}),- );+ )}- const imgFiles = await Promise.all(tasks);+ const imgFiles = await Promise.all(tasks)if (onMultipleChoose) {- onMultipleChoose(imgFiles);- } else if (onChoose) {- onChoose(imgFiles[0]);+ onMultipleChoose(imgFiles)}- } catch (e) {- message.error("选择图片失败");- console.error(e);+ else if (onChoose) {+ onChoose(imgFiles[0])+ }+ }+ catch (e) {+ message.error('选择图片失败')+ console.error(e)}- };+ }return (<Uploadaccept="image/*"multiple={!!onMultipleChoose}beforeUpload={async (file, uploadFileList) => {- chooseCount.current++;- fileListRef.current = [...fileListRef.current, file];+ chooseCount.current+++ fileListRef.current = [...fileListRef.current, file]if (chooseCount.current === uploadFileList.length) {- await handleUploadImg();- fileListRef.current = [];- chooseCount.current = 0;+ await handleUploadImg()+ fileListRef.current = []+ chooseCount.current = 0}- return Upload.LIST_IGNORE;+ return Upload.LIST_IGNORE}}>- {children ? (- <div className="imgChoose" style={{ cursor: "pointer" }}>- {children}- </div>- ) : (- <Button type="primary">选择图片</Button>- )}+ {children+ ? (+ <div className="imgChoose" style={{ cursor: 'pointer' }}>+ {children}+ </div>+ )+ : (+ <Button type="primary">选择图片</Button>+ )}</Upload>- );-};+ )+}-export default ImgChoose;+export default ImgChoosediff --git a/project/web/src/components/PublishDialog/compoents/DraftSelectionModal/index.tsx b/project/web/src/components/PublishDialog/compoents/DraftSelectionModal/index.tsxindex 2493b7e1..e8f0d2c7 100644--- a/project/web/src/components/PublishDialog/compoents/DraftSelectionModal/index.tsx+++ b/project/web/src/components/PublishDialog/compoents/DraftSelectionModal/index.tsx@@ -1,28 +1,30 @@-import {+import type {ForwardedRef,+} from 'react'+import { FolderOpenOutlined } from '@ant-design/icons'+import { Button, List, message, Modal, Spin } from 'antd'+import {forwardRef,memo,useCallback,useEffect,useMemo,useState,-} from "react";-import { Button, List, message, Modal, Spin } from "antd";-import { FolderOpenOutlined } from "@ant-design/icons";-import { PubType } from "@/app/config/publishConfig";-import { getOssUrl } from "@/utils/oss";-import { apiGetMaterialGroupList, apiGetMaterialList } from "@/api/material";-import { AccountPlatInfoMap } from "@/app/config/platConfig";-import { useTransClient } from "@/app/i18n/client";-import { usePublishDialog } from "@/components/PublishDialog/usePublishDialog";-import { useShallow } from "zustand/react/shallow";+} from 'react'+import { useShallow } from 'zustand/react/shallow'+import { apiGetMaterialGroupList, apiGetMaterialList } from '@/api/material'+import { AccountPlatInfoMap } from '@/app/config/platConfig'+import { PubType } from '@/app/config/publishConfig'+import { useTransClient } from '@/app/i18n/client'+import { usePublishDialog } from '@/components/PublishDialog/usePublishDialog'+import { getOssUrl } from '@/utils/oss'export interface IDraftSelectionModalRef {}export interface IDraftSelectionModalProps {- draftModalOpen: boolean;- onCancel: () => void;- onSelectDraft?: (draft: any) => void; // 新增:选择草稿后的回调函数+ draftModalOpen: boolean+ onCancel: () => void+ onSelectDraft?: (draft: any) => void // 新增:选择草稿后的回调函数}const DraftSelectionModal = memo(@@ -38,158 +40,167 @@ const DraftSelectionModal = memo(expandedPubItem,setOnePubParams,} = usePublishDialog(- useShallow((state) => ({+ useShallow(state => ({pubListChoosed: state.pubListChoosed,step: state.step,setAccountAllParams: state.setAccountAllParams,expandedPubItem: state.expandedPubItem,setOnePubParams: state.setOnePubParams,})),- );- const { t } = useTransClient("publish");- const [groupLoading, setGroupLoading] = useState(false);- const [groups, setGroups] = useState<any[]>([]);- const [selectedGroup, setSelectedGroup] = useState<any | null>(null);- const [draftLoading, setDraftLoading] = useState(false);- const [drafts, setDrafts] = useState<any[]>([]);+ )+ const { t } = useTransClient('publish')+ const [groupLoading, setGroupLoading] = useState(false)+ const [groups, setGroups] = useState<any[]>([])+ const [selectedGroup, setSelectedGroup] = useState<any | null>(null)+ const [draftLoading, setDraftLoading] = useState(false)+ const [drafts, setDrafts] = useState<any[]>([])// 过滤可用类型(根据当前步骤和账户选择)const allowImage = useMemo(() => {if (step === 1 && expandedPubItem) {const platConfig = AccountPlatInfoMap.get(expandedPubItem.account.type,- )!;- return platConfig.pubTypes.has(PubType.ImageText);+ )!+ return platConfig.pubTypes.has(PubType.ImageText)}if (pubListChoosed.length === 1) {const platConfig = AccountPlatInfoMap.get(pubListChoosed[0].account.type,- )!;- return platConfig.pubTypes.has(PubType.ImageText);+ )!+ return platConfig.pubTypes.has(PubType.ImageText)}- return true;- }, [step, expandedPubItem, pubListChoosed]);+ return true+ }, [step, expandedPubItem, pubListChoosed])const allowVideo = useMemo(() => {if (step === 1 && expandedPubItem) {const platConfig = AccountPlatInfoMap.get(expandedPubItem.account.type,- )!;- return platConfig.pubTypes.has(PubType.VIDEO);+ )!+ return platConfig.pubTypes.has(PubType.VIDEO)}if (pubListChoosed.length === 1) {const platConfig = AccountPlatInfoMap.get(pubListChoosed[0].account.type,- )!;- return platConfig.pubTypes.has(PubType.VIDEO);+ )!+ return platConfig.pubTypes.has(PubType.VIDEO)}- return true;- }, [step, expandedPubItem, pubListChoosed]);+ return true+ }, [step, expandedPubItem, pubListChoosed])const fetchGroups = useCallback(async () => {try {- setGroupLoading(true);- const res: any = await apiGetMaterialGroupList(1, 100);- const list = res?.data?.list || [];+ setGroupLoading(true)+ const res: any = await apiGetMaterialGroupList(1, 100)+ const list = res?.data?.list || []const filtered = list.filter((g: any) => {- if (g.type === PubType.ImageText) return allowImage;- if (g.type === PubType.VIDEO) return allowVideo;- return true;- });- setGroups(filtered);- } catch (e) {- } finally {- setGroupLoading(false);+ if (g.type === PubType.ImageText)+ return allowImage+ if (g.type === PubType.VIDEO)+ return allowVideo+ return true+ })+ setGroups(filtered)+ }+ catch (e) {}- }, [allowImage, allowVideo]);+ finally {+ setGroupLoading(false)+ }+ }, [allowImage, allowVideo])const fetchDrafts = useCallback(async (groupId: string) => {try {- setDraftLoading(true);- const res: any = await apiGetMaterialList(groupId, 1, 100);- setDrafts(res?.data?.list || []);- } catch (e) {- } finally {- setDraftLoading(false);+ setDraftLoading(true)+ const res: any = await apiGetMaterialList(groupId, 1, 100)+ setDrafts(res?.data?.list || [])+ }+ catch (e) {}- }, []);+ finally {+ setDraftLoading(false)+ }+ }, [])// 选择草稿后填充参数const applyDraft = useCallback((draft: any) => {// 如果有自定义回调,优先使用自定义回调if (onSelectDraft) {- onSelectDraft(draft);- onCancel();- message.success(t("draft.selectDraftSuccess"));- return;+ onSelectDraft(draft)+ onCancel()+ message.success(t('draft.selectDraftSuccess'))+ return}// 否则使用默认的填充逻辑- const nextParams: any = {};- if (draft.title) nextParams.title = draft.title;- if (draft.desc) nextParams.des = draft.desc;+ const nextParams: any = {}+ if (draft.title)+ nextParams.title = draft.title+ if (draft.desc)+ nextParams.des = draft.desc// 处理媒体内容if (Array.isArray(draft.mediaList) && draft.mediaList.length > 0) {const videos = draft.mediaList.filter((m: any) => m.type === PubType.VIDEO,- );+ )const images = draft.mediaList.filter((m: any) => m.type !== PubType.VIDEO,- );+ )// 如果有视频,设置视频参数if (videos.length > 0) {- const firstVideo = videos[0];- const ossUrl = getOssUrl(firstVideo.url);- const coverOss = getOssUrl(draft.coverUrl);+ const firstVideo = videos[0]+ const ossUrl = getOssUrl(firstVideo.url)+ const coverOss = getOssUrl(draft.coverUrl)nextParams.video = {- ossUrl: ossUrl,+ ossUrl,videoUrl: ossUrl,cover: {ossUrl: coverOss,imgUrl: coverOss,},- };+ }}// 如果有图片,设置图片参数if (images.length > 0) {nextParams.images = images.map((v: any) => {- const ossUrl = getOssUrl(v.url);+ const ossUrl = getOssUrl(v.url)return {ossUrl,imgUrl: ossUrl,- };- });+ }+ })}}if (step === 1 && expandedPubItem) {- setOnePubParams(nextParams, expandedPubItem.account.id);- } else {- setAccountAllParams(nextParams);+ setOnePubParams(nextParams, expandedPubItem.account.id)+ }+ else {+ setAccountAllParams(nextParams)}- onCancel();- message.success(t("draft.selectDraftSuccess"));+ onCancel()+ message.success(t('draft.selectDraftSuccess'))},[setAccountAllParams, setOnePubParams, step, expandedPubItem, onSelectDraft, onCancel, t],- );+ )useEffect(() => {if (draftModalOpen) {- setSelectedGroup(null);- setDrafts([]);- fetchGroups();+ setSelectedGroup(null)+ setDrafts([])+ fetchGroups()}- }, [draftModalOpen, fetchGroups]);+ }, [draftModalOpen, fetchGroups])useEffect(() => {if (selectedGroup?._id) {- fetchDrafts(selectedGroup._id);+ fetchDrafts(selectedGroup._id)}- }, [selectedGroup, fetchDrafts]);+ }, [selectedGroup, fetchDrafts])return (<Modal@@ -198,168 +209,174 @@ const DraftSelectionModal = memo(footer={null}title={selectedGroup- ? t("draft.selectDraftItem")- : t("draft.selectDraftGroup")+ ? t('draft.selectDraftItem')+ : t('draft.selectDraftGroup')}width={720}zIndex={20}>- {!selectedGroup ? (- <div>- {groupLoading ? (- <div style={{ textAlign: "center", padding: 24 }}>- <Spin />- </div>- ) : (- <List- grid={{ gutter: 16, column: 2 }}- dataSource={groups}- locale={{ emptyText: t("draft.noDraftGroups") }}- renderItem={(item: any) => (- <List.Item>- <div- style={{- background: "#FAEFFC",- border: "2px solid transparent",- padding: "16px",- borderRadius: "12px",- cursor: "pointer",- transition: "all 0.3s ease",- minHeight: "80px",- display: "flex",- flexDirection: "column",- justifyContent: "center",- alignItems: "center",- textAlign: "center",- position: "relative",- }}- onClick={() => setSelectedGroup(item)}- >- <div- style={{- fontSize: 24,- marginBottom: 8,- color: "#667eea",- }}- >- <FolderOpenOutlined />- </div>- <div- style={{- fontWeight: 600,- fontSize: 16,- color: "#2c3e50",- marginBottom: 4,- }}- >- {item.name || item.title}+ {!selectedGroup+ ? (+ <div>+ {groupLoading+ ? (+ <div style={{ textAlign: 'center', padding: 24 }}>+ <Spin /></div>- {item.desc && (- <div- style={{- fontSize: 12,- color: "#7f8c8d",- lineHeight: 1.4,- }}- >- {item.desc}- </div>- )}- <div- style={{- position: "absolute",- top: 8,- left: 8,- padding: "2px 8px",- borderRadius: "12px",- fontSize: 10,- color: "#fff",- background:+ )+ : (+ <List+ grid={{ gutter: 16, column: 2 }}+ dataSource={groups}+ locale={{ emptyText: t('draft.noDraftGroups') }}+ renderItem={(item: any) => (+ <List.Item>+ <div+ style={{+ background: '#FAEFFC',+ border: '2px solid transparent',+ padding: '16px',+ borderRadius: '12px',+ cursor: 'pointer',+ transition: 'all 0.3s ease',+ minHeight: '80px',+ display: 'flex',+ flexDirection: 'column',+ justifyContent: 'center',+ alignItems: 'center',+ textAlign: 'center',+ position: 'relative',+ }}+ onClick={() => setSelectedGroup(item)}+ >+ <div+ style={{+ fontSize: 24,+ marginBottom: 8,+ color: '#667eea',+ }}+ >+ <FolderOpenOutlined />+ </div>+ <div+ style={{+ fontWeight: 600,+ fontSize: 16,+ color: '#2c3e50',+ marginBottom: 4,+ }}+ >+ {item.name || item.title}+ </div>+ {item.desc && (+ <div+ style={{+ fontSize: 12,+ color: '#7f8c8d',+ lineHeight: 1.4,+ }}+ >+ {item.desc}+ </div>+ )}+ <div+ style={{+ position: 'absolute',+ top: 8,+ left: 8,+ padding: '2px 8px',+ borderRadius: '12px',+ fontSize: 10,+ color: '#fff',+ background:item.type === PubType.ImageText- ? "#52c41a"- : "#1890ff",- }}- >- {item.type === PubType.ImageText- ? t("draft.imageGroup")- : t("draft.videoGroup")}- </div>- </div>- </List.Item>- )}- />- )}- </div>- ) : (- <div>- <div style={{ marginBottom: 12 }}>- <Button type="link" onClick={() => setSelectedGroup(null)}>- {t("draft.backToGroups")}- </Button>- </div>- {draftLoading ? (- <div style={{ textAlign: "center", padding: 24 }}>- <Spin />+ ? '#52c41a'+ : '#1890ff',+ }}+ >+ {item.type === PubType.ImageText+ ? t('draft.imageGroup')+ : t('draft.videoGroup')}+ </div>+ </div>+ </List.Item>+ )}+ />+ )}</div>- ) : (- <List- grid={{ gutter: 16, column: 2 }}- dataSource={drafts}- locale={{ emptyText: t("draft.noDrafts") }}- renderItem={(item: any) => (- <List.Item>- <div- style={{- border: "1px solid #eee",- borderRadius: 8,- overflow: "hidden",- cursor: "pointer",- }}- onClick={() => applyDraft(item)}- >- <div- style={{- width: "100%",- paddingTop: "56%",- position: "relative",- background: "#f7f7f7",- }}- >- {Array.isArray(item.mediaList) &&- item.mediaList[0] && (- <img- src={getOssUrl(item.coverUrl)}- alt=""+ )+ : (+ <div>+ <div style={{ marginBottom: 12 }}>+ <Button type="link" onClick={() => setSelectedGroup(null)}>+ {t('draft.backToGroups')}+ </Button>+ </div>+ {draftLoading+ ? (+ <div style={{ textAlign: 'center', padding: 24 }}>+ <Spin />+ </div>+ )+ : (+ <List+ grid={{ gutter: 16, column: 2 }}+ dataSource={drafts}+ locale={{ emptyText: t('draft.noDrafts') }}+ renderItem={(item: any) => (+ <List.Item>+ <divstyle={{- position: "absolute",- left: 0,- top: 0,- width: "100%",- height: "100%",- objectFit: "cover",+ border: '1px solid #eee',+ borderRadius: 8,+ overflow: 'hidden',+ cursor: 'pointer',}}- />- )}- </div>- <div style={{ padding: 8 }}>- <div style={{ fontWeight: 600 }}>- {item.title || "-"}- </div>- <div style={{ fontSize: 12, color: "#999" }}>- {item.desc || ""}- </div>- </div>- </div>- </List.Item>- )}- />+ onClick={() => applyDraft(item)}+ >+ <div+ style={{+ width: '100%',+ paddingTop: '56%',+ position: 'relative',+ background: '#f7f7f7',+ }}+ >+ {Array.isArray(item.mediaList)+ && item.mediaList[0] && (+ <img+ src={getOssUrl(item.coverUrl)}+ alt=""+ style={{+ position: 'absolute',+ left: 0,+ top: 0,+ width: '100%',+ height: '100%',+ objectFit: 'cover',+ }}+ />+ )}+ </div>+ <div style={{ padding: 8 }}>+ <div style={{ fontWeight: 600 }}>+ {item.title || '-'}+ </div>+ <div style={{ fontSize: 12, color: '#999' }}>+ {item.desc || ''}+ </div>+ </div>+ </div>+ </List.Item>+ )}+ />+ )}+ </div>)}- </div>- )}</Modal>- );+ )},),-);+)-export default DraftSelectionModal;+export default DraftSelectionModaldiff --git a/project/web/src/components/PublishDialog/compoents/MaterialSelectionModal/index.tsx b/project/web/src/components/PublishDialog/compoents/MaterialSelectionModal/index.tsxindex 1e221a66..8e5ae317 100644--- a/project/web/src/components/PublishDialog/compoents/MaterialSelectionModal/index.tsx+++ b/project/web/src/components/PublishDialog/compoents/MaterialSelectionModal/index.tsx@@ -1,25 +1,27 @@-import {+import type {ForwardedRef,+} from 'react'+import { PictureOutlined } from '@ant-design/icons'+import { Button, List, Modal, Spin } from 'antd'+import {forwardRef,memo,useCallback,useEffect,useState,-} from "react";-import { Button, List, Modal, Spin } from "antd";-import { PictureOutlined } from "@ant-design/icons";-import { getOssUrl } from "@/utils/oss";-import { useTransClient } from "@/app/i18n/client";-import { getMediaGroupList, getMediaList } from "@/api/media";+} from 'react'+import { getMediaGroupList, getMediaList } from '@/api/media'+import { useTransClient } from '@/app/i18n/client'+import { getOssUrl } from '@/utils/oss'export interface IMaterialSelectionModalRef {}export interface IMaterialSelectionModalProps {- allowImage?: boolean;- allowVideo?: boolean;- libraryModalOpen: boolean;- onCancel: () => void;- onSelected?: (item: any) => void;+ allowImage?: boolean+ allowVideo?: boolean+ libraryModalOpen: boolean+ onCancel: () => void+ onSelected?: (item: any) => void}const MaterialSelectionModal = memo(@@ -35,68 +37,74 @@ const MaterialSelectionModal = memo(ref: ForwardedRef<IMaterialSelectionModalRef>,) => {// 素材库选择弹窗/数据- const [libraryGroupLoading, setLibraryGroupLoading] = useState(false);- const [libraryGroups, setLibraryGroups] = useState<any[]>([]);+ const [libraryGroupLoading, setLibraryGroupLoading] = useState(false)+ const [libraryGroups, setLibraryGroups] = useState<any[]>([])const [selectedLibraryGroup, setSelectedLibraryGroup] = useState<any | null- >(null);- const [libraryLoading, setLibraryLoading] = useState(false);- const [libraryItems, setLibraryItems] = useState<any[]>([]);- const { t } = useTransClient("publish");+ >(null)+ const [libraryLoading, setLibraryLoading] = useState(false)+ const [libraryItems, setLibraryItems] = useState<any[]>([])+ const { t } = useTransClient('publish')// 获取素材库组列表const fetchLibraryGroups = useCallback(async () => {try {- setLibraryGroupLoading(true);- const res: any = await getMediaGroupList(1, 100);- const list = res?.data?.list || [];+ setLibraryGroupLoading(true)+ const res: any = await getMediaGroupList(1, 100)+ const list = res?.data?.list || []const filtered = list.filter((g: any) => {- if (g.type === "img") return allowImage;- if (g.type === "video") return allowVideo;- return true;- });- setLibraryGroups(filtered);- } catch (e) {- } finally {- setLibraryGroupLoading(false);+ if (g.type === 'img')+ return allowImage+ if (g.type === 'video')+ return allowVideo+ return true+ })+ setLibraryGroups(filtered)+ }+ catch (e) {+ }+ finally {+ setLibraryGroupLoading(false)}- }, [allowImage, allowVideo]);+ }, [allowImage, allowVideo])// 获取素材库内容const fetchLibraryItems = useCallback(async (groupId: string) => {try {- setLibraryLoading(true);- const res: any = await getMediaList(groupId, 1, 100);- setLibraryItems(res?.data?.list || []);- } catch (e) {- } finally {- setLibraryLoading(false);+ setLibraryLoading(true)+ const res: any = await getMediaList(groupId, 1, 100)+ setLibraryItems(res?.data?.list || [])}- }, []);+ catch (e) {+ }+ finally {+ setLibraryLoading(false)+ }+ }, [])// 素材库弹窗打开时获取组列表useEffect(() => {if (libraryModalOpen) {- setSelectedLibraryGroup(null);- setLibraryItems([]);- fetchLibraryGroups();+ setSelectedLibraryGroup(null)+ setLibraryItems([])+ fetchLibraryGroups()}- }, [libraryModalOpen, fetchLibraryGroups]);+ }, [libraryModalOpen, fetchLibraryGroups])// 选中素材库组后加载组内素材useEffect(() => {if (selectedLibraryGroup?._id) {- fetchLibraryItems(selectedLibraryGroup._id);+ fetchLibraryItems(selectedLibraryGroup._id)}- }, [selectedLibraryGroup, fetchLibraryItems]);+ }, [selectedLibraryGroup, fetchLibraryItems])// 选择素材库内容后填充参数const applyLibraryItem = useCallback(async (item: any) => {if (onSelected) {- onSelected(item);- onCancel();+ onSelected(item)+ onCancel()}- }, []);+ }, [])return (<Modal@@ -105,179 +113,187 @@ const MaterialSelectionModal = memo(footer={null}title={selectedLibraryGroup- ? t("draft.selectLibraryItem")- : t("draft.selectLibraryGroup")+ ? t('draft.selectLibraryItem')+ : t('draft.selectLibraryGroup')}width={720}>- {!selectedLibraryGroup ? (- <div>- {libraryGroupLoading ? (- <div style={{ textAlign: "center", padding: 24 }}>- <Spin />- </div>- ) : (- <List- grid={{ gutter: 16, column: 2 }}- dataSource={libraryGroups}- locale={{ emptyText: t("draft.noLibraryGroups") }}- renderItem={(item: any) => (- <List.Item>- <div- style={{- background: "#F0F8FF",- border: "2px solid transparent",- padding: "16px",- borderRadius: "12px",- cursor: "pointer",- transition: "all 0.3s ease",- minHeight: "80px",- display: "flex",- flexDirection: "column",- justifyContent: "center",- alignItems: "center",- textAlign: "center",- position: "relative",- }}- onClick={() => setSelectedLibraryGroup(item)}- >- <div- style={{- fontSize: 24,- marginBottom: 8,- color: "#1890ff",- }}- >- <PictureOutlined />- </div>- <div- style={{- fontWeight: 600,- fontSize: 16,- color: "#2c3e50",- marginBottom: 4,- }}- >- {item.title}+ {!selectedLibraryGroup+ ? (+ <div>+ {libraryGroupLoading+ ? (+ <div style={{ textAlign: 'center', padding: 24 }}>+ <Spin /></div>- {item.desc && (- <div- style={{- fontSize: 12,- color: "#7f8c8d",- lineHeight: 1.4,- }}- >- {item.desc}- </div>- )}- <div- style={{- position: "absolute",- top: 8,- left: 8,- padding: "2px 8px",- borderRadius: "12px",- fontSize: 10,- color: "#fff",- background:- item.type === "img" ? "#52c41a" : "#1890ff",- }}- >- {item.type === "img"- ? t("draft.imageGroup")- : t("draft.videoGroup")}- </div>- </div>- </List.Item>- )}- />- )}- </div>- ) : (- <div>- <div style={{ marginBottom: 12 }}>- <Button- type="link"- onClick={() => setSelectedLibraryGroup(null)}- >- {t("draft.backToLibraryGroups")}- </Button>- </div>- {libraryLoading ? (- <div style={{ textAlign: "center", padding: 24 }}>- <Spin />- </div>- ) : (- <List- grid={{ gutter: 16, column: 2 }}- dataSource={libraryItems}- locale={{ emptyText: t("draft.noLibraryItems") }}- renderItem={(item: any) => (- <List.Item>- <div- style={{- border: "1px solid #eee",- borderRadius: 8,- overflow: "hidden",- cursor: "pointer",- }}- onClick={() => applyLibraryItem(item)}- >- <div- style={{- width: "100%",- paddingTop: "56%",- position: "relative",- background: "#f7f7f7",- }}- >- {item.type === "img" ? (- <img- src={getOssUrl(item.url)}- alt=""- style={{- position: "absolute",- left: 0,- top: 0,- width: "100%",- height: "100%",- objectFit: "cover",- }}- />- ) : (- <video- src={getOssUrl(item.url)}- style={{- position: "absolute",- left: 0,- top: 0,- width: "100%",- height: "100%",- objectFit: "cover",- }}- />+ )+ : (+ <List+ grid={{ gutter: 16, column: 2 }}+ dataSource={libraryGroups}+ locale={{ emptyText: t('draft.noLibraryGroups') }}+ renderItem={(item: any) => (+ <List.Item>+ <div+ style={{+ background: '#F0F8FF',+ border: '2px solid transparent',+ padding: '16px',+ borderRadius: '12px',+ cursor: 'pointer',+ transition: 'all 0.3s ease',+ minHeight: '80px',+ display: 'flex',+ flexDirection: 'column',+ justifyContent: 'center',+ alignItems: 'center',+ textAlign: 'center',+ position: 'relative',+ }}+ onClick={() => setSelectedLibraryGroup(item)}+ >+ <div+ style={{+ fontSize: 24,+ marginBottom: 8,+ color: '#1890ff',+ }}+ >+ <PictureOutlined />+ </div>+ <div+ style={{+ fontWeight: 600,+ fontSize: 16,+ color: '#2c3e50',+ marginBottom: 4,+ }}+ >+ {item.title}+ </div>+ {item.desc && (+ <div+ style={{+ fontSize: 12,+ color: '#7f8c8d',+ lineHeight: 1.4,+ }}+ >+ {item.desc}+ </div>+ )}+ <div+ style={{+ position: 'absolute',+ top: 8,+ left: 8,+ padding: '2px 8px',+ borderRadius: '12px',+ fontSize: 10,+ color: '#fff',+ background:+ item.type === 'img' ? '#52c41a' : '#1890ff',+ }}+ >+ {item.type === 'img'+ ? t('draft.imageGroup')+ : t('draft.videoGroup')}+ </div>+ </div>+ </List.Item>)}+ />+ )}+ </div>+ )+ : (+ <div>+ <div style={{ marginBottom: 12 }}>+ <Button+ type="link"+ onClick={() => setSelectedLibraryGroup(null)}+ >+ {t('draft.backToLibraryGroups')}+ </Button>+ </div>+ {libraryLoading+ ? (+ <div style={{ textAlign: 'center', padding: 24 }}>+ <Spin /></div>- <div style={{ padding: 8 }}>- <div style={{ fontWeight: 600 }}>- {item.title || "-"}- </div>- <div style={{ fontSize: 12, color: "#999" }}>- {item.desc || ""}- </div>- </div>- </div>- </List.Item>- )}- />+ )+ : (+ <List+ grid={{ gutter: 16, column: 2 }}+ dataSource={libraryItems}+ locale={{ emptyText: t('draft.noLibraryItems') }}+ renderItem={(item: any) => (+ <List.Item>+ <div+ style={{+ border: '1px solid #eee',+ borderRadius: 8,+ overflow: 'hidden',+ cursor: 'pointer',+ }}+ onClick={() => applyLibraryItem(item)}+ >+ <div+ style={{+ width: '100%',+ paddingTop: '56%',+ position: 'relative',+ background: '#f7f7f7',+ }}+ >+ {item.type === 'img'+ ? (+ <img+ src={getOssUrl(item.url)}+ alt=""+ style={{+ position: 'absolute',+ left: 0,+ top: 0,+ width: '100%',+ height: '100%',+ objectFit: 'cover',+ }}+ />+ )+ : (+ <video+ src={getOssUrl(item.url)}+ style={{+ position: 'absolute',+ left: 0,+ top: 0,+ width: '100%',+ height: '100%',+ objectFit: 'cover',+ }}+ />+ )}+ </div>+ <div style={{ padding: 8 }}>+ <div style={{ fontWeight: 600 }}>+ {item.title || '-'}+ </div>+ <div style={{ fontSize: 12, color: '#999' }}>+ {item.desc || ''}+ </div>+ </div>+ </div>+ </List.Item>+ )}+ />+ )}+ </div>)}- </div>- )}</Modal>- );+ )},),-);+)-export default MaterialSelectionModal;+export default MaterialSelectionModaldiff --git a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/common/CommonTitleInput.tsx b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/common/CommonTitleInput.tsxindex ea64fecc..23305d87 100644--- a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/common/CommonTitleInput.tsx+++ b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/common/CommonTitleInput.tsx@@ -1,16 +1,17 @@-import { ForwardedRef, forwardRef, memo, useMemo } from "react";-import styles from "../platParamsSetting.module.scss";-import { Input } from "antd";-import { AccountPlatInfoMap, PlatType } from "@/app/config/platConfig";-import { PubItem } from "@/components/PublishDialog/publishDialog.type";-import { usePublishDialog } from "@/components/PublishDialog/usePublishDialog";-import { useShallow } from "zustand/react/shallow";-import { useTransClient } from "@/app/i18n/client";+import type { ForwardedRef } from 'react'+import type { PubItem } from '@/components/PublishDialog/publishDialog.type'+import { Input } from 'antd'+import { forwardRef, memo, useMemo } from 'react'+import { useShallow } from 'zustand/react/shallow'+import { AccountPlatInfoMap, PlatType } from '@/app/config/platConfig'+import { useTransClient } from '@/app/i18n/client'+import { usePublishDialog } from '@/components/PublishDialog/usePublishDialog'+import styles from '../platParamsSetting.module.scss'export interface ICommonTitleInputRef {}export interface ICommonTitleInputProps {- pubItem: PubItem;+ pubItem: PubItem}const CommonTitleInput = memo(@@ -19,31 +20,31 @@ const CommonTitleInput = memo({ pubItem }: ICommonTitleInputProps,ref: ForwardedRef<ICommonTitleInputRef>,) => {- const { t } = useTransClient("publish");+ const { t } = useTransClient('publish')const platConfig = useMemo(() => {- return AccountPlatInfoMap.get(pubItem.account.type)!;- }, [pubItem]);+ return AccountPlatInfoMap.get(pubItem.account.type)!+ }, [pubItem])const { setOnePubParams, pubList } = usePublishDialog(- useShallow((state) => ({+ useShallow(state => ({setOnePubParams: state.setOnePubParams,pubList: state.pubList,})),- );+ )// 判断是否需要显示必填标识- const isRequired = pubItem.account.type === PlatType.Pinterest;+ const isRequired = pubItem.account.type === PlatType.Pinterestreturn (<div className={styles.commonTitleInput}><div className="platParamsSetting-label">- {t("form.title")}- {isRequired && <span style={{ color: "#ff4d4f", marginLeft: "4px" }}>*</span>}+ {t('form.title')}+ {isRequired && <span style={{ color: '#ff4d4f', marginLeft: '4px' }}>*</span>}</div><Inputvalue={pubItem.params.title}maxLength={platConfig.commonPubParamsConfig.titleMax || 20}- placeholder={t("form.titlePlaceholder") }+ placeholder={t('form.titlePlaceholder')}showCountonChange={(e) => {setOnePubParams(@@ -51,13 +52,13 @@ const CommonTitleInput = memo(title: e.target.value,},pubItem.account.id,- );+ )}}/></div>- );+ )},),-);+)-export default CommonTitleInput;+export default CommonTitleInputdiff --git a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon.tsx b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon.tsxindex 8b33d01f..62b841d7 100644--- a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon.tsx+++ b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon.tsx@@ -1,35 +1,35 @@-import { usePublishDialog } from "@/components/PublishDialog/usePublishDialog";-import { useShallow } from "zustand/react/shallow";-import { useCallback, useMemo } from "react";-import {+import type {IChangeParams,IPubParmasTextareaProps,-} from "@/components/PublishDialog/compoents/PubParmasTextarea";-import { PubItem } from "@/components/PublishDialog/publishDialog.type";-import { PubParamsVerifyInfo } from "@/components/PublishDialog/hooks/usePubParamsVerify";-import { Alert } from "antd";+} from '@/components/PublishDialog/compoents/PubParmasTextarea'+import type { PubItem } from '@/components/PublishDialog/publishDialog.type'+import { Alert } from 'antd'+import { useCallback, useMemo } from 'react'+import { useShallow } from 'zustand/react/shallow'+import { PubParamsVerifyInfo } from '@/components/PublishDialog/hooks/usePubParamsVerify'+import { usePublishDialog } from '@/components/PublishDialog/usePublishDialog'export default function usePlatParamsCommon(pubItem: PubItem) {- const { setOnePubParams, errParamsMap, pubListChoosed, warningParamsMap } =- usePublishDialog(- useShallow((state) => ({+ const { setOnePubParams, errParamsMap, pubListChoosed, warningParamsMap }+ = usePublishDialog(+ useShallow(state => ({setOnePubParams: state.setOnePubParams,step: state.step,errParamsMap: state.errParamsMap,pubListChoosed: state.pubListChoosed,warningParamsMap: state.warningParamsMap,})),- );+ )// 当前组件的错误消息const currErrItem = useMemo(() => {- return errParamsMap?.get(pubItem.account.id);- }, [errParamsMap, pubItem, pubListChoosed]);+ return errParamsMap?.get(pubItem.account.id)+ }, [errParamsMap, pubItem, pubListChoosed])// 当前组件的警告消息const currWarningItem = useMemo(() => {- return warningParamsMap?.get(pubItem.account.id);- }, [warningParamsMap, pubItem, pubListChoosed]);+ return warningParamsMap?.get(pubItem.account.id)+ }, [warningParamsMap, pubItem, pubListChoosed])const onChange = useCallback((values: IChangeParams) => {@@ -40,10 +40,10 @@ export default function usePlatParamsCommon(pubItem: PubItem) {video: values.video,},pubItem.account.id,- );+ )},[pubItem, setOnePubParams],- );+ )const pubParmasTextareaCommonParams = useMemo(() => {const props: IPubParmasTextareaProps = {@@ -62,18 +62,18 @@ export default function usePlatParamsCommon(pubItem: PubItem) {type="info"showIconmessage={- <p style={{ textAlign: "left" }}>{currWarningItem?.parErrMsg}</p>+ <p style={{ textAlign: 'left' }}>{currWarningItem?.parErrMsg}</p>}style={{- fontSize: "12px",+ fontSize: '12px',borderRadius: 0,- border: "none",+ border: 'none',}}/>),- };- return props;- }, [currErrItem, onChange, pubItem, currWarningItem]);+ }+ return props+ }, [currErrItem, onChange, pubItem, currWarningItem])- return { pubParmasTextareaCommonParams, setOnePubParams };+ return { pubParmasTextareaCommonParams, setOnePubParams }}diff --git a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/index.tsx b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/index.tsxindex 66032cd2..89395516 100644--- a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/index.tsx+++ b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/index.tsx@@ -1,25 +1,26 @@-import { CSSProperties, ForwardedRef, forwardRef, memo, useMemo } from "react";-import styles from "./platParamsSetting.module.scss";-import { usePublishDialog } from "@/components/PublishDialog/usePublishDialog";-import { AccountPlatInfoMap, PlatType } from "@/app/config/platConfig";-import BilibParams from "@/components/PublishDialog/compoents/PlatParamsSetting/plats/BilibParams";-import KwaiParams from "@/components/PublishDialog/compoents/PlatParamsSetting/plats/KwaiParams";-import FacebookParams from "@/components/PublishDialog/compoents/PlatParamsSetting/plats/FacebookParams";-import InstagramParams from "@/components/PublishDialog/compoents/PlatParamsSetting/plats/InstagramParams";-import YouTubeParams from "@/components/PublishDialog/compoents/PlatParamsSetting/plats/YouTubeParams";-import WxGzhParams from "@/components/PublishDialog/compoents/PlatParamsSetting/plats/WxGzhParams";-import PinterestParams from "@/components/PublishDialog/compoents/PlatParamsSetting/plats/PinterestParams";-import TikTokParams from "@/components/PublishDialog/compoents/PlatParamsSetting/plats/TikTokParams";-import ThreadsParams from "@/components/PublishDialog/compoents/PlatParamsSetting/plats/ThreadsParams";-import { useShallow } from "zustand/react/shallow";-import { PubItem } from "@/components/PublishDialog/publishDialog.type";-import { useTransClient } from "@/app/i18n/client";+import type { CSSProperties, ForwardedRef } from 'react'+import type { PubItem } from '@/components/PublishDialog/publishDialog.type'+import { forwardRef, memo, useMemo } from 'react'+import { useShallow } from 'zustand/react/shallow'+import { AccountPlatInfoMap, PlatType } from '@/app/config/platConfig'+import { useTransClient } from '@/app/i18n/client'+import BilibParams from '@/components/PublishDialog/compoents/PlatParamsSetting/plats/BilibParams'+import FacebookParams from '@/components/PublishDialog/compoents/PlatParamsSetting/plats/FacebookParams'+import InstagramParams from '@/components/PublishDialog/compoents/PlatParamsSetting/plats/InstagramParams'+import KwaiParams from '@/components/PublishDialog/compoents/PlatParamsSetting/plats/KwaiParams'+import PinterestParams from '@/components/PublishDialog/compoents/PlatParamsSetting/plats/PinterestParams'+import ThreadsParams from '@/components/PublishDialog/compoents/PlatParamsSetting/plats/ThreadsParams'+import TikTokParams from '@/components/PublishDialog/compoents/PlatParamsSetting/plats/TikTokParams'+import WxGzhParams from '@/components/PublishDialog/compoents/PlatParamsSetting/plats/WxGzhParams'+import YouTubeParams from '@/components/PublishDialog/compoents/PlatParamsSetting/plats/YouTubeParams'+import { usePublishDialog } from '@/components/PublishDialog/usePublishDialog'+import styles from './platParamsSetting.module.scss'export interface IPlatParamsSettingRef {}export interface IPlatParamsSettingProps {- pubItem: PubItem;- style?: CSSProperties;+ pubItem: PubItem+ style?: CSSProperties}const PlatParamsSetting = memo(@@ -29,94 +30,100 @@ const PlatParamsSetting = memo(ref: ForwardedRef<IPlatParamsSettingRef>,) => {const { expandedPubItem, step, setExpandedPubItem } = usePublishDialog(- useShallow((state) => ({+ useShallow(state => ({expandedPubItem: state.expandedPubItem,step: state.step,setExpandedPubItem: state.setExpandedPubItem,})),- );- const { t } = useTransClient("publish");+ )+ const { t } = useTransClient('publish')const platConfig = useMemo(() => {- return AccountPlatInfoMap.get(pubItem.account.type)!;- }, [pubItem]);+ return AccountPlatInfoMap.get(pubItem.account.type)!+ }, [pubItem])const PlatItemComp = useMemo(() => {switch (pubItem.account.type) {case PlatType.KWAI:- return <KwaiParams pubItem={pubItem} />;+ return <KwaiParams pubItem={pubItem} />case PlatType.BILIBILI:- return <BilibParams pubItem={pubItem} />;+ return <BilibParams pubItem={pubItem} />case PlatType.WxGzh:- return <WxGzhParams pubItem={pubItem} />;+ return <WxGzhParams pubItem={pubItem} />case PlatType.Facebook:- return <FacebookParams pubItem={pubItem} />;+ return <FacebookParams pubItem={pubItem} />case PlatType.Instagram:- return <InstagramParams pubItem={pubItem} />;+ return <InstagramParams pubItem={pubItem} />case PlatType.YouTube:- return <YouTubeParams pubItem={pubItem} />;+ return <YouTubeParams pubItem={pubItem} />case PlatType.Pinterest:- return <PinterestParams pubItem={pubItem} />;+ return <PinterestParams pubItem={pubItem} />case PlatType.Tiktok:- return <TikTokParams pubItem={pubItem} />;+ return <TikTokParams pubItem={pubItem} />case PlatType.Threads:- return <ThreadsParams pubItem={pubItem} />;+ return <ThreadsParams pubItem={pubItem} />default:- return <KwaiParams pubItem={pubItem} />;+ return <KwaiParams pubItem={pubItem} />}- }, [pubItem]);+ }, [pubItem])// true=展开当前账号的参数设置 false=不展开const isExpand = useMemo(() => {- if (step === 0) return true;- return expandedPubItem?.account.id === pubItem.account.id;- }, [expandedPubItem, pubItem]);+ if (step === 0)+ return true+ return expandedPubItem?.account.id === pubItem.account.id+ }, [expandedPubItem, pubItem])return (<divclassName={[styles.platParamsSetting,- !isExpand ? styles.platParamsSetting_expand : "",- ].join(" ")}- onClick={(e) => e.stopPropagation()}+ !isExpand ? styles.platParamsSetting_expand : '',+ ].join(' ')}+ onClick={e => e.stopPropagation()}style={style}><div className="platParamsSetting-wrapper"><div className="platParamsSetting-icon">- <img src={platConfig.icon} style={{ borderRadius: "50%" }} />+ <img src={platConfig.icon} style={{ borderRadius: '50%' }} /></div>- {isExpand ? (- PlatItemComp- ) : (- <div- className="platParamsSetting-des"- onClick={() => {- setExpandedPubItem(pubItem);- }}- >- <p- className={- platConfig.commonPubParamsConfig.desMax <- pubItem.params.des.length- ? "platParamsSetting-textOverflow"- : ""- }- >- {pubItem.params.des ? (- pubItem.params.des- ) : (- <span style={{ color: "var(--grayColor7)" }}>- {t("form.descriptionPlaceholder")}...- </span>- )}- </p>- </div>- )}+ {isExpand+ ? (+ PlatItemComp+ )+ : (+ <div+ className="platParamsSetting-des"+ onClick={() => {+ setExpandedPubItem(pubItem)+ }}+ >+ <p+ className={+ platConfig.commonPubParamsConfig.desMax+ < pubItem.params.des.length+ ? 'platParamsSetting-textOverflow'+ : ''+ }+ >+ {pubItem.params.des+ ? (+ pubItem.params.des+ )+ : (+ <span style={{ color: 'var(--grayColor7)' }}>+ {t('form.descriptionPlaceholder')}+ ...+ </span>+ )}+ </p>+ </div>+ )}</div></div>- );+ )},),-);+)-export default PlatParamsSetting;+export default PlatParamsSettingdiff --git a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/platParamsSetting.module.scss b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/platParamsSetting.module.scssindex 20a223e2..e59f9d7a 100644--- a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/platParamsSetting.module.scss+++ b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/platParamsSetting.module.scss@@ -58,9 +58,12 @@background-color: #ffffff !important;color: #333333 !important;border: 1px solid #d9d9d9 !important;- box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 9px 28px 8px rgba(0, 0, 0, 0.05) !important;+ box-shadow:+ 0 6px 16px 0 rgba(0, 0, 0, 0.08),+ 0 3px 6px -4px rgba(0, 0, 0, 0.12),+ 0 9px 28px 8px rgba(0, 0, 0, 0.05) !important;}-+.ant-tooltip .ant-tooltip-arrow::before {background-color: #ffffff !important;border: 1px solid #d9d9d9 !important;@@ -76,12 +79,10 @@color: #333333 !important;border: 1px solid #d9d9d9 !important;}-+.ant-tooltip .ant-tooltip-arrow::before {background-color: #ffffff !important;border: 1px solid #d9d9d9 !important;}}}--diff --git a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/BilibParams.tsx b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/BilibParams.tsxindex 2409ccdf..daa1553b 100644--- a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/BilibParams.tsx+++ b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/BilibParams.tsx@@ -1,111 +1,112 @@-import { ForwardedRef, forwardRef, memo, useEffect } from "react";-import {+import type { ForwardedRef } from 'react'+import type {IPlatsParamsProps,IPlatsParamsRef,-} from "@/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type";-import PubParmasTextarea from "@/components/PublishDialog/compoents/PubParmasTextarea";-import usePlatParamsCommon from "@/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon";-import CommonTitleInput from "@/components/PublishDialog/compoents/PlatParamsSetting/common/CommonTitleInput";-import { usePublishDialogData } from "@/components/PublishDialog/usePublishDialogData";-import { useShallow } from "zustand/react/shallow";-import styles from "../platParamsSetting.module.scss";-import { Input, Radio, Select } from "antd";-import { useTransClient } from "@/app/i18n/client";+} from '@/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type'+import { Input, Radio, Select } from 'antd'+import { forwardRef, memo, useEffect } from 'react'+import { useShallow } from 'zustand/react/shallow'+import { useTransClient } from '@/app/i18n/client'+import CommonTitleInput from '@/components/PublishDialog/compoents/PlatParamsSetting/common/CommonTitleInput'+import usePlatParamsCommon from '@/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon'+import PubParmasTextarea from '@/components/PublishDialog/compoents/PubParmasTextarea'+import { usePublishDialogData } from '@/components/PublishDialog/usePublishDialogData'+import styles from '../platParamsSetting.module.scss'const BilibParams = memo(forwardRef(({ pubItem }: IPlatsParamsProps, ref: ForwardedRef<IPlatsParamsRef>) => {- const { t } = useTransClient("publish");- const { pubParmasTextareaCommonParams, setOnePubParams } =- usePlatParamsCommon(pubItem);- const { getBilibiliPartitions, bilibiliPartitions } =- usePublishDialogData(- useShallow((state) => ({+ const { t } = useTransClient('publish')+ const { pubParmasTextareaCommonParams, setOnePubParams }+ = usePlatParamsCommon(pubItem)+ const { getBilibiliPartitions, bilibiliPartitions }+ = usePublishDialogData(+ useShallow(state => ({getBilibiliPartitions: state.getBilibiliPartitions,bilibiliPartitions: state.bilibiliPartitions,})),- );+ )useEffect(() => {- getBilibiliPartitions();- }, [getBilibiliPartitions]);+ getBilibiliPartitions()+ }, [getBilibiliPartitions])// 初始化Bilibili参数useEffect(() => {- const option = pubItem.params.option;+ const option = pubItem.params.optionif (!option.bilibili) {- option.bilibili = {};+ option.bilibili = {}}if (!option.bilibili.copyright) {- option.bilibili.copyright = 1;+ option.bilibili.copyright = 1setOnePubParams({option,},pubItem.account.id,- );+ )}- }, [pubItem.account.id]);+ }, [pubItem.account.id])return (<><PubParmasTextarea{...pubParmasTextareaCommonParams}- extend={+ extend={(<><CommonTitleInput pubItem={pubItem} /><divclassName={styles.commonTitleInput}- style={{ marginTop: "10px" }}+ style={{ marginTop: '10px' }}>- <div className="platParamsSetting-label">{t("form.partition")}</div>+ <div className="platParamsSetting-label">{t('form.partition')}</div><Select- style={{ width: "100%" }}+ style={{ width: '100%' }}options={bilibiliPartitions}value={pubItem.params.option.bilibili?.tid}onChange={(value) => {- const option = pubItem.params.option;- option.bilibili!.tid = value;+ const option = pubItem.params.option+ option.bilibili!.tid = valuesetOnePubParams({option,},pubItem.account.id,- );+ )}}showSearch={true}- placeholder={t("form.partitionPlaceholder")}+ placeholder={t('form.partitionPlaceholder')}fieldNames={{- label: "name",- value: "id",+ label: 'name',+ value: 'id',}}/></div><divclassName={styles.commonTitleInput}- style={{ marginTop: "10px" }}+ style={{ marginTop: '10px' }}>- <div className="platParamsSetting-label">{t("form.type")}</div>+ <div className="platParamsSetting-label">{t('form.type')}</div><Radio.Groupvalue={pubItem.params.option.bilibili?.copyright}options={[- { value: 1, label: t("form.original") },- { value: 2, label: t("form.reprint") },+ { value: 1, label: t('form.original') },+ { value: 2, label: t('form.reprint') },]}onChange={(e) => {- const option = pubItem.params.option;- const value = e.target.value;- option.bilibili!.copyright = value;+ const option = pubItem.params.option+ const value = e.target.value+ option.bilibili!.copyright = valueif (value === 1) {- option.bilibili!.source = "";+ option.bilibili!.source = ''}setOnePubParams({option,},pubItem.account.id,- );+ )}}/></div>@@ -113,19 +114,19 @@ const BilibParams = memo({pubItem.params.option.bilibili?.copyright === 2 && (<divclassName={styles.commonTitleInput}- style={{ marginTop: "10px" }}+ style={{ marginTop: '10px' }}>- <div className="platParamsSetting-label">{t("form.source")}</div>- <Input placeholder={t("form.sourcePlaceholder")} />+ <div className="platParamsSetting-label">{t('form.source')}</div>+ <Input placeholder={t('form.sourcePlaceholder')} /></div>)}</>- }+ )}/></>- );+ )},),-);+)-export default BilibParams;+export default BilibParamsdiff --git a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/FacebookParams.tsx b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/FacebookParams.tsxindex 2c7e35a6..f09e6ba4 100644--- a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/FacebookParams.tsx+++ b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/FacebookParams.tsx@@ -1,24 +1,25 @@-import { ForwardedRef, forwardRef, memo, useEffect } from "react";-import {+import type { ForwardedRef } from 'react'+import type {IPlatsParamsProps,IPlatsParamsRef,-} from "@/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type";-import PubParmasTextarea from "@/components/PublishDialog/compoents/PubParmasTextarea";-import usePlatParamsCommon from "@/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon";-import styles from "../platParamsSetting.module.scss";-import { Radio } from "antd";-import { useTransClient } from "@/app/i18n/client";+} from '@/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type'+import { Radio } from 'antd'+import { forwardRef, memo, useEffect } from 'react'+import { useTransClient } from '@/app/i18n/client'+import usePlatParamsCommon from '@/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon'+import PubParmasTextarea from '@/components/PublishDialog/compoents/PubParmasTextarea'+import styles from '../platParamsSetting.module.scss'const FacebookParams = memo(forwardRef(({ pubItem }: IPlatsParamsProps, ref: ForwardedRef<IPlatsParamsRef>) => {- const { t } = useTransClient("publish");- const { pubParmasTextareaCommonParams, setOnePubParams } =- usePlatParamsCommon(pubItem);+ const { t } = useTransClient('publish')+ const { pubParmasTextareaCommonParams, setOnePubParams }+ = usePlatParamsCommon(pubItem)// 初始化Facebook参数useEffect(() => {- const option = pubItem.params.option;+ const option = pubItem.params.optionif (!option.facebook || !option.facebook.content_category) {setOnePubParams({@@ -26,35 +27,35 @@ const FacebookParams = memo(...option,facebook: {...option.facebook,- content_category: "post",+ content_category: 'post',},},},pubItem.account.id,- );+ )}- }, [pubItem.account.id, setOnePubParams]);+ }, [pubItem.account.id, setOnePubParams])return (<><PubParmasTextarea{...pubParmasTextareaCommonParams}- extend={+ extend={(<><divclassName={styles.commonTitleInput}- style={{ marginTop: "10px" }}+ style={{ marginTop: '10px' }}><div className="platParamsSetting-label">- {t("form.type")}+ {t('form.type')}</div><Radio.Groupvalue={- pubItem.params.option.facebook?.content_category ||- "video"+ pubItem.params.option.facebook?.content_category+ || 'video'}onChange={(e) => {- const option = pubItem.params.option;+ const option = pubItem.params.optionsetOnePubParams({option: {@@ -66,7 +67,7 @@ const FacebookParams = memo(},},pubItem.account.id,- );+ )}}><Radio value="post">Post</Radio>@@ -75,12 +76,12 @@ const FacebookParams = memo(</Radio.Group></div></>- }+ )}/></>- );+ )},),-);+)-export default FacebookParams;+export default FacebookParamsdiff --git a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/InstagramParams.tsx b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/InstagramParams.tsxindex dc2a4a74..92a286e7 100644--- a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/InstagramParams.tsx+++ b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/InstagramParams.tsx@@ -1,69 +1,70 @@-import { ForwardedRef, forwardRef, memo, useEffect } from "react";-import {+import type { ForwardedRef } from 'react'+import type {IPlatsParamsProps,IPlatsParamsRef,-} from "@/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type";-import PubParmasTextarea from "@/components/PublishDialog/compoents/PubParmasTextarea";-import usePlatParamsCommon from "@/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon";-import CommonTitleInput from "@/components/PublishDialog/compoents/PlatParamsSetting/common/CommonTitleInput";-import styles from "../platParamsSetting.module.scss";-import { Radio } from "antd";-import { useTransClient } from "@/app/i18n/client";+} from '@/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type'+import { Radio } from 'antd'+import { forwardRef, memo, useEffect } from 'react'+import { useTransClient } from '@/app/i18n/client'+import CommonTitleInput from '@/components/PublishDialog/compoents/PlatParamsSetting/common/CommonTitleInput'+import usePlatParamsCommon from '@/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon'+import PubParmasTextarea from '@/components/PublishDialog/compoents/PubParmasTextarea'+import styles from '../platParamsSetting.module.scss'const InstagramParams = memo(forwardRef(({ pubItem }: IPlatsParamsProps, ref: ForwardedRef<IPlatsParamsRef>) => {- const { t } = useTransClient("publish");- const { pubParmasTextareaCommonParams, setOnePubParams } =- usePlatParamsCommon(pubItem);+ const { t } = useTransClient('publish')+ const { pubParmasTextareaCommonParams, setOnePubParams }+ = usePlatParamsCommon(pubItem)// 初始化Instagram参数useEffect(() => {- const option = pubItem.params.option;- console.log("InstagramParams - Current option:", option);- console.log("InstagramParams - Current instagram:", option.instagram);+ const option = pubItem.params.option+ console.log('InstagramParams - Current option:', option)+ console.log('InstagramParams - Current instagram:', option.instagram)if (!option.instagram || !option.instagram.content_category) {- console.log("InstagramParams - Setting default instagram option");+ console.log('InstagramParams - Setting default instagram option')setOnePubParams({option: {...option,instagram: {...option.instagram,- content_category: "post",+ content_category: 'post',},},},pubItem.account.id,- );+ )}- }, [pubItem.account.id, setOnePubParams]);+ }, [pubItem.account.id, setOnePubParams])return (<><PubParmasTextarea{...pubParmasTextareaCommonParams}- extend={+ extend={(<><divclassName={styles.commonTitleInput}- style={{ marginTop: "10px" }}+ style={{ marginTop: '10px' }}><div className="platParamsSetting-label">- {t("form.type")}+ {t('form.type')}</div><Radio.Groupvalue={- pubItem.params.option.instagram?.content_category ||- "video"+ pubItem.params.option.instagram?.content_category+ || 'video'}onChange={(e) => {- const option = pubItem.params.option;+ const option = pubItem.params.optionconsole.log(- "InstagramParams - onChange:",+ 'InstagramParams - onChange:',e.target.value,- );+ )setOnePubParams({option: {@@ -75,7 +76,7 @@ const InstagramParams = memo(},},pubItem.account.id,- );+ )}}><Radio value="post">Post</Radio>@@ -84,12 +85,12 @@ const InstagramParams = memo(</Radio.Group></div></>- }+ )}/></>- );+ )},),-);+)-export default InstagramParams;\ No newline at end of file+export default InstagramParamsdiff --git a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/KwaiParams.tsx b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/KwaiParams.tsxindex 09d87265..d61cce4f 100644--- a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/KwaiParams.tsx+++ b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/KwaiParams.tsx@@ -1,23 +1,24 @@-import { ForwardedRef, forwardRef, memo } from "react";-import {+import type { ForwardedRef } from 'react'+import type {IPlatsParamsProps,IPlatsParamsRef,-} from "@/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type";-import PubParmasTextarea from "@/components/PublishDialog/compoents/PubParmasTextarea";-import usePlatParamsCommon from "@/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon";+} from '@/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type'+import { forwardRef, memo } from 'react'+import usePlatParamsCommon from '@/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon'+import PubParmasTextarea from '@/components/PublishDialog/compoents/PubParmasTextarea'const KwaiParams = memo(forwardRef(({ pubItem }: IPlatsParamsProps, ref: ForwardedRef<IPlatsParamsRef>) => {- const { pubParmasTextareaCommonParams } = usePlatParamsCommon(pubItem);+ const { pubParmasTextareaCommonParams } = usePlatParamsCommon(pubItem)return (<><PubParmasTextarea {...pubParmasTextareaCommonParams} /></>- );+ )},),-);+)-export default KwaiParams;+export default KwaiParamsdiff --git a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/PinterestParams.tsx b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/PinterestParams.tsxindex 72ba0f59..4c2a142a 100644--- a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/PinterestParams.tsx+++ b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/PinterestParams.tsx@@ -1,20 +1,21 @@-import { ForwardedRef, forwardRef, memo, useEffect, useState } from "react";-import {+import type { ForwardedRef } from 'react'+import type {IPlatsParamsProps,IPlatsParamsRef,-} from "@/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type";-import PubParmasTextarea from "@/components/PublishDialog/compoents/PubParmasTextarea";-import usePlatParamsCommon from "@/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon";-import CommonTitleInput from "@/components/PublishDialog/compoents/PlatParamsSetting/common/CommonTitleInput";-import { usePublishDialogData } from "@/components/PublishDialog/usePublishDialogData";-import { useShallow } from "zustand/react/shallow";-import styles from "../platParamsSetting.module.scss";-import { Button, Tooltip, Input, List, message } from "antd";-import { useTransClient } from "@/app/i18n/client";-import { PushpinOutlined, PlusOutlined, SearchOutlined } from "@ant-design/icons";-import { createPinterestBoardApi } from "@/api/pinterest";-import { useAccountStore } from "@/store/account";-import { PlatType } from "@/app/config/platConfig";+} from '@/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type'+import { PlusOutlined, PushpinOutlined, SearchOutlined } from '@ant-design/icons'+import { Button, Input, List, message, Tooltip } from 'antd'+import { forwardRef, memo, useEffect, useState } from 'react'+import { useShallow } from 'zustand/react/shallow'+import { createPinterestBoardApi } from '@/api/pinterest'+import { PlatType } from '@/app/config/platConfig'+import { useTransClient } from '@/app/i18n/client'+import CommonTitleInput from '@/components/PublishDialog/compoents/PlatParamsSetting/common/CommonTitleInput'+import usePlatParamsCommon from '@/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon'+import PubParmasTextarea from '@/components/PublishDialog/compoents/PubParmasTextarea'+import { usePublishDialogData } from '@/components/PublishDialog/usePublishDialogData'+import { useAccountStore } from '@/store/account'+import styles from '../platParamsSetting.module.scss'// 添加全局样式const tooltipStyles = `@@ -27,261 +28,269 @@ const tooltipStyles = `background-color: #ffffff !important;border: 1px solid #d9d9d9 !important;}-`;+`-const PinterestParams = memo(+const PinterestParams = memo(forwardRef(({ pubItem }: IPlatsParamsProps, ref: ForwardedRef<IPlatsParamsRef>) => {- const { t } = useTransClient("pinterest");- const { pubParmasTextareaCommonParams, setOnePubParams } =- usePlatParamsCommon(pubItem);- const { getPinterestBoards, pinterestBoards } =- usePublishDialogData(- useShallow((state) => ({+ const { t } = useTransClient('pinterest')+ const { pubParmasTextareaCommonParams, setOnePubParams }+ = usePlatParamsCommon(pubItem)+ const { getPinterestBoards, pinterestBoards }+ = usePublishDialogData(+ useShallow(state => ({getPinterestBoards: state.getPinterestBoards,pinterestBoards: state.pinterestBoards,})),- );+ )// 弹窗状态- const [boardTooltipVisible, setBoardTooltipVisible] = useState(false);- const [searchKeyword, setSearchKeyword] = useState("");- const [newBoardName, setNewBoardName] = useState("");- const [creatingBoard, setCreatingBoard] = useState(false);+ const [boardTooltipVisible, setBoardTooltipVisible] = useState(false)+ const [searchKeyword, setSearchKeyword] = useState('')+ const [newBoardName, setNewBoardName] = useState('')+ const [creatingBoard, setCreatingBoard] = useState(false)useEffect(() => {- getPinterestBoards(false, pubItem.account.id);- }, [getPinterestBoards, pubItem.account.id]);+ getPinterestBoards(false, pubItem.account.id)+ }, [getPinterestBoards, pubItem.account.id])// 添加样式到页面useEffect(() => {- const styleElement = document.createElement('style');- styleElement.textContent = tooltipStyles;- document.head.appendChild(styleElement);-+ const styleElement = document.createElement('style')+ styleElement.textContent = tooltipStyles+ document.head.appendChild(styleElement)+return () => {- document.head.removeChild(styleElement);- };- }, []);+ document.head.removeChild(styleElement)+ }+ }, [])// 初始化Pinterest参数useEffect(() => {- const option = pubItem.params.option;+ const option = pubItem.params.optionif (!option.pinterest) {- option.pinterest = {};+ option.pinterest = {}}setOnePubParams({option,},pubItem.account.id,- );- }, [pubItem.account.id]);+ )+ }, [pubItem.account.id])// 默认选择第一个BoarduseEffect(() => {if (pinterestBoards.length > 0 && !pubItem.params.option.pinterest?.boardId) {- const option = pubItem.params.option;+ const option = pubItem.params.optionif (!option.pinterest) {- option.pinterest = {};+ option.pinterest = {}}- option.pinterest.boardId = pinterestBoards[0].id;+ option.pinterest.boardId = pinterestBoards[0].idsetOnePubParams({option,},pubItem.account.id,- );+ )}- }, [pinterestBoards, pubItem.params.option.pinterest?.boardId, pubItem.account.id]);+ }, [pinterestBoards, pubItem.params.option.pinterest?.boardId, pubItem.account.id])// 获取当前选中的Board信息const selectedBoard = pinterestBoards.find(- board => board.id === pubItem.params.option.pinterest?.boardId- );+ board => board.id === pubItem.params.option.pinterest?.boardId,+ )// 过滤Board列表- const filteredBoards = pinterestBoards.filter(board =>- board.name.toLowerCase().includes(searchKeyword.toLowerCase())- );+ const filteredBoards = pinterestBoards.filter(board =>+ board.name.toLowerCase().includes(searchKeyword.toLowerCase()),+ )// 创建新Boardconst handleCreateBoard = async () => {if (!newBoardName.trim()) {- message.error(t("validation.boardNameRequired"));- return;+ message.error(t('validation.boardNameRequired'))+ return}const pinterestAccount = useAccountStore.getState()- .accountList.find((v) => v.type === PlatType.Pinterest);+ .accountList+ .find(v => v.type === PlatType.Pinterest)if (!pinterestAccount) {- message.error(t("messages.noAccountFound"));- return;+ message.error(t('messages.noAccountFound'))+ return}try {- setCreatingBoard(true);+ setCreatingBoard(true)const response = await createPinterestBoardApi(- { name: newBoardName.trim() },- pinterestAccount.id- );-+ { name: newBoardName.trim() },+ pinterestAccount.id,+ )+if (response?.code === 0) {- message.success(t("messages.boardCreateSuccess"));- setNewBoardName("");+ message.success(t('messages.boardCreateSuccess'))+ setNewBoardName('')// 重新获取Board列表- await getPinterestBoards(true, pubItem.account.id);- } else {- message.error(t("messages.boardCreateFailed"));+ await getPinterestBoards(true, pubItem.account.id)+ }+ else {+ message.error(t('messages.boardCreateFailed'))}- } catch (error) {- message.error(t("messages.boardCreateFailed"));- } finally {- setCreatingBoard(false);}- };+ catch (error) {+ message.error(t('messages.boardCreateFailed'))+ }+ finally {+ setCreatingBoard(false)+ }+ }-- // 选择Board- const handleSelectBoard = (boardId: string) => {- const option = pubItem.params.option;- if (!option.pinterest) {- option.pinterest = {};- }- option.pinterest.boardId = boardId;- setOnePubParams(- {- option,- },- pubItem.account.id,- );- setBoardTooltipVisible(false);- setSearchKeyword("");- };+ // 选择Board+ const handleSelectBoard = (boardId: string) => {+ const option = pubItem.params.option+ if (!option.pinterest) {+ option.pinterest = {}+ }+ option.pinterest.boardId = boardId+ setOnePubParams(+ {+ option,+ },+ pubItem.account.id,+ )+ setBoardTooltipVisible(false)+ setSearchKeyword('')+ }return (<><PubParmasTextarea{...pubParmasTextareaCommonParams}- extend={+ extend={(<><CommonTitleInput pubItem={pubItem} /><divclassName={`${styles.commonTitleInput} ${styles.tooltipOverride}`}- style={{ marginTop: "10px" }}+ style={{ marginTop: '10px' }}><div className="platParamsSetting-label">- {t("pin.selectBoard")}- <span style={{ color: "#ff4d4f", marginLeft: "4px" }}>*</span>+ {t('pin.selectBoard')}+ <span style={{ color: '#ff4d4f', marginLeft: '4px' }}>*</span></div>- <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><Buttonicon={<PushpinOutlined />}- style={{- border: "none"+ style={{+ border: 'none',}}>- {selectedBoard?.name || t("pin.selectBoardPlaceholder")}+ {selectedBoard?.name || t('pin.selectBoardPlaceholder')}</Button>- <Tooltip- title={- <div style={{ maxHeight: "400px", overflow: "auto", background: "#ffffff" }}>- <div style={{ marginBottom: "1px" }}>- <Input- placeholder={t("actions.search")}- prefix={<SearchOutlined />}- value={searchKeyword}- onChange={(e) => setSearchKeyword(e.target.value)}- size="small"- style={{ marginBottom: "12px" }}- />- </div>-- {/* Board列表 */}- <List- dataSource={filteredBoards}+ <Tooltip+ title={(+ <div style={{ maxHeight: '400px', overflow: 'auto', background: '#ffffff' }}>+ <div style={{ marginBottom: '1px' }}>+ <Input+ placeholder={t('actions.search')}+ prefix={<SearchOutlined />}+ value={searchKeyword}+ onChange={e => setSearchKeyword(e.target.value)}size="small"- style={{ maxHeight: "200px", overflow: "auto" }}- renderItem={(board) => (- <List.Item- style={{- cursor: "pointer",- padding: "6px 8px",- borderRadius: "4px",- backgroundColor: board.id === pubItem.params.option.pinterest?.boardId ? "#f0f0f0" : "transparent"- }}- onClick={() => handleSelectBoard(board.id)}- >- <div style={{ display: "flex", alignItems: "center", gap: "6px" }}>- <PushpinOutlined style={{ fontSize: "12px" }} />- <span style={{ fontSize: "12px" }}>{board.name}</span>- {board.id === pubItem.params.option.pinterest?.boardId && (- <span style={{ color: "#1890ff", fontSize: "10px" }}>({t("badges.selected")})</span>- )}- </div>- </List.Item>- )}- locale={{- emptyText: t("empty.noBoards")- }}+ style={{ marginBottom: '12px' }}/>-- {/* 创建新Board */}- <div style={{- border: "1px solid #d9d9d9",- borderRadius: "4px",- padding: "8px",- marginTop: "12px"- }}>+ </div>++ {/* Board列表 */}+ <List+ dataSource={filteredBoards}+ size="small"+ style={{ maxHeight: '200px', overflow: 'auto' }}+ renderItem={board => (+ <List.Item+ style={{+ cursor: 'pointer',+ padding: '6px 8px',+ borderRadius: '4px',+ backgroundColor: board.id === pubItem.params.option.pinterest?.boardId ? '#f0f0f0' : 'transparent',+ }}+ onClick={() => handleSelectBoard(board.id)}+ >+ <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>+ <PushpinOutlined style={{ fontSize: '12px' }} />+ <span style={{ fontSize: '12px' }}>{board.name}</span>+ {board.id === pubItem.params.option.pinterest?.boardId && (+ <span style={{ color: '#1890ff', fontSize: '10px' }}>+ (+ {t('badges.selected')}+ )+ </span>+ )}+ </div>+ </List.Item>+ )}+ locale={{+ emptyText: t('empty.noBoards'),+ }}+ />- <div style={{ display: "flex", gap: "6px" }}>- <Input- placeholder={t("board.namePlaceholder")}- value={newBoardName}- onChange={(e) => setNewBoardName(e.target.value)}- onPressEnter={handleCreateBoard}- size="small"- />- <Button- type="primary"- icon={<PlusOutlined />}- onClick={handleCreateBoard}- loading={creatingBoard}- size="small"- >- {t("board.createButton")}- </Button>- </div>+ {/* 创建新Board */}+ <div style={{+ border: '1px solid #d9d9d9',+ borderRadius: '4px',+ padding: '8px',+ marginTop: '12px',+ }}+ >++ <div style={{ display: 'flex', gap: '6px' }}>+ <Input+ placeholder={t('board.namePlaceholder')}+ value={newBoardName}+ onChange={e => setNewBoardName(e.target.value)}+ onPressEnter={handleCreateBoard}+ size="small"+ />+ <Button+ type="primary"+ icon={<PlusOutlined />}+ onClick={handleCreateBoard}+ loading={creatingBoard}+ size="small"+ >+ {t('board.createButton')}+ </Button></div></div>- }- open={boardTooltipVisible}- onOpenChange={setBoardTooltipVisible}- placement="top"- trigger="click"- >- <Button- onClick={() => setBoardTooltipVisible(!boardTooltipVisible)}- style={{- backgroundColor: "#f5f5f5",- border: "none",- color: "#666"- }}- >- {t("actions.change")}- </Button>- </Tooltip>+ </div>+ )}+ open={boardTooltipVisible}+ onOpenChange={setBoardTooltipVisible}+ placement="top"+ trigger="click"+ >+ <Button+ onClick={() => setBoardTooltipVisible(!boardTooltipVisible)}+ style={{+ backgroundColor: '#f5f5f5',+ border: 'none',+ color: '#666',+ }}+ >+ {t('actions.change')}+ </Button>+ </Tooltip></div></div></>- }- />+ )}+ /></>- );+ )},),-);+)-export default PinterestParams;+export default PinterestParamsdiff --git a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/ThreadsParams.tsx b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/ThreadsParams.tsxindex cb8a7a1d..5d64c74f 100644--- a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/ThreadsParams.tsx+++ b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/ThreadsParams.tsx@@ -1,34 +1,36 @@-import { ForwardedRef, forwardRef, memo, useEffect, useState, useCallback, useRef } from "react";-import {+import type { ForwardedRef } from 'react'+import type { ThreadsLocationItem } from '@/api/plat/threads'+import type {IPlatsParamsProps,IPlatsParamsRef,-} from "@/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type";-import PubParmasTextarea from "@/components/PublishDialog/compoents/PubParmasTextarea";-import usePlatParamsCommon from "@/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon";+} from '@/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type'+import { Input, Select } from 'antd'+import { debounce } from 'lodash'+import { forwardRef, memo, useCallback, useEffect, useRef, useState } from 'react'+import { apiGetThreadsLocations } from '@/api/plat/threads'+import { useTransClient } from '@/app/i18n/client'+import usePlatParamsCommon from '@/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon'+import PubParmasTextarea from '@/components/PublishDialog/compoents/PubParmasTextarea'// 去掉标题输入-import styles from "../platParamsSetting.module.scss";-import { Select, Input } from "antd";-import { useTransClient } from "@/app/i18n/client";-import { apiGetThreadsLocations, ThreadsLocationItem } from "@/api/plat/threads";-import { debounce } from "lodash";+import styles from '../platParamsSetting.module.scss'-const { Search } = Input;+const { Search } = Inputconst ThreadsParams = memo(forwardRef(({ pubItem }: IPlatsParamsProps, ref: ForwardedRef<IPlatsParamsRef>) => {- const { t } = useTransClient("publish");- const { pubParmasTextareaCommonParams, setOnePubParams } =- usePlatParamsCommon(pubItem);+ const { t } = useTransClient('publish')+ const { pubParmasTextareaCommonParams, setOnePubParams }+ = usePlatParamsCommon(pubItem)- const [locations, setLocations] = useState<ThreadsLocationItem[]>([]);- const [loading, setLoading] = useState(false);- const [searchKeyword, setSearchKeyword] = useState("");- const debouncedSearchRef = useRef<ReturnType<typeof debounce> | null>(null);+ const [locations, setLocations] = useState<ThreadsLocationItem[]>([])+ const [loading, setLoading] = useState(false)+ const [searchKeyword, setSearchKeyword] = useState('')+ const debouncedSearchRef = useRef<ReturnType<typeof debounce> | null>(null)// 初始化Threads参数useEffect(() => {- const option = pubItem.params.option;+ const option = pubItem.params.optionif (!option.threads) {setOnePubParams({@@ -39,70 +41,72 @@ const ThreadsParams = memo(},},pubItem.account.id,- );+ )}- }, [pubItem.account.id, setOnePubParams]);+ }, [pubItem.account.id, setOnePubParams])// 获取位置列表const fetchLocations = useCallback(async (keyword?: string) => {if (!keyword) {- return;+ return}try {- setLoading(true);- const response:any = await apiGetThreadsLocations(+ setLoading(true)+ const response: any = await apiGetThreadsLocations(pubItem.account.id,- keyword || ""- );+ keyword || '',+ )console.log('response', response)if (response && response.code === 0) {- setLocations(response.data);+ setLocations(response.data)}- } catch (error) {- console.error("获取Threads位置列表失败:", error);- } finally {- setLoading(false);}- }, [pubItem.account.id]);+ catch (error) {+ console.error('获取Threads位置列表失败:', error)+ }+ finally {+ setLoading(false)+ }+ }, [pubItem.account.id])// 创建防抖搜索函数useEffect(() => {debouncedSearchRef.current = debounce((keyword: string) => {- fetchLocations(keyword);- }, 500); // 增加防抖延迟到500ms+ fetchLocations(keyword)+ }, 500) // 增加防抖延迟到500ms// 清理函数return () => {if (debouncedSearchRef.current) {- debouncedSearchRef.current.cancel();+ debouncedSearchRef.current.cancel()}- };- }, [fetchLocations]);+ }+ }, [fetchLocations])// 初始加载位置列表useEffect(() => {- fetchLocations();- }, [fetchLocations]);+ fetchLocations()+ }, [fetchLocations])// 处理位置选择const handleLocationChange = (locationId: string) => {-- const selectedLocation = locations.find(loc => loc.id === locationId);- const option = pubItem.params.option;-+ const selectedLocation = locations.find(loc => loc.id === locationId)+ const option = pubItem.params.option+// 构建 threads 对象,如果没有选择位置则不包含 location_idconst threadsOption = {...option.threads,- };-+ }+if (selectedLocation?.id) {- threadsOption.location_id = selectedLocation.id;- } else {+ threadsOption.location_id = selectedLocation.id+ }+ else {// 如果没有选择位置,删除 location_id 属性- delete threadsOption.location_id;+ delete threadsOption.location_id}-+setOnePubParams({option: {@@ -111,40 +115,40 @@ const ThreadsParams = memo(},},pubItem.account.id,- );- };+ )+ }// 处理搜索const handleSearch = useCallback((value: string) => {- setSearchKeyword(value);+ setSearchKeyword(value)if (debouncedSearchRef.current) {- debouncedSearchRef.current(value);+ debouncedSearchRef.current(value)}- }, []);+ }, [])return (<><PubParmasTextarea{...pubParmasTextareaCommonParams}- extend={+ extend={(<><divclassName={styles.commonTitleInput}- style={{ marginTop: "10px" }}+ style={{ marginTop: '10px' }}><div className="platParamsSetting-label">- {t("form.location" as any)}+ {t('form.location' as any)}</div><Select- placeholder={t("form.selectLocation" as any)}+ placeholder={t('form.selectLocation' as any)}value={pubItem.params.option.threads?.location_id || undefined}onChange={handleLocationChange}loading={loading}- style={{ width: "100%" }}+ style={{ width: '100%' }}showSearchfilterOption={false}- onSearch={(val) => handleSearch(val)}- options={locations.map((location) => ({+ onSearch={val => handleSearch(val)}+ options={locations.map(location => ({value: location.id,label: location.label,}))}@@ -152,12 +156,12 @@ const ThreadsParams = memo(/></div></>- }+ )}/></>- );+ )},),-);+)-export default ThreadsParams;+export default ThreadsParamsdiff --git a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/TikTokParams.tsx b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/TikTokParams.tsxindex 6bc236b6..bcc6f183 100644--- a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/TikTokParams.tsx+++ b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/TikTokParams.tsx@@ -1,56 +1,59 @@-import { ForwardedRef, forwardRef, memo, useEffect, useState } from "react";-import {+import type { ForwardedRef } from 'react'+import type {IPlatsParamsProps,IPlatsParamsRef,-} from "@/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type";-import PubParmasTextarea from "@/components/PublishDialog/compoents/PubParmasTextarea";-import usePlatParamsCommon from "@/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon";-import CommonTitleInput from "@/components/PublishDialog/compoents/PlatParamsSetting/common/CommonTitleInput";-import styles from "../platParamsSetting.module.scss";-import { Select, Checkbox, Switch, Alert } from "antd";-import { useTransClient } from "@/app/i18n/client";-import http from "@/utils/request";+} from '@/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type'+import { Alert, Checkbox, Select, Switch } from 'antd'+import { forwardRef, memo, useEffect, useState } from 'react'+import { useTransClient } from '@/app/i18n/client'+import CommonTitleInput from '@/components/PublishDialog/compoents/PlatParamsSetting/common/CommonTitleInput'+import usePlatParamsCommon from '@/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon'+import PubParmasTextarea from '@/components/PublishDialog/compoents/PubParmasTextarea'+import http from '@/utils/request'+import styles from '../platParamsSetting.module.scss'// TikTok Creator Info 接口类型interface TikTokCreatorInfo {- max_video_post_duration_sec: number;- privacy_level_options: string[];- stitch_disabled: boolean;- comment_disabled: boolean;- creator_avatar_url: string;- creator_nickname: string;- creator_username: string;- duet_disabled: boolean;+ max_video_post_duration_sec: number+ privacy_level_options: string[]+ stitch_disabled: boolean+ comment_disabled: boolean+ creator_avatar_url: string+ creator_nickname: string+ creator_username: string+ duet_disabled: boolean}const TikTokParams = memo(forwardRef(({ pubItem }: IPlatsParamsProps, ref: ForwardedRef<IPlatsParamsRef>) => {- const { t } = useTransClient("publish");- const { pubParmasTextareaCommonParams, setOnePubParams } =- usePlatParamsCommon(pubItem);-- const [creatorInfo, setCreatorInfo] = useState<TikTokCreatorInfo | null>(null);- const [loading, setLoading] = useState(false);+ const { t } = useTransClient('publish')+ const { pubParmasTextareaCommonParams, setOnePubParams }+ = usePlatParamsCommon(pubItem)++ const [creatorInfo, setCreatorInfo] = useState<TikTokCreatorInfo | null>(null)+ const [loading, setLoading] = useState(false)// 获取 TikTok Creator Infoconst fetchCreatorInfo = async () => {try {- setLoading(true);- const response = await http.get<TikTokCreatorInfo>(`plat/tiktok/creator/info/${pubItem.account.id}`);+ setLoading(true)+ const response = await http.get<TikTokCreatorInfo>(`plat/tiktok/creator/info/${pubItem.account.id}`)if (response && response.code === 0) {- setCreatorInfo(response.data as TikTokCreatorInfo);+ setCreatorInfo(response.data as TikTokCreatorInfo)}- } catch (error) {- console.error('Failed to fetch TikTok creator info:', error);- } finally {- setLoading(false);}- };+ catch (error) {+ console.error('Failed to fetch TikTok creator info:', error)+ }+ finally {+ setLoading(false)+ }+ }// 初始化 TikTok 参数useEffect(() => {- const option = pubItem.params.option;+ const option = pubItem.params.optionif (!option.tiktok) {option.tiktok = {privacy_level: '',@@ -59,162 +62,171 @@ const TikTokParams = memo(stitch_disabled: false,brand_organic_toggle: false,brand_content_toggle: false,- };- console.log('Initializing TikTok options:', option.tiktok);- setOnePubParams({ option }, pubItem.account.id);- } else {- console.log('TikTok options already exist:', option.tiktok);+ }+ console.log('Initializing TikTok options:', option.tiktok)+ setOnePubParams({ option }, pubItem.account.id)+ }+ else {+ console.log('TikTok options already exist:', option.tiktok)}- fetchCreatorInfo();- }, [pubItem.account.id, pubItem.account.account]);+ fetchCreatorInfo()+ }, [pubItem.account.id, pubItem.account.account])// 隐私级别选项映射const getPrivacyLevelLabel = (value: string) => {switch (value) {case 'PUBLIC_TO_EVERYONE':- return t('tiktok.privacy.public' as any);+ return t('tiktok.privacy.public' as any)case 'MUTUAL_FOLLOW_FRIENDS':- return t('tiktok.privacy.friends' as any);+ return t('tiktok.privacy.friends' as any)case 'SELF_ONLY':- return t('tiktok.privacy.private' as any);+ return t('tiktok.privacy.private' as any)default:- return value;+ return value}- };+ }// 获取合规声明文本和链接const getComplianceContent = () => {- const { brand_organic_toggle, brand_content_toggle } = pubItem.params.option.tiktok || {};-+ const { brand_organic_toggle, brand_content_toggle } = pubItem.params.option.tiktok || {}+// 根据选择确定链接- const linkUrl = brand_content_toggle+ const linkUrl = brand_content_toggle? 'https://www.tiktok.com/legal/page/global/bc-policy/en'- : 'https://www.tiktok.com/legal/page/global/music-usage-confirmation/en';-+ : 'https://www.tiktok.com/legal/page/global/music-usage-confirmation/en'+// 根据选择确定文本- let text = '';+ let text = ''if (brand_organic_toggle && brand_content_toggle) {- text = t('tiktok.compliance.both' as any);- } else if (brand_content_toggle) {- text = t('tiktok.compliance.branded' as any);- } else if (brand_organic_toggle) {- text = t('tiktok.compliance.organic' as any);- } else {- text = t('tiktok.compliance.default' as any);+ text = t('tiktok.compliance.both' as any)+ }+ else if (brand_content_toggle) {+ text = t('tiktok.compliance.branded' as any)+ }+ else if (brand_organic_toggle) {+ text = t('tiktok.compliance.organic' as any)}-+ else {+ text = t('tiktok.compliance.default' as any)+ }+// 返回整个文本作为可点击的链接return (// <></>- <a- href={linkUrl}- target="_blank"+ <a+ href={linkUrl}+ target="_blank"rel="noopener noreferrer"- style={{- color: '#1890ff',+ style={{+ color: '#1890ff',textDecoration: 'underline',cursor: 'pointer',display: 'block',- width: '100%'+ width: '100%',}}>{text}</a>- );- };+ )+ }return (<><PubParmasTextarea{...pubParmasTextareaCommonParams}- extend={+ extend={(<>{/* Creator Info Display */}{creatorInfo && (- <div className={styles.commonTitleInput} style={{ marginTop: "10px" }}>- <div className="platParamsSetting-label">{t('tiktok.creatorInfo' as any)}</div>- <div style={{- display: 'flex',- alignItems: 'center',+ <div className={styles.commonTitleInput} style={{ marginTop: '10px' }}>+ <div className="platParamsSetting-label">{t('tiktok.creatorInfo' as any)}</div>+ <div style={{+ display: 'flex',+ alignItems: 'center',gap: '8px',padding: '8px',- borderRadius: '4px'- }}>- <img- src={creatorInfo.creator_avatar_url}+ borderRadius: '4px',+ }}+ >+ <img+ src={creatorInfo.creator_avatar_url}alt="Creator Avatar"style={{ width: '32px', height: '32px', borderRadius: '50%' }}/><span style={{ fontWeight: 500 }}>{creatorInfo.creator_nickname}</span>- <span style={{ color: '#666' }}>(@{creatorInfo.creator_username})</span>+ <span style={{ color: '#666' }}>+ (@+ {creatorInfo.creator_username}+ )+ </span></div></div>)}{/* Privacy Level Selection */}{creatorInfo && (- <div className={styles.commonTitleInput} style={{ marginTop: "10px" }}>- <div className="platParamsSetting-label">{t('tiktok.privacy.title' as any)}</div>+ <div className={styles.commonTitleInput} style={{ marginTop: '10px' }}>+ <div className="platParamsSetting-label">{t('tiktok.privacy.title' as any)}</div><Select- style={{ width: "100%", marginLeft: '3px' }}+ style={{ width: '100%', marginLeft: '3px' }}value={pubItem.params.option.tiktok?.privacy_level}onChange={(value) => {- const option = pubItem.params.option;- option.tiktok!.privacy_level = value;- setOnePubParams({ option }, pubItem.account.id);+ const option = pubItem.params.option+ option.tiktok!.privacy_level = value+ setOnePubParams({ option }, pubItem.account.id)}}- placeholder={t('tiktok.privacy.placeholder' as any)}+ placeholder={t('tiktok.privacy.placeholder' as any)}options={creatorInfo.privacy_level_options.map(level => ({value: level,- label: getPrivacyLevelLabel(level)+ label: getPrivacyLevelLabel(level),}))}/></div>)}{/* Allow users to interact */}- <div className={styles.commonTitleInput} style={{ marginTop: "10px" }}>- <div className="platParamsSetting-label">{t('tiktok.interactions.title' as any)}</div>+ <div className={styles.commonTitleInput} style={{ marginTop: '10px' }}>+ <div className="platParamsSetting-label">{t('tiktok.interactions.title' as any)}</div><div style={{ display: 'flex', flexDirection: 'row', gap: '8px', marginLeft: '3px' }}><Checkboxchecked={!pubItem.params.option.tiktok?.comment_disabled}disabled={creatorInfo?.comment_disabled}onChange={(e) => {- const option = pubItem.params.option;- option.tiktok!.comment_disabled = !e.target.checked;- setOnePubParams({ option }, pubItem.account.id);+ const option = pubItem.params.option+ option.tiktok!.comment_disabled = !e.target.checked+ setOnePubParams({ option }, pubItem.account.id)}}>- {t('tiktok.interactions.comment' as any)}+ {t('tiktok.interactions.comment' as any)}</Checkbox><Checkboxchecked={!pubItem.params.option.tiktok?.duet_disabled}disabled={creatorInfo?.duet_disabled}onChange={(e) => {- const option = pubItem.params.option;- option.tiktok!.duet_disabled = !e.target.checked;- setOnePubParams({ option }, pubItem.account.id);+ const option = pubItem.params.option+ option.tiktok!.duet_disabled = !e.target.checked+ setOnePubParams({ option }, pubItem.account.id)}}>- {t('tiktok.interactions.duet' as any)}+ {t('tiktok.interactions.duet' as any)}</Checkbox><Checkboxchecked={!pubItem.params.option.tiktok?.stitch_disabled}disabled={creatorInfo?.stitch_disabled}onChange={(e) => {- const option = pubItem.params.option;- option.tiktok!.stitch_disabled = !e.target.checked;- setOnePubParams({ option }, pubItem.account.id);+ const option = pubItem.params.option+ option.tiktok!.stitch_disabled = !e.target.checked+ setOnePubParams({ option }, pubItem.account.id)}}>- {t('tiktok.interactions.stitch' as any)}+ {t('tiktok.interactions.stitch' as any)}</Checkbox></div></div>{/* Commercial Content Disclosure */}- <div className={styles.commonTitleInput} style={{ marginTop: "10px" }}>- <div className="platParamsSetting-label">{t('tiktok.commercial.title' as any)}</div>+ <div className={styles.commonTitleInput} style={{ marginTop: '10px' }}>+ <div className="platParamsSetting-label">{t('tiktok.commercial.title' as any)}</div><div style={{ marginBottom: '0px' }}>{/* <div style={{ fontSize: '12px', color: '#666', marginBottom: '4px' }}>当前状态: {JSON.stringify({@@ -228,8 +240,8 @@ const TikTokParams = memo(size="small"style={{ marginTop: '2px', marginLeft: '3px' }}onChange={(checked) => {- console.log('TikTok Switch changed:', checked);- const option = { ...pubItem.params.option };+ console.log('TikTok Switch changed:', checked)+ const option = { ...pubItem.params.option }if (!option.tiktok) {option.tiktok = {privacy_level: '',@@ -238,91 +250,92 @@ const TikTokParams = memo(stitch_disabled: false,brand_organic_toggle: false,brand_content_toggle: false,- };+ }}-+if (!checked) {// 关闭时,清空所有商业内容选项- option.tiktok.brand_organic_toggle = false;- option.tiktok.brand_content_toggle = false;- } else {+ option.tiktok.brand_organic_toggle = false+ option.tiktok.brand_content_toggle = false+ }+ else {// 开启时,默认选择"您的品牌"选项- option.tiktok.brand_organic_toggle = true;- option.tiktok.brand_content_toggle = false;+ option.tiktok.brand_organic_toggle = true+ option.tiktok.brand_content_toggle = false}- console.log('TikTok options after change:', option.tiktok);- setOnePubParams({ option }, pubItem.account.id);+ console.log('TikTok options after change:', option.tiktok)+ setOnePubParams({ option }, pubItem.account.id)}}/>- <span style={{ marginLeft: '8px', fontSize: '11px' }}>{t('tiktok.commercial.toggle' as any)}</span>+ <span style={{ marginLeft: '8px', fontSize: '11px' }}>{t('tiktok.commercial.toggle' as any)}</span></div>--+</div>{(pubItem.params.option.tiktok?.brand_organic_toggle || pubItem.params.option.tiktok?.brand_content_toggle) && (- <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', marginTop: '8px', fontSize: '12px' }}>- <Checkbox- checked={pubItem.params.option.tiktok?.brand_organic_toggle}- onChange={(e) => {- const option = { ...pubItem.params.option };- if (!option.tiktok) {- option.tiktok = {- privacy_level: '',- comment_disabled: false,- duet_disabled: false,- stitch_disabled: false,- brand_organic_toggle: false,- brand_content_toggle: false,- };+ <div style={{ display: 'flex', flexDirection: 'column', gap: '8px', marginTop: '8px', fontSize: '12px' }}>+ <Checkbox+ checked={pubItem.params.option.tiktok?.brand_organic_toggle}+ onChange={(e) => {+ const option = { ...pubItem.params.option }+ if (!option.tiktok) {+ option.tiktok = {+ privacy_level: '',+ comment_disabled: false,+ duet_disabled: false,+ stitch_disabled: false,+ brand_organic_toggle: false,+ brand_content_toggle: false,}- option.tiktok.brand_organic_toggle = e.target.checked;- setOnePubParams({ option }, pubItem.account.id);- }}- >- {t('tiktok.commercial.yourBrand' as any)}- </Checkbox>- <Checkbox- checked={pubItem.params.option.tiktok?.brand_content_toggle}- onChange={(e) => {- const option = { ...pubItem.params.option };- if (!option.tiktok) {- option.tiktok = {- privacy_level: '',- comment_disabled: false,- duet_disabled: false,- stitch_disabled: false,- brand_organic_toggle: false,- brand_content_toggle: false,- };+ }+ option.tiktok.brand_organic_toggle = e.target.checked+ setOnePubParams({ option }, pubItem.account.id)+ }}+ >+ {t('tiktok.commercial.yourBrand' as any)}+ </Checkbox>+ <Checkbox+ checked={pubItem.params.option.tiktok?.brand_content_toggle}+ onChange={(e) => {+ const option = { ...pubItem.params.option }+ if (!option.tiktok) {+ option.tiktok = {+ privacy_level: '',+ comment_disabled: false,+ duet_disabled: false,+ stitch_disabled: false,+ brand_organic_toggle: false,+ brand_content_toggle: false,}- option.tiktok.brand_content_toggle = e.target.checked;- setOnePubParams({ option }, pubItem.account.id);- }}- >- {t('tiktok.commercial.brandedContent' as any)} 11- </Checkbox>+ }+ option.tiktok.brand_content_toggle = e.target.checked+ setOnePubParams({ option }, pubItem.account.id)+ }}+ >+ {t('tiktok.commercial.brandedContent' as any)}+ {' '}+ 11+ </Checkbox>- {/* Compliance Declaration */}- <div className={styles.commonTitleInput} style={{ marginTop: "10px" }}>- <Alert- description={getComplianceContent()}- type="info"- showIcon- style={{ fontSize: '12px', padding: '3px 6px' }}- />- </div>+ {/* Compliance Declaration */}+ <div className={styles.commonTitleInput} style={{ marginTop: '10px' }}>+ <Alert+ description={getComplianceContent()}+ type="info"+ showIcon+ style={{ fontSize: '12px', padding: '3px 6px' }}+ /></div>- )}+ </div>+ )}-</>- }+ )}/></>- );+ )},),-);+)-export default TikTokParams;+export default TikTokParamsdiff --git a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/WxGzhParams.tsx b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/WxGzhParams.tsxindex 96ea8150..14b97e75 100644--- a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/WxGzhParams.tsx+++ b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/WxGzhParams.tsx@@ -1,10 +1,11 @@-import { ForwardedRef, forwardRef, memo, useEffect } from "react";-import { IPlatsParamsProps, IPlatsParamsRef } from "@/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type";-import PubParmasTextarea from "@/components/PublishDialog/compoents/PubParmasTextarea";-import usePlatParamsCommon from "@/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon";-import styles from "../platParamsSetting.module.scss";-import { Input } from "antd";-import { useTransClient } from "@/app/i18n/client";+import type { ForwardedRef } from 'react'+import type { IPlatsParamsProps, IPlatsParamsRef } from '@/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type'+import { Input } from 'antd'+import { forwardRef, memo, useEffect } from 'react'+import { useTransClient } from '@/app/i18n/client'+import usePlatParamsCommon from '@/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon'+import PubParmasTextarea from '@/components/PublishDialog/compoents/PubParmasTextarea'+import styles from '../platParamsSetting.module.scss'/*** 微信公众号平台参数@@ -12,8 +13,8 @@ import { useTransClient } from "@/app/i18n/client";*/const WxGzhParams = memo(forwardRef(({ pubItem }: IPlatsParamsProps, ref: ForwardedRef<IPlatsParamsRef>) => {- const { t } = useTransClient("publish");- const { pubParmasTextareaCommonParams, setOnePubParams } = usePlatParamsCommon(pubItem);+ const { t } = useTransClient('publish')+ const { pubParmasTextareaCommonParams, setOnePubParams } = usePlatParamsCommon(pubItem)// 初始化 wxGzh 参数对象// useEffect(() => {@@ -29,24 +30,24 @@ const WxGzhParams = memo(<><PubParmasTextarea{...pubParmasTextareaCommonParams}- extend={<>- <div className={styles.commonTitleInput} style={{ marginTop: "10px" }}>- <div className="platParamsSetting-label">{t("form.title")}</div>- <Input- value={pubItem.params.title}- placeholder={t("form.titlePlaceholder")}- onChange={(e) => {- setOnePubParams({ title: e.target.value }, pubItem.account.id);- }}- />- </div>- </>}+ extend={(+ <>+ <div className={styles.commonTitleInput} style={{ marginTop: '10px' }}>+ <div className="platParamsSetting-label">{t('form.title')}</div>+ <Input+ value={pubItem.params.title}+ placeholder={t('form.titlePlaceholder')}+ onChange={(e) => {+ setOnePubParams({ title: e.target.value }, pubItem.account.id)+ }}+ />+ </div>+ </>+ )}/></>- );- })-);--export default WxGzhParams;-+ )+ }),+)+export default WxGzhParamsdiff --git a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/YouTubeParams.tsx b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/YouTubeParams.tsxindex b8222be1..a2006bf8 100644--- a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/YouTubeParams.tsx+++ b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/YouTubeParams.tsx@@ -1,82 +1,83 @@-import { ForwardedRef, forwardRef, memo, useEffect } from "react";-import {+import type { ForwardedRef } from 'react'+import type {IPlatsParamsProps,IPlatsParamsRef,-} from "@/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type";-import PubParmasTextarea from "@/components/PublishDialog/compoents/PubParmasTextarea";-import usePlatParamsCommon from "@/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon";-import CommonTitleInput from "@/components/PublishDialog/compoents/PlatParamsSetting/common/CommonTitleInput";-import { usePublishDialogData } from "@/components/PublishDialog/usePublishDialogData";-import { useShallow } from "zustand/react/shallow";-import styles from "../platParamsSetting.module.scss";-import { Radio, Select, Checkbox } from "antd";-import { YouTubeCategoryItem } from "@/components/PublishDialog/publishDialog.type";-import { useTransClient } from "@/app/i18n/client";+} from '@/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type'+import { Checkbox, Radio, Select } from 'antd'+import { forwardRef, memo, useEffect } from 'react'+import { useShallow } from 'zustand/react/shallow'+import { useTransClient } from '@/app/i18n/client'+import CommonTitleInput from '@/components/PublishDialog/compoents/PlatParamsSetting/common/CommonTitleInput'+import usePlatParamsCommon from '@/components/PublishDialog/compoents/PlatParamsSetting/hooks/usePlatParamsCoomon'+import PubParmasTextarea from '@/components/PublishDialog/compoents/PubParmasTextarea'+import { YouTubeCategoryItem } from '@/components/PublishDialog/publishDialog.type'+import { usePublishDialogData } from '@/components/PublishDialog/usePublishDialogData'+import styles from '../platParamsSetting.module.scss'const YouTubeParams = memo(forwardRef(({ pubItem }: IPlatsParamsProps, ref: ForwardedRef<IPlatsParamsRef>) => {- const { t } = useTransClient("publish");- const { pubParmasTextareaCommonParams, setOnePubParams } =- usePlatParamsCommon(pubItem);+ const { t } = useTransClient('publish')+ const { pubParmasTextareaCommonParams, setOnePubParams }+ = usePlatParamsCommon(pubItem)const {getYouTubeCategories,- youTubeCategories+ youTubeCategories,} = usePublishDialogData(- useShallow((state) => ({+ useShallow(state => ({getYouTubeCategories: state.getYouTubeCategories,youTubeCategories: state.youTubeCategories,})),- );+ )useEffect(() => {- getYouTubeCategories(pubItem.account.id);- }, [getYouTubeCategories, pubItem.account.id]);+ getYouTubeCategories(pubItem.account.id)+ }, [getYouTubeCategories, pubItem.account.id])// 当获取到视频分类列表后,默认选中第一个分类useEffect(() => {if (youTubeCategories.length > 0 && !pubItem.params.option.youtube?.categoryId) {- const option = pubItem.params.option;+ const option = pubItem.params.optionif (!option.youtube) {- option.youtube = {};+ option.youtube = {}}- option.youtube.categoryId = youTubeCategories[0].id;+ option.youtube.categoryId = youTubeCategories[0].idsetOnePubParams({option,},pubItem.account.id,- );+ )}- }, [youTubeCategories, pubItem.params.option.youtube?.categoryId, pubItem.account.id]);+ }, [youTubeCategories, pubItem.params.option.youtube?.categoryId, pubItem.account.id])// 初始化YouTube参数useEffect(() => {- const option = pubItem.params.option;+ const option = pubItem.params.optionif (!option.youtube) {- option.youtube = {};+ option.youtube = {}}- let needsUpdate = false;+ let needsUpdate = falseif (!option.youtube.privacyStatus) {- option.youtube.privacyStatus = 'public';- needsUpdate = true;+ option.youtube.privacyStatus = 'public'+ needsUpdate = true}if (!option.youtube.license) {- option.youtube.license = 'youtube';- needsUpdate = true;+ option.youtube.license = 'youtube'+ needsUpdate = true}if ((option.youtube as any).notifySubscribers === undefined) {- (option.youtube as any).notifySubscribers = true;- needsUpdate = true;+ (option.youtube as any).notifySubscribers = true+ needsUpdate = true}if ((option.youtube as any).embeddable === undefined) {- (option.youtube as any).embeddable = true;- needsUpdate = true;+ (option.youtube as any).embeddable = true+ needsUpdate = true}if ((option.youtube as any).selfDeclaredMadeForKids === undefined) {- (option.youtube as any).selfDeclaredMadeForKids = false;- needsUpdate = true;+ (option.youtube as any).selfDeclaredMadeForKids = false+ needsUpdate = true}if (needsUpdate) {@@ -85,76 +86,75 @@ const YouTubeParams = memo(option,},pubItem.account.id,- );+ )}- }, [pubItem.account.id]);-+ }, [pubItem.account.id])return (<><PubParmasTextarea{...pubParmasTextareaCommonParams}- extend={+ extend={(<><CommonTitleInput pubItem={pubItem} /><div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: '10px' }}><divclassName={styles.commonTitleInput}- style={{ marginTop: "10px", flex: 1 }}+ style={{ marginTop: '10px', flex: 1 }}>- <div className="platParamsSetting-label">{t("form.category")}</div>+ <div className="platParamsSetting-label">{t('form.category')}</div><Select- style={{ width: "100%" }}- options={youTubeCategories.map((item) => ({+ style={{ width: '100%' }}+ options={youTubeCategories.map(item => ({label: item.snippet.title,value: item.id,}))}value={pubItem.params.option.youtube?.categoryId}onChange={(value) => {- const option = pubItem.params.option;+ const option = pubItem.params.optionif (!option.youtube) {- option.youtube = {};+ option.youtube = {}}- option.youtube.categoryId = value;+ option.youtube.categoryId = valuesetOnePubParams({option,},pubItem.account.id,- );+ )}}showSearch={true}- placeholder={t("form.categoryPlaceholder")}+ placeholder={t('form.categoryPlaceholder')}/></div><divclassName={styles.commonTitleInput}- style={{ marginTop: "10px", flex: 1 }}+ style={{ marginTop: '10px', flex: 1 }}>- <div className="platParamsSetting-label">{t("form.privacyStatus")}</div>+ <div className="platParamsSetting-label">{t('form.privacyStatus')}</div><Selectvalue={pubItem.params.option.youtube?.privacyStatus}options={[- { value: "public", label: t("form.public") },- { value: "unlisted", label: t("form.unlisted") },- { value: "private", label: t("form.private") },+ { value: 'public', label: t('form.public') },+ { value: 'unlisted', label: t('form.unlisted') },+ { value: 'private', label: t('form.private') },]}onChange={(value) => {- const option = pubItem.params.option;+ const option = pubItem.params.optionif (!option.youtube) {- option.youtube = {};+ option.youtube = {}}- option.youtube.privacyStatus = value;+ option.youtube.privacyStatus = valuesetOnePubParams({option,},pubItem.account.id,- );+ )}}- style={{ width: "100%" }}+ style={{ width: '100%' }}placeholder="请选择隐私状态"/></div>@@ -163,30 +163,30 @@ const YouTubeParams = memo(<divclassName={styles.commonTitleInput}- style={{ marginTop: "10px" }}+ style={{ marginTop: '10px' }}>- <div className="platParamsSetting-label">{t("form.license" as any)}</div>+ <div className="platParamsSetting-label">{t('form.license' as any)}</div><Select- style={{ width: "100%" }}+ style={{ width: '100%' }}options={[- { value: "youtube", label: t("form.standardYouTubeLicense" as any) },- { value: "creativeCommon", label: t("form.creativeCommonsLicense" as any) },+ { value: 'youtube', label: t('form.standardYouTubeLicense' as any) },+ { value: 'creativeCommon', label: t('form.creativeCommonsLicense' as any) },]}value={pubItem.params.option.youtube?.license}onChange={(value) => {- const option = pubItem.params.option;+ const option = pubItem.params.optionif (!option.youtube) {- option.youtube = {};+ option.youtube = {}}- option.youtube.license = value;+ option.youtube.license = valuesetOnePubParams({option,},pubItem.account.id,- );+ )}}- placeholder={t("form.licensePlaceholder" as any)}+ placeholder={t('form.licensePlaceholder' as any)}/></div>@@ -197,24 +197,25 @@ const YouTubeParams = memo(alignItems: 'center',justifyContent: 'space-between',marginTop: '20px',- flexWrap: 'wrap'- }}>+ flexWrap: 'wrap',+ }}+ ><div style={{ width: '40px' }}> </div><Checkboxchecked={(pubItem.params.option.youtube as any)?.notifySubscribers}onChange={(e) => {- const option = pubItem.params.option;+ const option = pubItem.params.optionif (!option.youtube) {- option.youtube = {};+ option.youtube = {}}- (option.youtube as any).notifySubscribers = e.target.checked;+ (option.youtube as any).notifySubscribers = e.target.checkedsetOnePubParams({option,},pubItem.account.id,- );+ )}}>Notify Subscribers@@ -223,17 +224,17 @@ const YouTubeParams = memo(<Checkboxchecked={(pubItem.params.option.youtube as any)?.embeddable}onChange={(e) => {- const option = pubItem.params.option;+ const option = pubItem.params.optionif (!option.youtube) {- option.youtube = {};+ option.youtube = {}}- (option.youtube as any).embeddable = e.target.checked;+ (option.youtube as any).embeddable = e.target.checkedsetOnePubParams({option,},pubItem.account.id,- );+ )}}>Allow Embedding@@ -242,29 +243,29 @@ const YouTubeParams = memo(<Checkboxchecked={(pubItem.params.option.youtube as any)?.selfDeclaredMadeForKids}onChange={(e) => {- const option = pubItem.params.option;+ const option = pubItem.params.optionif (!option.youtube) {- option.youtube = {};+ option.youtube = {}}- (option.youtube as any).selfDeclaredMadeForKids = e.target.checked;+ (option.youtube as any).selfDeclaredMadeForKids = e.target.checkedsetOnePubParams({option,},pubItem.account.id,- );+ )}}>Made for Kids</Checkbox></div></>- }+ )}/></>- );+ )},),-);+)-export default YouTubeParams;\ No newline at end of file+export default YouTubeParamsdiff --git a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type.ts b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type.tsindex b9f789fd..787f0f7c 100644--- a/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type.ts+++ b/project/web/src/components/PublishDialog/compoents/PlatParamsSetting/plats/plats.type.ts@@ -1,7 +1,7 @@-import { PubItem } from "@/components/PublishDialog/publishDialog.type";+import type { PubItem } from '@/components/PublishDialog/publishDialog.type'export interface IPlatsParamsRef {}export interface IPlatsParamsProps {- pubItem: PubItem;+ pubItem: PubItem}diff --git a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/components/Menu.tsx b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/components/Menu.tsxindex d4442dde..14924f39 100644--- a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/components/Menu.tsx+++ b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/components/Menu.tsx@@ -1,10 +1,10 @@-import {+import type {BeautifulMentionsMenuItemProps,BeautifulMentionsMenuProps,-} from "lexical-beautiful-mentions";-import { forwardRef } from "react";-import styles from "../pubParmasMentionInput.module.scss";-import { LoadingOutlined } from "@ant-design/icons";+} from 'lexical-beautiful-mentions'+import { LoadingOutlined } from '@ant-design/icons'+import { forwardRef } from 'react'+import styles from '../pubParmasMentionInput.module.scss'/*** Menu component for the BeautifulMentionsPlugin.@@ -16,9 +16,9 @@ export function Menu({ loading, ...other }: BeautifulMentionsMenuProps) {<span>Loading</span><LoadingOutlined /></div>- );+ )}- return <ul className={styles.mentionMenu} {...other} />;+ return <ul className={styles.mentionMenu} {...other} />}/**@@ -31,7 +31,7 @@ export const MenuItem = forwardRef<<liref={ref}{...props}- className={`${styles.mentionMenuItem} ${selected ? styles.selected : ""}`}+ className={`${styles.mentionMenuItem} ${selected ? styles.selected : ''}`}/>-));-MenuItem.displayName = "MenuItem";+))+MenuItem.displayName = 'MenuItem'diff --git a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/index.tsx b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/index.tsxindex 4bf2f53c..6c80eecb 100644--- a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/index.tsx+++ b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/index.tsx@@ -1,65 +1,70 @@-"use client";+'use client'-import React, {+import type {+ InitialConfigType,+} from '@lexical/react/LexicalComposer'+import type { EditorState, LexicalEditor } from 'lexical'+import type {ForwardedRef,- forwardRef,- memo,- useCallback,- useRef,-} from "react";+} from 'react'+import { AutoFocusPlugin } from '@lexical/react/LexicalAutoFocusPlugin'+import {+ LexicalComposer,+} from '@lexical/react/LexicalComposer'+import { ContentEditable } from '@lexical/react/LexicalContentEditable'+import { LexicalErrorBoundary } from '@lexical/react/LexicalErrorBoundary'+import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin'+import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin'+import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin'+import { $getRoot } from 'lexical'import {BeautifulMentionNode,BeautifulMentionsPlugin,PlaceholderNode,-} from "lexical-beautiful-mentions";-import {- InitialConfigType,- LexicalComposer,-} from "@lexical/react/LexicalComposer";-import { RichTextPlugin } from "@lexical/react/LexicalRichTextPlugin";-import { ContentEditable } from "@lexical/react/LexicalContentEditable";-import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary";-import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin";-import { EditorState, $getRoot, LexicalEditor } from "lexical";-import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";-import { AutoFocusPlugin } from "@lexical/react/LexicalAutoFocusPlugin";-import styles from "./pubParmasMentionInput.module.scss";+} from 'lexical-beautiful-mentions'+import React, {+ forwardRef,+ memo,+ useCallback,+ useRef,+} from 'react'+import { getDouyinTopicsApi } from '@/api/dataStatistics'import {Menu,MenuItem,-} from "@/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/components/Menu";-import { getDouyinTopicsApi } from "@/api/dataStatistics";+} from '@/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/components/Menu'import {InitialValuePlugin,PasteTopicsPlugin,-} from "@/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/utils/editor-utils";+} from '@/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/utils/editor-utils'+import styles from './pubParmasMentionInput.module.scss'export interface IPubParmasMentionInputRef {}export interface IPubParmasMentionInputProps {- onChange: (value: string) => void;- value: string;- placeholder: string;- maxLength: number;+ onChange: (value: string) => void+ value: string+ placeholder: string+ maxLength: number}const mentionItems = {- "#": [],-};+ '#': [],+}const editorConfig: InitialConfigType = {nodes: [BeautifulMentionNode, PlaceholderNode],- namespace: "PublishDescriptionEditor",+ namespace: 'PublishDescriptionEditor',onError(error: Error) {- throw error;+ throw error},theme: {beautifulMentions: {- "#": `${styles.mentionsStyle}`,+ '#': `${styles.mentionsStyle}`,},},-};+}const PubParmasMentionInput = memo(forwardRef(@@ -67,35 +72,36 @@ const PubParmasMentionInput = memo({ onChange, value, placeholder, maxLength }: IPubParmasMentionInputProps,ref: ForwardedRef<IPubParmasMentionInputRef>,) => {- const comboboxAnchor = useRef<HTMLDivElement>(null);+ const comboboxAnchor = useRef<HTMLDivElement>(null)const handleChange = useCallback((editorState: EditorState, editor: LexicalEditor) => {editorState.read(() => {- const root = $getRoot();- const text = root.getTextContent();- onChange(text);- });+ const root = $getRoot()+ const text = root.getTextContent()+ onChange(text)+ })},[],- );+ )const handleSearch = useCallback(async (trigger: string, queryString?: string | null) => {- if (!queryString) return [];- const res = await getDouyinTopicsApi(queryString!);- return res?.data ?? [];+ if (!queryString)+ return []+ const res = await getDouyinTopicsApi(queryString!)+ return res?.data ?? []},[],- );+ )// @ts-ignoreconst beautifulMentionsProps: any = {comboboxAnchor: comboboxAnchor.current,items: mentionItems,- triggers: ["#"],+ triggers: ['#'],autoSpace: true,creatable: {- "#": 'Add tag "{{name}}"',+ '#': 'Add tag "{{name}}"',},menuComponent: Menu,menuItemComponent: MenuItem,@@ -104,18 +110,18 @@ const PubParmasMentionInput = memo(allowSpaces: false,searchDelay: 200,onSearch: handleSearch,- };+ }return (<div className={styles.mentionsContainer} ref={comboboxAnchor}><LexicalComposer initialConfig={editorConfig}><RichTextPlugin- contentEditable={+ contentEditable={(<ContentEditableclassName={styles.mentionsContentEditable}style={{ tabSize: 1 }}/>- }+ )}placeholder={<div className={styles.mentionsPlaceholder}>{placeholder}</div>}@@ -132,9 +138,9 @@ const PubParmasMentionInput = memo(<BeautifulMentionsPlugin {...beautifulMentionsProps} /></LexicalComposer></div>- );+ )},),-);+)-export default PubParmasMentionInput;+export default PubParmasMentionInputdiff --git a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/pubParmasMentionInput.module.scss b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/pubParmasMentionInput.module.scssindex 2254d9ef..306943ad 100644--- a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/pubParmasMentionInput.module.scss+++ b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/pubParmasMentionInput.module.scss@@ -1,4 +1,5 @@-.mentionMenu, .mentionMenuLoading {+.mentionMenu,+.mentionMenuLoading {position: absolute;top: 2px;left: 0;@@ -8,7 +9,7 @@min-width: 8rem;border: 1px solid #e5e7eb;border-radius: 0.375rem;- box-shadow: 0 4px 16px rgba(0,0,0,0.08);+ box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);padding: 0.25rem;margin: 0;overflow: hidden;@@ -19,7 +20,8 @@border-radius: 0.25rem;cursor: pointer;transition: background 0.15s;- &:hover, &[aria-selected="true"] {+ &:hover,+ &[aria-selected='true'] {background: #f3f4f6;}}@@ -93,7 +95,9 @@outline: none;height: 250px;overflow: auto !important;- transition: box-shadow 0.2s, border-color 0.2s;+ transition:+ box-shadow 0.2s,+ border-color 0.2s;&::placeholder {color: var(--grayColor7);diff --git a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/utils/editor-utils.ts b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/utils/editor-utils.tsindex 83a3ea38..8b927c50 100644--- a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/utils/editor-utils.ts+++ b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput/utils/editor-utils.ts@@ -1,111 +1,116 @@-import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";-import { useEffect, useRef } from "react";+import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'import {$createParagraphNode,$createTextNode,$getRoot,$getSelection,$isRangeSelection,- PASTE_COMMAND,COMMAND_PRIORITY_LOW,-} from "lexical";-import { BeautifulMentionNode } from "lexical-beautiful-mentions";+ PASTE_COMMAND,+} from 'lexical'+import { BeautifulMentionNode } from 'lexical-beautiful-mentions'+import { useEffect, useRef } from 'react'export function InitialValuePlugin({ value }: { value: string }) {- const [editor] = useLexicalComposerContext();- const lastAppliedRef = useRef<string>("");+ const [editor] = useLexicalComposerContext()+ const lastAppliedRef = useRef<string>('')useEffect(() => {editor.update(() => {- const root = $getRoot();- const currentText = root.getTextContent();- if (value === currentText || value === lastAppliedRef.current) return;+ const root = $getRoot()+ const currentText = root.getTextContent()+ if (value === currentText || value === lastAppliedRef.current)+ return- root.clear();- const paragraph = $createParagraphNode();- root.append(paragraph);+ root.clear()+ const paragraph = $createParagraphNode()+ root.append(paragraph)if (!value) {- lastAppliedRef.current = value;- return;+ lastAppliedRef.current = value+ return}// 按原顺序拆分:话题片段形如 "#xxx"- const parts = value.split(/(#\S+)/g).filter(Boolean);+ const parts = value.split(/(#\S+)/g).filter(Boolean)- console.log(parts);+ console.log(parts)parts.forEach((part) => {- if (part.startsWith("#")) {- const topic = part.slice(1);+ if (part.startsWith('#')) {+ const topic = part.slice(1)if (topic) {// @ts-ignore 构造函数依库版本- const mentionNode = new BeautifulMentionNode("#", topic);- paragraph.append(mentionNode);+ const mentionNode = new BeautifulMentionNode('#', topic)+ paragraph.append(mentionNode)}- } else {+ }+ else {if (part) {- paragraph.append($createTextNode(part));+ paragraph.append($createTextNode(part))}}- });+ })- lastAppliedRef.current = value;- });- }, [editor, value]);+ lastAppliedRef.current = value+ })+ }, [editor, value])- return null;+ return null}export function PasteTopicsPlugin() {- const [editor] = useLexicalComposerContext();+ const [editor] = useLexicalComposerContext()useEffect(() => {return editor.registerCommand(PASTE_COMMAND,(event: ClipboardEvent) => {- const clipboardText = event.clipboardData?.getData("text/plain");- if (!clipboardText) return false;+ const clipboardText = event.clipboardData?.getData('text/plain')+ if (!clipboardText)+ return false- event.preventDefault();+ event.preventDefault()editor.update(() => {- const selection = $getSelection();+ const selection = $getSelection()// 仅处理普通范围选区- if (!$isRangeSelection(selection)) return;+ if (!$isRangeSelection(selection))+ return// 删除当前选区内容- selection.removeText();+ selection.removeText()- const lines = clipboardText.split(/\r?\n/);+ const lines = clipboardText.split(/\r?\n/)lines.forEach((line, idx) => {- const parts = line.split(/(#\S+)/g).filter(Boolean);+ const parts = line.split(/(#\S+)/g).filter(Boolean)parts.forEach((part) => {- if (part.startsWith("#")) {- const topic = part.slice(1);+ if (part.startsWith('#')) {+ const topic = part.slice(1)if (topic) {// @ts-ignore- const mentionNode = new BeautifulMentionNode("#", topic);- selection.insertNodes([mentionNode]);+ const mentionNode = new BeautifulMentionNode('#', topic)+ selection.insertNodes([mentionNode])}- } else {- selection.insertText(part);}- });+ else {+ selection.insertText(part)+ }+ })// 换行 -> 新段落if (idx < lines.length - 1) {- const p = $createParagraphNode();- selection.insertNodes([p]);- p.select();+ const p = $createParagraphNode()+ selection.insertNodes([p])+ p.select()}- });- });+ })+ })- return true;+ return true},COMMAND_PRIORITY_LOW,- );- }, [editor]);+ )+ }, [editor])- return null;+ return null}diff --git a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasTextareaUpload.tsx b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasTextareaUpload.tsxindex 55eb63a0..088ab563 100644--- a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasTextareaUpload.tsx+++ b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasTextareaUpload.tsx@@ -1,43 +1,45 @@-import React, {+import type { MenuProps } from 'antd'+import type { RcFile } from 'antd/es/upload'+import type { UploadRef } from 'antd/es/upload/Upload'+import type {ForwardedRef,+} from 'react'+import type { UploadResult } from '@/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload.type'+import type {+ IImgFile,+ IVideoFile,+} from '@/components/PublishDialog/publishDialog.type'+import { PlusOutlined } from '@ant-design/icons'+import { Dropdown, message, Upload } from 'antd'+import React, {forwardRef,memo,useCallback,useMemo,useRef,useState,-} from "react";-import { Dropdown, message, Upload } from "antd";+} from 'react'+import { useTransClient } from '@/app/i18n/client'+import MaterialSelectionModal from '@/components/PublishDialog/compoents/MaterialSelectionModal'+import { UploadTaskTypeEnum } from '@/components/PublishDialog/compoents/PublishManageUpload/publishManageUpload.enum'+import { usePublishManageUpload } from '@/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload'import {formatImg,formatVideo,VideoGrabFrame,-} from "@/components/PublishDialog/PublishDialog.util";-import {- IImgFile,- IVideoFile,-} from "@/components/PublishDialog/publishDialog.type";-import { OSS_URL } from "@/constant";-import { RcFile } from "antd/es/upload";-import { useTransClient } from "@/app/i18n/client";-import { UploadRef } from "antd/es/upload/Upload";-import { PlusOutlined } from "@ant-design/icons";-import type { MenuProps } from "antd";-import MaterialSelectionModal from "@/components/PublishDialog/compoents/MaterialSelectionModal";-import { getOssUrl } from "@/utils/oss";-import { usePublishManageUpload } from "@/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload";-import { UploadResult } from "@/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload.type";-import { UploadTaskTypeEnum } from "@/components/PublishDialog/compoents/PublishManageUpload/publishManageUpload.enum";+} from '@/components/PublishDialog/PublishDialog.util'+import { OSS_URL } from '@/constant'+import { getOssUrl } from '@/utils/oss'-const { Dragger } = Upload;+const { Dragger } = Uploadexport interface IPubParmasTextareaUploadRef {}export interface IPubParmasTextareaUploadProps {- uploadAccept: string;- checkFileListType: (fileList: File[]) => boolean;- onVideoUpdateFinish: (video: IVideoFile) => void;- onImgUpdateFinish: (img: IImgFile[]) => void;+ uploadAccept: string+ checkFileListType: (fileList: File[]) => boolean+ onVideoUpdateFinish: (video: IVideoFile) => void+ onImgUpdateFinish: (img: IImgFile[]) => void}const PubParmasTextareaUpload = memo(@@ -51,21 +53,21 @@ const PubParmasTextareaUpload = memo(}: IPubParmasTextareaUploadProps,ref: ForwardedRef<IPubParmasTextareaUploadRef>,) => {- const chooseCount = useRef<number>(0);- const fileListRef = useRef<RcFile[]>([]);- const { t } = useTransClient("publish");- const uploadRef = useRef<UploadRef>(null);- const [materialSelectionOpen, setMaterialSelectionOpen] = useState(false);+ const chooseCount = useRef<number>(0)+ const fileListRef = useRef<RcFile[]>([])+ const { t } = useTransClient('publish')+ const uploadRef = useRef<UploadRef>(null)+ const [materialSelectionOpen, setMaterialSelectionOpen] = useState(false)const enqueueUpload = usePublishManageUpload(- (state) => state.enqueueUpload,- );+ state => state.enqueueUpload,+ )const isAbortError = useCallback((error: unknown) => {if (error instanceof DOMException) {- return error.name === "AbortError";+ return error.name === 'AbortError'}- return Boolean((error as { name?: string })?.name === "AbortError");- }, []);+ return Boolean((error as { name?: string })?.name === 'AbortError')+ }, [])// 上传视频const uploadVideo = useCallback(@@ -74,12 +76,12 @@ const PubParmasTextareaUpload = memo(file: video.file,fileName: video.filename,type: UploadTaskTypeEnum.Video,- });+ })const coverHandle = enqueueUpload({file: video.cover.file,fileName: video.cover.filename,type: UploadTaskTypeEnum.VideoCover,- });+ })const videoWithTasks: IVideoFile = {...video,@@ -91,15 +93,15 @@ const PubParmasTextareaUpload = memo(video: videoHandle.taskId,cover: coverHandle.taskId,},- };+ }- onVideoUpdateFinish(videoWithTasks);+ onVideoUpdateFinish(videoWithTasks)try {const [videoResult, coverResult] = await Promise.all([videoHandle.promise,coverHandle.promise,- ]);+ ])onVideoUpdateFinish({...videoWithTasks,@@ -108,54 +110,55 @@ const PubParmasTextareaUpload = memo(...videoWithTasks.cover,ossUrl: coverResult.ossUrl,},- });- } catch (error) {+ })+ }+ catch (error) {if (!isAbortError(error)) {- console.error(error);- message.error("上传失败,请稍后重试");- videoHandle.cancel();- coverHandle.cancel();+ console.error(error)+ message.error('上传失败,请稍后重试')+ videoHandle.cancel()+ coverHandle.cancel()}}},[enqueueUpload, isAbortError, onVideoUpdateFinish],- );+ )// 上传图片const uploadImg = useCallback(async (fileList: RcFile[]) => {const uploads: Array<{- image: IImgFile;- promise: Promise<UploadResult>;- cancel: () => void;- }> = [];+ image: IImgFile+ promise: Promise<UploadResult>+ cancel: () => void+ }> = []for (const file of fileList) {const image = await formatImg({blob: file!,path: file.name,- });+ })const handle = enqueueUpload({file: image.file,fileName: image.filename,type: UploadTaskTypeEnum.Image,- });+ })const imageWithTask: IImgFile = {...image,uploadTaskId: handle.taskId,- };+ }uploads.push({image: imageWithTask,promise: handle.promise,cancel: handle.cancel,- });+ })}if (uploads.length) {- onImgUpdateFinish(uploads.map((item) => item.image));+ onImgUpdateFinish(uploads.map(item => item.image))}uploads.forEach(({ image, promise, cancel }) => {@@ -166,130 +169,133 @@ const PubParmasTextareaUpload = memo(...image,ossUrl: result.ossUrl,},- ]);+ ])}).catch((error) => {if (!isAbortError(error)) {- console.error(error);- message.error("上传失败,请稍后重试");- cancel();+ console.error(error)+ message.error('上传失败,请稍后重试')+ cancel()}- });- });+ })+ })},[enqueueUpload, isAbortError, onImgUpdateFinish],- );+ )- const dropdownItems: MenuProps["items"] = useMemo(() => {+ const dropdownItems: MenuProps['items'] = useMemo(() => {return [{- key: "1",+ key: '1',label: (<aonClick={() => {// 触发上传uploadRef- .current!.nativeElement?.querySelector("input")!- .click();+ .current!.nativeElement?.querySelector('input')!+ .click()}}>- {t("upload.uploadLocal")}+ {t('upload.uploadLocal')}</a>),},{- key: "2",+ key: '2',label: (<a onClick={() => setMaterialSelectionOpen(true)}>- {t("actions.selectMaterial")}+ {t('actions.selectMaterial')}</a>),},- ];- }, [t]);+ ]+ }, [t])return (<divclassName="pubParmasTextarea-uploads-upload"- onClick={(e) => e.stopPropagation()}+ onClick={e => e.stopPropagation()}><MaterialSelectionModalonCancel={() => setMaterialSelectionOpen(false)}libraryModalOpen={materialSelectionOpen}- allowImage={uploadAccept.includes("image")}- allowVideo={uploadAccept.includes("video")}+ allowImage={uploadAccept.includes('image')}+ allowVideo={uploadAccept.includes('video')}onSelected={async (item) => {- const ossUrl = getOssUrl(item.url);+ const ossUrl = getOssUrl(item.url)try {- if (item.type === "img") {+ if (item.type === 'img') {// 图片素材,下载const req = await fetch(- ossUrl.replace(OSS_URL, "/ossProxy/"),- );- const blob = await req.blob();+ ossUrl.replace(OSS_URL, '/ossProxy/'),+ )+ const blob = await req.blob()const imagefile = await formatImg({blob,- path: `${item.title || "image"}.${blob.type.split("/")[1]}`,- });- imagefile["ossUrl"] = item.url;- onImgUpdateFinish([imagefile]);- } else {- const videoInfo = await VideoGrabFrame(ossUrl, 0);+ path: `${item.title || 'image'}.${blob.type.split('/')[1]}`,+ })+ imagefile.ossUrl = item.url+ onImgUpdateFinish([imagefile])+ }+ else {+ const videoInfo = await VideoGrabFrame(ossUrl, 0)const video: any = {- ossUrl: ossUrl,+ ossUrl,videoUrl: ossUrl,width: videoInfo.width,height: videoInfo.height,duration: videoInfo.duration,size: item.metadata.size,cover: videoInfo.cover,- };- onVideoUpdateFinish(video);+ }+ onVideoUpdateFinish(video)}- } catch (e) {- console.error(e);+ }+ catch (e) {+ console.error(e)}}}/><Draggerref={uploadRef}- style={{ display: "none" }}+ style={{ display: 'none' }}accept={uploadAccept}- multiple={uploadAccept.includes("image")}+ multiple={uploadAccept.includes('image')}listType="text"beforeUpload={async (file, uploadFileList) => {if (!checkFileListType(uploadFileList)) {- return Upload.LIST_IGNORE;+ return Upload.LIST_IGNORE+ }+ if (file.type.startsWith('video/')) {+ const video = await formatVideo(file)+ await uploadVideo(video)}- if (file.type.startsWith("video/")) {- const video = await formatVideo(file);- await uploadVideo(video);- } else {- chooseCount.current++;- fileListRef.current = [...fileListRef.current, file];+ else {+ chooseCount.current+++ fileListRef.current = [...fileListRef.current, file]if (chooseCount.current === uploadFileList.length) {- await uploadImg(fileListRef.current);- fileListRef.current = [];- chooseCount.current = 0;+ await uploadImg(fileListRef.current)+ fileListRef.current = []+ chooseCount.current = 0}}- return false;+ return false}}showUploadList={false}/><Dropdown menu={{ items: dropdownItems }} placement="top"><div className="pubParmasTextarea-uploads-upload-blocker">- <PlusOutlined style={{ fontSize: "20px" }} />- {t("upload.selectFile")}+ <PlusOutlined style={{ fontSize: '20px' }} />+ {t('upload.selectFile')}</div></Dropdown></div>- );+ )},),-);+)-export default PubParmasTextareaUpload;+export default PubParmasTextareaUploaddiff --git a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasTextuploadImage.tsx b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasTextuploadImage.tsxindex 9af5bd6c..14646c66 100644--- a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasTextuploadImage.tsx+++ b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/PubParmasTextuploadImage.tsx@@ -1,17 +1,18 @@-import React, { ForwardedRef, forwardRef, memo } from "react";-import { CloseOutlined, EditOutlined } from "@ant-design/icons";-import { Button, Tooltip } from "antd";-import { useTranslation } from "react-i18next";-import { IImgFile } from "@/components/PublishDialog/publishDialog.type";-import PublishUploadProgress from "@/components/PublishDialog/compoents/PublishManageUpload/PublishUploadProgress";+import type { ForwardedRef } from 'react'+import type { IImgFile } from '@/components/PublishDialog/publishDialog.type'+import { CloseOutlined, EditOutlined } from '@ant-design/icons'+import { Button, Tooltip } from 'antd'+import React, { forwardRef, memo } from 'react'+import { useTranslation } from 'react-i18next'+import PublishUploadProgress from '@/components/PublishDialog/compoents/PublishManageUpload/PublishUploadProgress'export interface IPubParmasTextuploadImageRef {}export interface IPubParmasTextuploadImageProps {- onClose: () => void;- onClick: () => void;- imageFile: IImgFile;- onEditClick: () => void;+ onClose: () => void+ onClick: () => void+ imageFile: IImgFile+ onEditClick: () => void}const PubParmasTextuploadImage = memo(@@ -25,7 +26,7 @@ const PubParmasTextuploadImage = memo(}: IPubParmasTextuploadImageProps,ref: ForwardedRef<IPubParmasTextuploadImageRef>,) => {- const { t } = useTranslation("publish");+ const { t } = useTranslation('publish')return (<>@@ -33,13 +34,13 @@ const PubParmasTextuploadImage = memo(<divclassName="pubParmasTextarea-uploads-item-close"onClick={(e) => {- e.stopPropagation();- onClose();+ e.stopPropagation()+ onClose()}}><CloseOutlined /></div>- <Tooltip title={t("actions.preview")}>+ <Tooltip title={t('actions.preview')}><img src={imageFile.imgUrl} alt="preview" /></Tooltip>@@ -49,8 +50,8 @@ const PubParmasTextuploadImage = memo(icon={<EditOutlined />}size="small"onClick={(e) => {- e.stopPropagation();- onEditClick();+ e.stopPropagation()+ onEditClick()}}/></Tooltip>@@ -60,9 +61,9 @@ const PubParmasTextuploadImage = memo()}</div></>- );+ )},),-);+)-export default PubParmasTextuploadImage;+export default PubParmasTextuploadImagediff --git a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/VideoCoverSeting.tsx b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/VideoCoverSeting.tsxindex 676b15e8..1fad580f 100644--- a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/VideoCoverSeting.tsx+++ b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/VideoCoverSeting.tsx@@ -1,41 +1,43 @@-import {+import type {ForwardedRef,+} from 'react'+import type {+ IImgFile,+ IVideoFile,+} from '@/components/PublishDialog/publishDialog.type'+import { Alert, Button, Modal, Slider, Spin } from 'antd'+import Cropper from 'cropperjs'+import {forwardRef,memo,useEffect,useRef,useState,-} from "react";-import styles from "./videoCoverSeting.module.scss";-import { Alert, Button, Modal, Slider, Spin } from "antd";-import Cropper from "cropperjs";-import "cropperjs/dist/cropper.css";+} from 'react'+import { uploadToOss } from '@/api/oss'+import ImgChoose from '@/components/PublishDialog/compoents/Choose/ImgChoose'import {formatImg,VideoGrabFrame,-} from "@/components/PublishDialog/PublishDialog.util";-import {- IImgFile,- IVideoFile,-} from "@/components/PublishDialog/publishDialog.type";-import ImgChoose from "@/components/PublishDialog/compoents/Choose/ImgChoose";-import { uploadToOss } from "@/api/oss";-import { getOssUrl } from "@/utils/oss";+} from '@/components/PublishDialog/PublishDialog.util'+import { getOssUrl } from '@/utils/oss'+import styles from './videoCoverSeting.module.scss'+import 'cropperjs/dist/cropper.css'export interface IVideoCoverSetingRef {}export interface IVideoCoverSetingProps {// 封面选择完成- onChoosed: (imgFile: IImgFile) => void;+ onChoosed: (imgFile: IImgFile) => void// 当前选择的封面- value?: IImgFile;+ value?: IImgFile// 需要截帧的视频- videoFile?: IVideoFile;+ videoFile?: IVideoFile// 保存图片的唯一值- saveImgId?: string;+ saveImgId?: string// 关闭按钮点击事件,如果有这个事件就会显示关闭按钮- onClose: () => void;- videoCoverSetingModal: boolean;+ onClose: () => void+ videoCoverSetingModal: boolean}// 视频封面设置@@ -47,51 +49,54 @@ const VideoCoverSeting = memo(onChoosed,value,videoFile,- saveImgId = "",+ saveImgId = '',onClose,}: IVideoCoverSetingProps,ref: ForwardedRef<IVideoCoverSetingRef>,) => {- const [imgFile, setImgFile] = useState<IImgFile>();- const cropper = useRef<Cropper>();- const cropperImg = useRef<HTMLImageElement>(null);- const [videoCoverLoading, setVideoCoverLoading] = useState(false);- const [sliderVal, setSliderVal] = useState(0);- const [uploadLoing, setUploadLoing] = useState(false);+ const [imgFile, setImgFile] = useState<IImgFile>()+ const cropper = useRef<Cropper>()+ const cropperImg = useRef<HTMLImageElement>(null)+ const [videoCoverLoading, setVideoCoverLoading] = useState(false)+ const [sliderVal, setSliderVal] = useState(0)+ const [uploadLoing, setUploadLoing] = useState(false)useEffect(() => {- if (!videoCoverSetingModal) return;+ if (!videoCoverSetingModal)+ returnif (value) {- setImgFile(value);- return;+ setImgFile(value)+ return}- getVideoCover(0);- }, [videoCoverSetingModal]);+ getVideoCover(0)+ }, [videoCoverSetingModal])useEffect(() => {- if (!imgFile) return;- initCropper();- }, [imgFile]);+ if (!imgFile)+ return+ initCropper()+ }, [imgFile])/* 获取封面 */const getVideoCover = async (n: number) => {- setVideoCoverLoading(true);- const videoInfo = await VideoGrabFrame(videoFile!.videoUrl, n);- setImgFile(videoInfo.cover);- setVideoCoverLoading(false);- };+ setVideoCoverLoading(true)+ const videoInfo = await VideoGrabFrame(videoFile!.videoUrl, n)+ setImgFile(videoInfo.cover)+ setVideoCoverLoading(false)+ }const close = () => {- onClose();- };+ onClose()+ }// 初始化裁剪工具const initCropper = () => {- if (!cropperImg.current) return;+ if (!cropperImg.current)+ returnif (cropper.current) {- cropper.current.destroy();- cropper.current = undefined;+ cropper.current.destroy()+ cropper.current = undefined}cropper.current = new Cropper(cropperImg.current!, {@@ -105,10 +110,10 @@ const VideoCoverSeting = memo(top: 0,width: cropperImg.current!.naturalWidth,height: cropperImg.current!.naturalHeight,- });+ })},- });- };+ })+ }return (<>@@ -118,35 +123,35 @@ const VideoCoverSeting = memo(maskClosable={false}open={videoCoverSetingModal}onCancel={close}- footer={+ footer={(<><Button onClick={close}>取消</Button><Buttonloading={uploadLoing}type="primary"onClick={async () => {- setUploadLoing(true);- const canvas = cropper.current!.getCroppedCanvas();- canvas.toBlob(async function (blob) {+ setUploadLoing(true)+ const canvas = cropper.current!.getCroppedCanvas()+ canvas.toBlob(async (blob) => {const cover = await formatImg({blob: blob!,- path: `${saveImgId}.${imgFile?.file.type.split("/")[1]}`,- });+ path: `${saveImgId}.${imgFile?.file.type.split('/')[1]}`,+ })// 上传封面const uploadCoverRes = await uploadToOss(cover.file,- );- cover["ossUrl"] = getOssUrl(uploadCoverRes);- setUploadLoing(false);- onChoosed(cover);- close();- }, "image/png");+ )+ cover.ossUrl = getOssUrl(uploadCoverRes)+ setUploadLoing(false)+ onChoosed(cover)+ close()+ }, 'image/png')}}>确定</Button></>- }+ )}><Spin spinning={videoCoverLoading}><div className={styles.videoCoverSetingModal}>@@ -158,8 +163,9 @@ const VideoCoverSeting = memo(/><ImgChooseonChoose={(imgFile) => {- if (!imgFile) return;- setImgFile(imgFile);+ if (!imgFile)+ return+ setImgFile(imgFile)}}><Button>本地上传</Button>@@ -168,15 +174,15 @@ const VideoCoverSeting = memo(<div className="videoCoverSetingModal-cropper"><img- style={{ opacity: imgFile?.imgUrl ? "1" : "0" }}+ style={{ opacity: imgFile?.imgUrl ? '1' : '0' }}ref={cropperImg}- src={imgFile?.imgUrl || "/"}+ src={imgFile?.imgUrl || '/'}/></div><Slidervalue={sliderVal}- style={{ margin: "50px 0" }}+ style={{ margin: '50px 0' }}step={1}min={0}max={videoFile?.duration}@@ -187,10 +193,10 @@ const VideoCoverSeting = memo(</Spin></Modal></>- );+ )},),-);-VideoCoverSeting.displayName = "VideoCoverSeting";+)+VideoCoverSeting.displayName = 'VideoCoverSeting'-export default VideoCoverSeting;+export default VideoCoverSetingdiff --git a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/index.tsx b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/index.tsxindex 60cbe2f7..a3091279 100644--- a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/index.tsx+++ b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/index.tsx@@ -1,6 +1,20 @@-import React, {+import type {CSSProperties,ForwardedRef,+} from 'react'+import type { PlatType } from '@/app/config/platConfig'+import type {+ IImgFile,+ IVideoFile,+} from '@/components/PublishDialog/publishDialog.type'+import {+ CaretRightOutlined,+ CloseOutlined,+ FileTextOutlined,+} from '@ant-design/icons'+import { Button, Image, Input, message, Tooltip } from 'antd'+import dynamic from 'next/dynamic'+import React, {forwardRef,memo,useCallback,@@ -8,69 +22,58 @@ import React, {useMemo,useRef,useState,-} from "react";-import { Button, Image, Input, message, Tooltip } from "antd";-import styles from "@/components/PublishDialog/compoents/PubParmasTextarea/pubCommonComps.module.scss";-import { ReactSortable } from "react-sortablejs";-import { CSSTransition, TransitionGroup } from "react-transition-group";-import {- CaretRightOutlined,- CloseOutlined,- FileTextOutlined,-} from "@ant-design/icons";-import {- IImgFile,- IVideoFile,-} from "@/components/PublishDialog/publishDialog.type";--import VideoCoverSeting from "@/components/PublishDialog/compoents/PubParmasTextarea/VideoCoverSeting";-import PubParmasTextareaUpload from "@/components/PublishDialog/compoents/PubParmasTextarea/PubParmasTextareaUpload";-import { AccountPlatInfoMap, PlatType } from "@/app/config/platConfig";-import { PubType } from "@/app/config/publishConfig";-import { useTransClient } from "@/app/i18n/client";-import PubParmasTextuploadImage from "@/components/PublishDialog/compoents/PubParmasTextarea/PubParmasTextuploadImage";-import VideoPreviewModal from "@/components/VideoPreviewModal";-import dynamic from "next/dynamic";-import Aibrush from "@/components/PublishDialog/svgs/aibrush.svg";-import { usePublishDialog } from "@/components/PublishDialog/usePublishDialog";-import { useShallow } from "zustand/react/shallow";-import DraftSelectionModal from "@/components/PublishDialog/compoents/DraftSelectionModal";-import PubParmasMentionInput from "@/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput";-import { usePublishManageUpload } from "@/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload";-import PublishUploadProgress from "@/components/PublishDialog/compoents/PublishManageUpload/PublishUploadProgress";--const { TextArea } = Input;+} from 'react'+import { ReactSortable } from 'react-sortablejs'++import { CSSTransition, TransitionGroup } from 'react-transition-group'+import { useShallow } from 'zustand/react/shallow'+import { AccountPlatInfoMap } from '@/app/config/platConfig'+import { PubType } from '@/app/config/publishConfig'+import { useTransClient } from '@/app/i18n/client'+import DraftSelectionModal from '@/components/PublishDialog/compoents/DraftSelectionModal'+import PublishUploadProgress from '@/components/PublishDialog/compoents/PublishManageUpload/PublishUploadProgress'+import { usePublishManageUpload } from '@/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload'+import styles from '@/components/PublishDialog/compoents/PubParmasTextarea/pubCommonComps.module.scss'+import PubParmasMentionInput from '@/components/PublishDialog/compoents/PubParmasTextarea/PubParmasMentionInput'+import PubParmasTextareaUpload from '@/components/PublishDialog/compoents/PubParmasTextarea/PubParmasTextareaUpload'+import PubParmasTextuploadImage from '@/components/PublishDialog/compoents/PubParmasTextarea/PubParmasTextuploadImage'+import VideoCoverSeting from '@/components/PublishDialog/compoents/PubParmasTextarea/VideoCoverSeting'+import Aibrush from '@/components/PublishDialog/svgs/aibrush.svg'+import { usePublishDialog } from '@/components/PublishDialog/usePublishDialog'+import VideoPreviewModal from '@/components/VideoPreviewModal'++const { TextArea } = Inputexport interface IPubParmasTextareaRef {}export interface IChangeParams {- imgs?: IImgFile[];- video?: IVideoFile;- value: string;+ imgs?: IImgFile[]+ video?: IVideoFile+ value: string}export interface IPubParmasTextareaProps {- onChange?: (values: IChangeParams) => void;- rows?: number;+ onChange?: (values: IChangeParams) => void+ rows?: number// 视频数量限制- videoMax?: number;+ videoMax?: number// 扩展内容- extend?: React.ReactNode;+ extend?: React.ReactNode// 在前面的扩展元素- beforeExtend?: React.ReactNode;+ beforeExtend?: React.ReactNode// 在中间的扩展元素- centerExtend?: React.ReactNode;+ centerExtend?: React.ReactNode// 平台类型- platType: PlatType;- style?: CSSProperties;- imageFileListValue?: IImgFile[];- videoFileValue?: IVideoFile;- desValue?: string;+ platType: PlatType+ style?: CSSProperties+ imageFileListValue?: IImgFile[]+ videoFileValue?: IVideoFile+ desValue?: string}const ImageEditorModal = dynamic(- () => import("@/components/ImageEditorModal"),+ () => import('@/components/ImageEditorModal'),{ ssr: false },-);+)const PubParmasTextarea = memo(forwardRef(@@ -84,198 +87,206 @@ const PubParmasTextarea = memo(centerExtend,imageFileListValue = [],videoFileValue,- desValue = "",+ desValue = '',beforeExtend,platType,}: IPubParmasTextareaProps,ref: ForwardedRef<IPubParmasTextareaRef>,) => {- const [draftModalOpen, setDraftModalOpen] = useState(false);+ const [draftModalOpen, setDraftModalOpen] = useState(false)const { setOpenLeft } = usePublishDialog(- useShallow((state) => ({+ useShallow(state => ({setOpenLeft: state.setOpenLeft,})),- );- const [value, setValue] = useState(desValue);+ )+ const [value, setValue] = useState(desValue)const [previewData, setPreviewData] = useState<IImgFile | IVideoFile | undefined- >(undefined);+ >(undefined)// 图片- const [imageFileList, setImageFileList] =- useState<IImgFile[]>(imageFileListValue);+ const [imageFileList, setImageFileList]+ = useState<IImgFile[]>(imageFileListValue)// 视频const [videoFile, setVideoFile] = useState<IVideoFile | undefined>(videoFileValue,- );+ )// 裁剪弹框- const [videoCoverSetingModal, setVideoCoverSetingModal] = useState(false);+ const [videoCoverSetingModal, setVideoCoverSetingModal] = useState(false)const isFirst = useRef({effect: true,sort: true,- });- const { t } = useTransClient("publish");+ })+ const { t } = useTransClient('publish')// 编辑图片的索引- const [editImgIndex, setEditImgIndex] = useState(-1);+ const [editImgIndex, setEditImgIndex] = useState(-1)const { cancelUpload } = usePublishManageUpload(- useShallow((state) => ({+ useShallow(state => ({cancelUpload: state.cancelUpload,})),- );+ )useEffect(() => {if (isFirst.current.effect) {- isFirst.current.effect = false;- return;+ isFirst.current.effect = false+ return}const values = {imgs: imageFileList,video: videoFile,value,- };- if (onChange) onChange(values);- }, [imageFileList, videoFile, value]);+ }+ if (onChange)+ onChange(values)+ }, [imageFileList, videoFile, value])useEffect(() => {- setImageFileList(imageFileListValue ?? []);- }, [imageFileListValue]);+ setImageFileList(imageFileListValue ?? [])+ }, [imageFileListValue])useEffect(() => {- setValue(desValue || "");- }, [desValue]);+ setValue(desValue || '')+ }, [desValue])useEffect(() => {- setVideoFile(videoFileValue);- }, [videoFileValue]);+ setVideoFile(videoFileValue)+ }, [videoFileValue])const platConfig = useMemo(() => {- return AccountPlatInfoMap.get(platType)! || {};- }, [platType]);+ return AccountPlatInfoMap.get(platType)! || {}+ }, [platType])const imageMax = useMemo(() => {- return platConfig.commonPubParamsConfig?.imagesMax || 10;- }, [platConfig]);+ return platConfig.commonPubParamsConfig?.imagesMax || 10+ }, [platConfig])// 动态accept类型const uploadAccept = useMemo(() => {- const hasImage = imageFileList.length !== 0;- const hasVideo = !!videoFile;+ const hasImage = imageFileList.length !== 0+ const hasVideo = !!videoFileif (hasImage && !hasVideo && platConfig.pubTypes.has(PubType.ImageText))- return "image/*";+ return 'image/*'if (!hasImage && hasVideo && platConfig.pubTypes.has(PubType.VIDEO))- return "video/*";+ return 'video/*'if (- platConfig.pubTypes.has(PubType.ImageText) &&- platConfig.pubTypes.has(PubType.VIDEO)- )- return "video/*,image/*";- if (platConfig.pubTypes.has(PubType.ImageText)) return "image/*";- if (platConfig.pubTypes.has(PubType.VIDEO)) return "video/*";+ platConfig.pubTypes.has(PubType.ImageText)+ && platConfig.pubTypes.has(PubType.VIDEO)+ ) {+ return 'video/*,image/*'+ }+ if (platConfig.pubTypes.has(PubType.ImageText))+ return 'image/*'+ if (platConfig.pubTypes.has(PubType.VIDEO))+ return 'video/*'- return "video/*,image/*";- }, [imageFileList, videoFile, platConfig]);+ return 'video/*,image/*'+ }, [imageFileList, videoFile, platConfig])// 是否可见Draggerconst canShowDragger = useMemo(() => {- const imageCount = imageFileList.length;- const videoCount = videoFile ? 1 : 0;- const hasImage = imageCount > 0;- const hasVideo = videoCount > 0;-- if (hasImage && imageCount >= imageMax) return false;- if (hasVideo && videoCount >= videoMax) return false;+ const imageCount = imageFileList.length+ const videoCount = videoFile ? 1 : 0+ const hasImage = imageCount > 0+ const hasVideo = videoCount > 0++ if (hasImage && imageCount >= imageMax)+ return false+ if (hasVideo && videoCount >= videoMax)+ return false// 视频和图片都没有,或者只选一种且未到上限- return true;- }, [videoFile, imageMax, videoMax, videoFile]);+ return true+ }, [videoFile, imageMax, videoMax, videoFile])// 检查上传文件类型const checkFileListType = useCallback((fileList: File[]) => {- const hasImageInList = imageFileList.length !== 0;- const hasVideoInList = !!videoFile;- let uploadHasImage = false;- let uploadHasVideo = false;- let invalidFile = false;+ const hasImageInList = imageFileList.length !== 0+ const hasVideoInList = !!videoFile+ let uploadHasImage = false+ let uploadHasVideo = false+ let invalidFile = falsefor (const file of fileList) {- if (file.type.startsWith("image/")) {- uploadHasImage = true;- } else if (file.type.startsWith("video/")) {- uploadHasVideo = true;- } else {- invalidFile = true;+ if (file.type.startsWith('image/')) {+ uploadHasImage = true+ }+ else if (file.type.startsWith('video/')) {+ uploadHasVideo = true+ }+ else {+ invalidFile = true}}const messageOpen = (content: string) => {message.open({- content: content,- type: "warning",- key: "1",- });- };+ content,+ type: 'warning',+ key: '1',+ })+ }if (uploadHasImage && !platConfig.pubTypes.has(PubType.ImageText)) {- messageOpen(t("validation.uploadImage"));- return false;+ messageOpen(t('validation.uploadImage'))+ return false}if (uploadHasVideo && !platConfig.pubTypes.has(PubType.VIDEO)) {- messageOpen(t("validation.uploadVideo"));- return false;+ messageOpen(t('validation.uploadVideo'))+ return false}// 已有图片,只能传图片if (hasImageInList && !hasVideoInList && uploadHasVideo) {- messageOpen(t("validation.imageOnly"));- return false;+ messageOpen(t('validation.imageOnly'))+ return false}// 已有视频,只能传视频if (hasVideoInList && !hasImageInList && uploadHasImage) {- messageOpen(t("validation.videoOnly"));- return false;+ messageOpen(t('validation.videoOnly'))+ return false}// 混合上传拦截if (- (uploadHasImage && uploadHasVideo) ||- (hasImageInList && uploadHasVideo) ||- (hasVideoInList && uploadHasImage)+ (uploadHasImage && uploadHasVideo)+ || (hasImageInList && uploadHasVideo)+ || (hasVideoInList && uploadHasImage)) {- messageOpen(t("validation.imageVideoMixed"));- return false;+ messageOpen(t('validation.imageVideoMixed'))+ return false}// 非法类型if (invalidFile) {- messageOpen(t("validation.onlyImageOrVideo"));- return false;+ messageOpen(t('validation.onlyImageOrVideo'))+ return false}if (uploadHasVideo) {// 视频条数限制- const totalVideoCount =- (videoFile ? 1 : 0) +- fileList.filter((f) => f.type.startsWith("video/")).length;+ const totalVideoCount+ = (videoFile ? 1 : 0)+ + fileList.filter(f => f.type.startsWith('video/')).lengthif (totalVideoCount > videoMax) {messageOpen(- t("validation.videoMaxExceeded", { maxCount: videoMax }),- );- return false;+ t('validation.videoMaxExceeded', { maxCount: videoMax }),+ )+ return false}}if (uploadHasImage) {// 图片条数限制- const totalImageCount =- imageFileList.length +- fileList.filter((f) => f.type.startsWith("image/")).length;+ const totalImageCount+ = imageFileList.length+ + fileList.filter(f => f.type.startsWith('image/')).lengthif (totalImageCount > imageMax) {messageOpen(- t("validation.imageMaxExceeded", { maxCount: imageMax }),- );- return false;+ t('validation.imageMaxExceeded', { maxCount: imageMax }),+ )+ return false}}- return true;+ return true},[imageFileList, videoMax, imageMax, videoFile, platConfig],- );+ )const desMax = useMemo(() => {- return platConfig.commonPubParamsConfig?.desMax || 2200;- }, [platConfig]);+ return platConfig.commonPubParamsConfig?.desMax || 2200+ }, [platConfig])return (<>@@ -286,25 +297,26 @@ const PubParmasTextarea = memo(value={videoFile?.cover}onChoosed={(newCover) => {setVideoFile((prevState) => {- const newState = { ...(prevState as IVideoFile) };- newState.cover = newCover;- return newState;- });+ const newState = { ...(prevState as IVideoFile) }+ newState.cover = newCover+ return newState+ })}}/><Imagesrc={(previewData as IImgFile)?.imgUrl}style={{- width: "100%",- height: "400px",- objectFit: "contain",- display: "none",+ width: '100%',+ height: '400px',+ objectFit: 'contain',+ display: 'none',}}preview={{visible: !!(previewData && (previewData as IImgFile).imgUrl),onVisibleChange: (visible) => {- if (!visible) setPreviewData(undefined);+ if (!visible)+ setPreviewData(undefined)},}}/>@@ -316,10 +328,10 @@ const PubParmasTextarea = memo(<ImageEditorModalonOk={(editedImg) => {setImageFileList((prevState) => {- const newState = [...prevState];- newState[editImgIndex] = editedImg;- return newState;- });+ const newState = [...prevState]+ newState[editImgIndex] = editedImg+ return newState+ })}}imgFile={imageFileList[editImgIndex]}open={editImgIndex !== -1}@@ -331,8 +343,8 @@ const PubParmasTextarea = memo({beforeExtend}<PubParmasMentionInputvalue={value}- onChange={(value) => setValue(value)}- placeholder={t("form.descriptionPlaceholder")}+ onChange={value => setValue(value)}+ placeholder={t('form.descriptionPlaceholder')}maxLength={desMax}/><ReactSortable@@ -341,10 +353,10 @@ const PubParmasTextarea = memo(animation={250}setList={(newList) => {if (isFirst.current.sort) {- isFirst.current.sort = false;- return;+ isFirst.current.sort = false+ return}- setImageFileList(newList);+ setImageFileList(newList)}}scrollSensitivity={100}scrollSpeed={15}@@ -368,22 +380,22 @@ const PubParmasTextarea = memo(><PubParmasTextuploadImageonEditClick={() => {- setEditImgIndex(i);+ setEditImgIndex(i)}}imageFile={v}onClick={() => {- setPreviewData(v);+ setPreviewData(v)}}onClose={() => {- const targetImage = imageFileList[i];+ const targetImage = imageFileList[i]if (targetImage?.uploadTaskId) {- cancelUpload(targetImage.uploadTaskId);+ cancelUpload(targetImage.uploadTaskId)}setImageFileList((prevState) => {- const newState = [...prevState];- newState.splice(i, 1);- return newState;- });+ const newState = [...prevState]+ newState.splice(i, 1)+ return newState+ })}}/></CSSTransition>@@ -405,7 +417,7 @@ const PubParmasTextarea = memo(<divclassName="pubParmasTextarea-uploads-item"onClick={() => {- setPreviewData(videoFile);+ setPreviewData(videoFile)}}>{videoFile?.uploadTaskIds?.video && (@@ -417,20 +429,20 @@ const PubParmasTextarea = memo(<divclassName="pubParmasTextarea-uploads-item-close"onClick={(e) => {- e.stopPropagation();- const uploadIds = videoFile?.uploadTaskIds;+ e.stopPropagation()+ const uploadIds = videoFile?.uploadTaskIdsif (uploadIds?.video) {- cancelUpload(uploadIds.video);+ cancelUpload(uploadIds.video)}if (uploadIds?.cover) {- cancelUpload(uploadIds.cover);+ cancelUpload(uploadIds.cover)}- setVideoFile(undefined);+ setVideoFile(undefined)}}><CloseOutlined /></div>- <Tooltip title={t("actions.preview")}>+ <Tooltip title={t('actions.preview')}><div className="pubParmasTextarea-uploads-item-video"><img src={v.cover?.imgUrl} /><div className="pubParmasTextarea-uploads-item-play">@@ -440,7 +452,7 @@ const PubParmasTextarea = memo(</Tooltip></div></CSSTransition>- );+ )})}{canShowDragger && (@@ -461,45 +473,46 @@ const PubParmasTextarea = memo(onVideoUpdateFinish={(video) => {setVideoFile((prevState) => {if (prevState) {- const prevIds = prevState.uploadTaskIds ?? {};- const nextIds = video?.uploadTaskIds ?? {};+ const prevIds = prevState.uploadTaskIds ?? {}+ const nextIds = video?.uploadTaskIds ?? {}if (- prevIds.video &&- prevIds.video !== nextIds.video+ prevIds.video+ && prevIds.video !== nextIds.video) {- cancelUpload(prevIds.video);+ cancelUpload(prevIds.video)}if (- prevIds.cover &&- prevIds.cover !== nextIds.cover+ prevIds.cover+ && prevIds.cover !== nextIds.cover) {- cancelUpload(prevIds.cover);+ cancelUpload(prevIds.cover)}}- return video;- });+ return video+ })}}onImgUpdateFinish={(imgs) => {setImageFileList((prevState) => {- const next = [...prevState];+ const next = [...prevState]imgs.forEach((img) => {const index = next.findIndex(- (item) => item.id === img.id,- );+ item => item.id === img.id,+ )if (index !== -1) {- next[index] = img;- } else {- next.push(img);+ next[index] = img+ }+ else {+ next.push(img)}- });+ })- return next;- });+ return next+ })}}/></CSSTransition>@@ -510,10 +523,10 @@ const PubParmasTextarea = memo({/* 裁剪 */}{videoFile && (<Button- style={{ marginTop: "10px" }}+ style={{ marginTop: '10px' }}onClick={() => setVideoCoverSetingModal(true)}>- {t("actions.cropCover")}+ {t('actions.cropCover')}</Button>)}</div>@@ -527,11 +540,11 @@ const PubParmasTextarea = memo(icon={<FileTextOutlined />}type="text"onClick={(e) => {- e.stopPropagation();- setDraftModalOpen(true);+ e.stopPropagation()+ setDraftModalOpen(true)}}>- {t("actions.selectDraft")}+ {t('actions.selectDraft')}</Button></div><div className="pubParmasTextarea-footer-options-left-item">@@ -540,11 +553,11 @@ const PubParmasTextarea = memo(icon={<Aibrush />}type="text"onClick={(e) => {- e.stopPropagation();- setOpenLeft(true);+ e.stopPropagation()+ setOpenLeft(true)}}>- {t("writingAssistant")}+ {t('writingAssistant')}</Button></div></div>@@ -565,9 +578,9 @@ const PubParmasTextarea = memo(/></div></>- );+ )},),-);+)-export default PubParmasTextarea;+export default PubParmasTextareadiff --git a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/pubCommonComps.module.scss b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/pubCommonComps.module.scssindex f95c2c39..c47e7ba6 100644--- a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/pubCommonComps.module.scss+++ b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/pubCommonComps.module.scss@@ -197,7 +197,6 @@ $boxHegiht: 110px;transform: translateY(-50%);right: 15px;}-}&-extend {@@ -217,7 +216,9 @@ $boxHegiht: 110px;.itemEnterActive {opacity: 1;transform: scale(1);- transition: opacity 300ms, transform 300ms;+ transition:+ opacity 300ms,+ transform 300ms;}.itemExit {@@ -228,5 +229,7 @@ $boxHegiht: 110px;.itemExitActive {opacity: 0;transform: scale(0.8);- transition: opacity 300ms, transform 300ms;-}\ No newline at end of file+ transition:+ opacity 300ms,+ transform 300ms;+}diff --git a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/videoCoverSeting.module.scss b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/videoCoverSeting.module.scssindex 64afc623..711a0038 100644--- a/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/videoCoverSeting.module.scss+++ b/project/web/src/components/PublishDialog/compoents/PubParmasTextarea/videoCoverSeting.module.scss@@ -10,7 +10,8 @@.imgChoose {height: 100%;}- .videoCoverSeting-img, img {+ .videoCoverSeting-img,+ img {width: 100%;height: 100%;}diff --git a/project/web/src/components/PublishDialog/compoents/PublishDialogAi.tsx b/project/web/src/components/PublishDialog/compoents/PublishDialogAi.tsxindex 9106a6b6..186449c2 100644--- a/project/web/src/components/PublishDialog/compoents/PublishDialogAi.tsx+++ b/project/web/src/components/PublishDialog/compoents/PublishDialogAi.tsx@@ -1,13 +1,14 @@-import { ForwardedRef, forwardRef, memo } from "react";-import styles from "../publishDialog.module.scss";-import Chat from "@/components/Chat";-import { useTransClient } from "@/app/i18n/client";-import { CloseCircleFilled } from "@ant-design/icons";+import type { ForwardedRef } from 'react'+import { CloseCircleFilled } from '@ant-design/icons'+import { forwardRef, memo } from 'react'+import { useTransClient } from '@/app/i18n/client'+import Chat from '@/components/Chat'+import styles from '../publishDialog.module.scss'export interface IPublishDialogAiRef {}export interface IPublishDialogAiProps {- onClose: () => void;+ onClose: () => void}// AI写作@@ -17,21 +18,21 @@ const PublishDialogAi = memo({ onClose }: IPublishDialogAiProps,ref: ForwardedRef<IPublishDialogAiRef>,) => {- const { t } = useTransClient("publish");+ const { t } = useTransClient('publish')return (<div className={styles.publishDialogAi} id="publishDialogAi"><h1>- <span>{t("writingAssistant")}</span>+ <span>{t('writingAssistant')}</span><CloseCircleFilled onClick={onClose} /></h1><div className="publishDialogAi-wrapper"><Chat /></div></div>- );+ )},),-);+)-export default PublishDialogAi;+export default PublishDialogAidiff --git a/project/web/src/components/PublishDialog/compoents/PublishDialogDataPicker.tsx b/project/web/src/components/PublishDialog/compoents/PublishDialogDataPicker.tsxindex 39ce1aa7..785fff59 100644--- a/project/web/src/components/PublishDialog/compoents/PublishDialogDataPicker.tsx+++ b/project/web/src/components/PublishDialog/compoents/PublishDialogDataPicker.tsx@@ -1,11 +1,12 @@-import { ForwardedRef, forwardRef, memo, useMemo } from "react";-import { DatePicker } from "antd";-import type { DatePickerProps, GetProps } from "antd";-import dayjs from "dayjs";-import { usePublishDialog } from "@/components/PublishDialog/usePublishDialog";-import { useShallow } from "zustand/react/shallow";+import type { DatePickerProps, GetProps } from 'antd'+import type { ForwardedRef } from 'react'+import { DatePicker } from 'antd'+import dayjs from 'dayjs'+import { forwardRef, memo, useMemo } from 'react'+import { useShallow } from 'zustand/react/shallow'+import { usePublishDialog } from '@/components/PublishDialog/usePublishDialog'-type RangePickerProps = GetProps<typeof DatePicker.RangePicker>;+type RangePickerProps = GetProps<typeof DatePicker.RangePicker>export interface IPublishDialogDataPickerRef {}@@ -15,89 +16,94 @@ export interface IPublishDialogDataPickerProps {}const PublishDialogDataPicker = memo(forwardRef((- {}: IPublishDialogDataPickerProps,+ _: IPublishDialogDataPickerProps,ref: ForwardedRef<IPublishDialogDataPickerRef>,) => {const { pubTime, setPubTime } = usePublishDialog(- useShallow((state) => ({+ useShallow(state => ({pubTime: state.pubTime,setPubTime: state.setPubTime,})),- );+ )// 禁用今天之前的日期const disabledDate = (current: dayjs.Dayjs) => {- return current && current < dayjs().startOf("day");- };+ return current && current < dayjs().startOf('day')+ }// 禁用当前时间之前和当前时间半小时内的时间(只精确到分钟,不考虑秒)const disabledDateTime = (current: dayjs.Dayjs | null) => {- if (!current) return {};+ if (!current)+ return {}- const now = dayjs();- const minTime = now.add(20, "minute");+ const now = dayjs()+ const minTime = now.add(20, 'minute')// 只对今天限制- if (current.isSame(now, "day")) {- const minHour = minTime.hour();- const minMinute = minTime.minute();+ if (current.isSame(now, 'day')) {+ const minHour = minTime.hour()+ const minMinute = minTime.minute()// 禁用小时const disabledHours = () => {- const hours: number[] = [];+ const hours: number[] = []for (let i = 0; i < 24; i++) {- if (i < minHour) hours.push(i);+ if (i < minHour)+ hours.push(i)}- return hours;- };+ return hours+ }// 禁用分钟const disabledMinutes = (selectedHour: number) => {- const minutes: number[] = [];+ const minutes: number[] = []if (selectedHour === minHour) {for (let i = 0; i < minMinute; i++) {- minutes.push(i);+ minutes.push(i)}- } else if (selectedHour < minHour) {+ }+ else if (selectedHour < minHour) {// 小时都禁用了,分钟全部禁用for (let i = 0; i < 60; i++) {- minutes.push(i);+ minutes.push(i)}}- return minutes;- };+ return minutes+ }return {disabledHours,disabledMinutes,- };+ }}// 非今天不限制- return {};- };+ return {}+ }const pubTimeValue = useMemo(() => {if (pubTime) {- return dayjs(pubTime);+ return dayjs(pubTime)}- }, [pubTime]);+ }, [pubTime])- return pubTime ? (- <DatePicker- value={pubTimeValue}- showTime={{ format: "HH:mm" }}- allowClear={false}- disabledDate={disabledDate}- disabledTime={disabledDateTime}- onChange={(value) => {- setPubTime(value ? value.format() : undefined);- }}- />- ) : (- <div />- );+ return pubTime+ ? (+ <DatePicker+ value={pubTimeValue}+ showTime={{ format: 'HH:mm' }}+ allowClear={false}+ disabledDate={disabledDate}+ disabledTime={disabledDateTime}+ onChange={(value) => {+ setPubTime(value ? value.format() : undefined)+ }}+ />+ )+ : (+ <div />+ )},),-);+)-export default PublishDialogDataPicker;+export default PublishDialogDataPickerdiff --git a/project/web/src/components/PublishDialog/compoents/PublishDialogPreview.tsx b/project/web/src/components/PublishDialog/compoents/PublishDialogPreview.tsxindex f98756df..b09d0dfd 100644--- a/project/web/src/components/PublishDialog/compoents/PublishDialogPreview.tsx+++ b/project/web/src/components/PublishDialog/compoents/PublishDialogPreview.tsx@@ -1,35 +1,38 @@-import { ForwardedRef, forwardRef, memo, useEffect, useRef } from "react";-import styles from "../publishDialog.module.scss";-import { Empty } from "antd";-import { usePublishDialog } from "@/components/PublishDialog/usePublishDialog";-import { useShallow } from "zustand/react/shallow";-import { Swiper, SwiperSlide } from "swiper/react";-import { Navigation, Pagination } from "swiper/modules";-import { useTranslation } from "react-i18next";-import "swiper/css";-import "swiper/css/pagination";+import type { ForwardedRef } from 'react'+import { Empty } from 'antd'+import { forwardRef, memo, useEffect, useRef } from 'react'+import { useTranslation } from 'react-i18next'+import { Navigation, Pagination } from 'swiper/modules'+import { Swiper, SwiperSlide } from 'swiper/react'+import { useShallow } from 'zustand/react/shallow'+import { usePublishDialog } from '@/components/PublishDialog/usePublishDialog'+import styles from '../publishDialog.module.scss'+import 'swiper/css'+import 'swiper/css/pagination'// 格式化文件大小-const formatFileSize = (bytes: number): string => {- if (bytes === 0) return '0 Bytes';- const k = 1024;- const sizes = ['Bytes', 'KB', 'MB', 'GB'];- const i = Math.floor(Math.log(bytes) / Math.log(k));- return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];-};+function formatFileSize(bytes: number): string {+ if (bytes === 0)+ return '0 Bytes'+ const k = 1024+ const sizes = ['Bytes', 'KB', 'MB', 'GB']+ const i = Math.floor(Math.log(bytes) / Math.log(k))+ return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`+}// 格式化时长-const formatDuration = (seconds: number): string => {- const hours = Math.floor(seconds / 3600);- const minutes = Math.floor((seconds % 3600) / 60);- const secs = Math.floor(seconds % 60);-+function formatDuration(seconds: number): string {+ const hours = Math.floor(seconds / 3600)+ const minutes = Math.floor((seconds % 3600) / 60)+ const secs = Math.floor(seconds % 60)+if (hours > 0) {- return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;- } else {- return `${minutes}:${secs.toString().padStart(2, '0')}`;+ return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`+ }+ else {+ return `${minutes}:${secs.toString().padStart(2, '0')}`}-};+}export interface IPublishDialogPreviewRef {}@@ -39,131 +42,143 @@ export interface IPublishDialogPreviewProps {}const PublishDialogPreview = memo(forwardRef((- {}: IPublishDialogPreviewProps,+ _: IPublishDialogPreviewProps,ref: ForwardedRef<IPublishDialogPreviewRef>,) => {- const { t } = useTranslation("publish");+ const { t } = useTranslation('publish')const { expandedPubItem } = usePublishDialog(- useShallow((state) => ({+ useShallow(state => ({expandedPubItem: state.expandedPubItem,pubList: state.pubList,})),- );- const videoRef = useRef<HTMLVideoElement>(null);+ )+ const videoRef = useRef<HTMLVideoElement>(null)useEffect(() => {if (!expandedPubItem) {- videoRef.current?.pause();+ videoRef.current?.pause()}- }, [expandedPubItem]);+ }, [expandedPubItem])return (<div className={styles.publishDialogPreview}><div className="publishDialogPreview-wrapper"><div className="publishDialogPreview-title">- {t("preview.title")}+ {t('preview.title')}</div>- {expandedPubItem &&- (expandedPubItem?.params.video ||- (expandedPubItem?.params.images &&- expandedPubItem?.params.images?.length !== 0)) ? (- <div className="publishDialogPreview-preview">- {expandedPubItem?.params.video ? (- <div className="publishDialogPreview-preview-video">- <div className="publishDialogPreview-preview-video-wrapper">- <div className="publishDialogPreview-preview-video-top" />- <video- ref={videoRef}- src={expandedPubItem.params.video?.videoUrl}- controls- poster={expandedPubItem.params.video?.cover?.imgUrl}- />- {/* 视频信息显示 */}- <div className="publishDialogPreview-video-info" style={{ color: '#fff', fontSize: '11px' }}>- <div className="publishDialogPreview-video-info-item">- <span className="publishDialogPreview-video-info-label">{t('preview.videoInfo.filename' as any)}:</span>- <span className="publishDialogPreview-video-info-value">- {expandedPubItem.params.video?.filename || 'Unknown'}- </span>- </div>- <div className="publishDialogPreview-video-info-item">- <span className="publishDialogPreview-video-info-label">{t('preview.videoInfo.format' as any)}:</span>- <span className="publishDialogPreview-video-info-value">- {expandedPubItem.params.video?.filename?.split('.').pop()?.toUpperCase() || 'Unknown'}- </span>- </div>- <div className="publishDialogPreview-video-info-item">- <span className="publishDialogPreview-video-info-label">{t('preview.videoInfo.resolution' as any)}:</span>- <span className="publishDialogPreview-video-info-value">- {expandedPubItem.params.video?.width && expandedPubItem.params.video?.height- ? `${expandedPubItem.params.video.width}x${expandedPubItem.params.video.height}`- : 'Unknown'- }- </span>+ {expandedPubItem+ && (expandedPubItem?.params.video+ || (expandedPubItem?.params.images+ && expandedPubItem?.params.images?.length !== 0)) ? (+ <div className="publishDialogPreview-preview">+ {expandedPubItem?.params.video ? (+ <div className="publishDialogPreview-preview-video">+ <div className="publishDialogPreview-preview-video-wrapper">+ <div className="publishDialogPreview-preview-video-top" />+ <video+ ref={videoRef}+ src={expandedPubItem.params.video?.videoUrl}+ controls+ poster={expandedPubItem.params.video?.cover?.imgUrl}+ />+ {/* 视频信息显示 */}+ <div className="publishDialogPreview-video-info" style={{ color: '#fff', fontSize: '11px' }}>+ <div className="publishDialogPreview-video-info-item">+ <span className="publishDialogPreview-video-info-label">+ {t('preview.videoInfo.filename' as any)}+ :+ </span>+ <span className="publishDialogPreview-video-info-value">+ {expandedPubItem.params.video?.filename || 'Unknown'}+ </span>+ </div>+ <div className="publishDialogPreview-video-info-item">+ <span className="publishDialogPreview-video-info-label">+ {t('preview.videoInfo.format' as any)}+ :+ </span>+ <span className="publishDialogPreview-video-info-value">+ {expandedPubItem.params.video?.filename?.split('.').pop()?.toUpperCase() || 'Unknown'}+ </span>+ </div>+ <div className="publishDialogPreview-video-info-item">+ <span className="publishDialogPreview-video-info-label">+ {t('preview.videoInfo.resolution' as any)}+ :+ </span>+ <span className="publishDialogPreview-video-info-value">+ {expandedPubItem.params.video?.width && expandedPubItem.params.video?.height+ ? `${expandedPubItem.params.video.width}x${expandedPubItem.params.video.height}`+ : 'Unknown'}+ </span>+ </div>+ <div className="publishDialogPreview-video-info-item">+ <span className="publishDialogPreview-video-info-label">+ {t('preview.videoInfo.size' as any)}+ :+ </span>+ <span className="publishDialogPreview-video-info-value">+ {expandedPubItem.params.video?.size+ ? formatFileSize(expandedPubItem.params.video.size)+ : 'Unknown'}+ </span>+ </div>+ <div className="publishDialogPreview-video-info-item">+ <span className="publishDialogPreview-video-info-label">+ {t('preview.videoInfo.duration' as any)}+ :+ </span>+ <span className="publishDialogPreview-video-info-value">+ {expandedPubItem.params.video?.duration+ ? formatDuration(expandedPubItem.params.video.duration)+ : 'Unknown'}+ </span>+ </div>+ </div></div>- <div className="publishDialogPreview-video-info-item">- <span className="publishDialogPreview-video-info-label">{t('preview.videoInfo.size' as any)}:</span>- <span className="publishDialogPreview-video-info-value">- {expandedPubItem.params.video?.size- ? formatFileSize(expandedPubItem.params.video.size)- : 'Unknown'- }- </span>- </div>- <div className="publishDialogPreview-video-info-item">- <span className="publishDialogPreview-video-info-label">{t('preview.videoInfo.duration' as any)}:</span>- <span className="publishDialogPreview-video-info-value">- {expandedPubItem.params.video?.duration- ? formatDuration(expandedPubItem.params.video.duration)- : 'Unknown'- }- </span>+ </div>+ ) : (+ <div className="publishDialogPreview-preview-video">+ <div className="publishDialogPreview-preview-video-wrapper">+ <div className="publishDialogPreview-preview-video-top" />+ <div className="publishDialogPreview-preview-images">+ <Swiper+ loop={+ (expandedPubItem!.params.images?.length || 0) > 1+ }+ modules={[Navigation, Pagination]}+ pagination={{+ clickable: true,+ el: '.swiper-pagination',+ }}+ >+ {expandedPubItem!.params.images!.map(+ (image, index) => (+ <SwiperSlide key={index + image.imgUrl}>+ <img+ src={image.imgUrl}+ alt={`Image ${index + 1}`}+ />+ </SwiperSlide>+ ),+ )}+ </Swiper>+ <div className="swiper-pagination"></div>+ </div></div></div>- </div>+ )}</div>) : (- <div className="publishDialogPreview-preview-video">- <div className="publishDialogPreview-preview-video-wrapper">- <div className="publishDialogPreview-preview-video-top" />- <div className="publishDialogPreview-preview-images">- <Swiper- loop={- (expandedPubItem!.params.images?.length || 0) > 1- }- modules={[Navigation, Pagination]}- pagination={{- clickable: true,- el: ".swiper-pagination",- }}- >- {expandedPubItem!.params.images!.map(- (image, index) => (- <SwiperSlide key={index + image.imgUrl}>- <img- src={image.imgUrl}- alt={`Image ${index + 1}`}- />- </SwiperSlide>- ),- )}- </Swiper>- <div className="swiper-pagination"></div>- </div>- </div>+ <div className="publishDialogPreview-empty">+ <Empty description={t('preview.emptyDescription')} /></div>)}- </div>- ) : (- <div className="publishDialogPreview-empty">- <Empty description={t("preview.emptyDescription")} />- </div>- )}</div></div>- );+ )},),-);+)-export default PublishDialogPreview;+export default PublishDialogPreviewdiff --git a/project/web/src/components/PublishDialog/compoents/PublishManageUpload/PublishUploadProgress.tsx b/project/web/src/components/PublishDialog/compoents/PublishManageUpload/PublishUploadProgress.tsxindex a3b3835b..0277ab88 100644--- a/project/web/src/components/PublishDialog/compoents/PublishManageUpload/PublishUploadProgress.tsx+++ b/project/web/src/components/PublishDialog/compoents/PublishManageUpload/PublishUploadProgress.tsx@@ -1,23 +1,23 @@-import type { ReactNode } from "react";-import { forwardRef, memo, useMemo } from "react";-import styles from "./publishUploadProgress.module.scss";-import { usePublishManageUpload } from "@/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload";-import { Tooltip, Progress } from "antd";-import { CheckOutlined, CloseOutlined } from "@ant-design/icons";-import { UploadTaskStatusEnum } from "./publishManageUpload.enum";-import { useTransClient } from "@/app/i18n/client";+import type { ReactNode } from 'react'+import { CheckOutlined, CloseOutlined } from '@ant-design/icons'+import { Progress, Tooltip } from 'antd'+import { forwardRef, memo, useMemo } from 'react'+import { useTransClient } from '@/app/i18n/client'+import { usePublishManageUpload } from '@/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload'+import { UploadTaskStatusEnum } from './publishManageUpload.enum'+import styles from './publishUploadProgress.module.scss'-export type IPublishUploadProgressRef = HTMLDivElement;+export type IPublishUploadProgressRef = HTMLDivElementexport interface IPublishUploadProgressProps {- taskId: string;+ taskId: string}const PublishUploadProgress = memo(forwardRef<IPublishUploadProgressRef, IPublishUploadProgressProps>(({ taskId }, ref) => {- const task = usePublishManageUpload((state) => state.tasks[taskId]);- const { t } = useTransClient("publish");+ const task = usePublishManageUpload(state => state.tasks[taskId])+ const { t } = useTransClient('publish')const {percent,@@ -29,80 +29,83 @@ const PublishUploadProgress = memo(} = useMemo(() => {const defaultResult = {percent: 0,- tooltipTitle: "",- progressStatus: "normal" as "normal" | "success" | "exception",+ tooltipTitle: '',+ progressStatus: 'normal' as 'normal' | 'success' | 'exception',format: undefined as ((percent?: number) => ReactNode) | undefined,- strokeColor: "var(--theColor5)",+ strokeColor: 'var(--theColor5)',showText: false,- };+ }if (!task) {- return defaultResult;+ return defaultResult}const clampPercent = (value: number) => {- if (Number.isNaN(value)) return 0;- return Math.min(100, Math.max(0, value));- };+ if (Number.isNaN(value))+ return 0+ return Math.min(100, Math.max(0, value))+ }- let computedPercent = clampPercent(task.progress ?? 0);- let status: "normal" | "success" | "exception" = "normal";- let format: ((percent?: number) => ReactNode) | undefined;- let strokeColor = "var(--theColor5)";- let showText = false;+ let computedPercent = clampPercent(task.progress ?? 0)+ let status: 'normal' | 'success' | 'exception' = 'normal'+ let format: ((percent?: number) => ReactNode) | undefined+ let strokeColor = 'var(--theColor5)'+ let showText = falseconst ensureMinimum = () => {if (computedPercent <= 0) {- computedPercent = 8;+ computedPercent = 8}- };+ }switch (task.status) {case UploadTaskStatusEnum.Hashing:case UploadTaskStatusEnum.Pending:case UploadTaskStatusEnum.Uploading:- ensureMinimum();- break;+ ensureMinimum()+ breakcase UploadTaskStatusEnum.Success:- computedPercent = 100;- status = "success";- format = () => <CheckOutlined style={{ fontSize: 12 }} />;- strokeColor = "var(--theColor5)";- showText = true;- break;+ computedPercent = 100+ status = 'success'+ format = () => <CheckOutlined style={{ fontSize: 12 }} />+ strokeColor = 'var(--theColor5)'+ showText = true+ breakcase UploadTaskStatusEnum.Error:- status = "exception";- format = () => <CloseOutlined style={{ fontSize: 12 }} />;- strokeColor = "var(--theColor8)";- showText = true;- break;+ status = 'exception'+ format = () => <CloseOutlined style={{ fontSize: 12 }} />+ strokeColor = 'var(--theColor8)'+ showText = true+ breakcase UploadTaskStatusEnum.Canceled:- status = "exception";- strokeColor = "var(--theColor8)";- break;+ status = 'exception'+ strokeColor = 'var(--theColor8)'+ breakdefault:- break;+ break}if (task.fromCache) {- computedPercent = 100;- status = "success";- format = () => <CheckOutlined style={{ fontSize: 12 }} />;- strokeColor = "var(--theColor5)";- showText = true;+ computedPercent = 100+ status = 'success'+ format = () => <CheckOutlined style={{ fontSize: 12 }} />+ strokeColor = 'var(--theColor5)'+ showText = true}- const displayPercent = Math.round(clampPercent(computedPercent));- let tooltipTitle: string = t("upload.progress", {+ const displayPercent = Math.round(clampPercent(computedPercent))+ let tooltipTitle: string = t('upload.progress', {percent: displayPercent,- });+ })if (task.status === UploadTaskStatusEnum.Success || task.fromCache) {- tooltipTitle = t("upload.completed");- } else if (task.status === UploadTaskStatusEnum.Error) {- tooltipTitle = t("upload.failed");- } else if (task.status === UploadTaskStatusEnum.Canceled) {- tooltipTitle = t("upload.canceled");+ tooltipTitle = t('upload.completed')+ }+ else if (task.status === UploadTaskStatusEnum.Error) {+ tooltipTitle = t('upload.failed')+ }+ else if (task.status === UploadTaskStatusEnum.Canceled) {+ tooltipTitle = t('upload.canceled')}return {@@ -112,11 +115,11 @@ const PublishUploadProgress = memo(format,strokeColor,showText,- };- }, [task]);+ }+ }, [task])if (!task) {- return null;+ return null}return (@@ -136,9 +139,9 @@ const PublishUploadProgress = memo(</div></div></Tooltip>- );+ )},),-);+)-export default PublishUploadProgress;+export default PublishUploadProgressdiff --git a/project/web/src/components/PublishDialog/compoents/PublishManageUpload/publishManageUpload.enum.ts b/project/web/src/components/PublishDialog/compoents/PublishManageUpload/publishManageUpload.enum.tsindex c8ec4565..377caba3 100644--- a/project/web/src/components/PublishDialog/compoents/PublishManageUpload/publishManageUpload.enum.ts+++ b/project/web/src/components/PublishDialog/compoents/PublishManageUpload/publishManageUpload.enum.ts@@ -1,14 +1,14 @@export enum UploadTaskStatusEnum {- Hashing = "hashing",- Pending = "pending",- Uploading = "uploading",- Success = "success",- Error = "error",- Canceled = "canceled",+ Hashing = 'hashing',+ Pending = 'pending',+ Uploading = 'uploading',+ Success = 'success',+ Error = 'error',+ Canceled = 'canceled',}export enum UploadTaskTypeEnum {- Image = "image",- Video = "video",- VideoCover = "videoCover",+ Image = 'image',+ Video = 'video',+ VideoCover = 'videoCover',}diff --git a/project/web/src/components/PublishDialog/compoents/PublishManageUpload/publishUploadProgress.module.scss b/project/web/src/components/PublishDialog/compoents/PublishManageUpload/publishUploadProgress.module.scssindex b144158e..43c154e8 100644--- a/project/web/src/components/PublishDialog/compoents/PublishManageUpload/publishUploadProgress.module.scss+++ b/project/web/src/components/PublishDialog/compoents/PublishManageUpload/publishUploadProgress.module.scss@@ -12,7 +12,10 @@border: 1px solid rgba(255, 255, 255, 0.08);backdrop-filter: blur(4px);box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18);- transition: transform 0.15s ease, box-shadow 0.15s ease, background 0.15s ease;+ transition:+ transform 0.15s ease,+ box-shadow 0.15s ease,+ background 0.15s ease;&:hover {transform: translateY(-1px);diff --git a/project/web/src/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload.ts b/project/web/src/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload.tsindex 501e44bb..99e8c60c 100644--- a/project/web/src/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload.ts+++ b/project/web/src/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload.ts@@ -1,36 +1,36 @@-import lodash from "lodash";-import { create } from "zustand";-import { combine } from "zustand/middleware";-import { uploadToOss } from "@/api/oss";-import { OSS_URL } from "@/constant";-import {- UploadTask,+import type {+ IPublishManageUploadState,+ StartUploadOptions,UploadCacheItem,UploadResult,- StartUploadOptions,- IPublishManageUploadState,UploadRuntime,-} from "./usePublishManageUpload.type";-import { UploadTaskStatusEnum } from "./publishManageUpload.enum";+ UploadTask,+} from './usePublishManageUpload.type'+import lodash from 'lodash'+import { create } from 'zustand'+import { combine } from 'zustand/middleware'+import { uploadToOss } from '@/api/oss'import {computeFileMd5,createTaskId,isAbortError,-} from "@/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload.utils";+} from '@/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload.utils'+import { OSS_URL } from '@/constant'+import { UploadTaskStatusEnum } from './publishManageUpload.enum'// 仅定义状态形状,方法类型走类型推断const initialState: IPublishManageUploadState = {tasks: {},md5Cache: {},-};+}-const getStore = () => {- return lodash.cloneDeep(initialState);-};+function getStore() {+ return lodash.cloneDeep(initialState)+}-const uploadRuntimeMap = new Map<string, UploadRuntime>();-const taskMd5Map = new Map<string, string>();-const canceledTasks = new Set<string>();+const uploadRuntimeMap = new Map<string, UploadRuntime>()+const taskMd5Map = new Map<string, string>()+const canceledTasks = new Set<string>()// 管理发布弹框的上传任务(去重/进度/取消/缓存)export const usePublishManageUpload = create(@@ -44,21 +44,22 @@ export const usePublishManageUpload = create(updater: (task: UploadTask) => UploadTask | null,) => {set((state) => {- let mutated = false;- const nextTasks: Record<string, UploadTask> = { ...state.tasks };+ let mutated = false+ const nextTasks: Record<string, UploadTask> = { ...state.tasks }for (const [id, task] of Object.entries(state.tasks)) {- if (task.md5 !== md5) continue;- const updated = updater(task);+ if (task.md5 !== md5)+ continue+ const updated = updater(task)if (updated && updated !== task) {- nextTasks[id] = updated;- mutated = true;+ nextTasks[id] = updated+ mutated = true}}- return mutated ? { tasks: nextTasks } : state;- });- };+ return mutated ? { tasks: nextTasks } : state+ })+ }/*** 确保为同一个 MD5 创建并复用唯一 runtime@@ -66,76 +67,77 @@ export const usePublishManageUpload = create(* - 统一终止控制*/const ensureRuntime = (md5: string, file: Blob): UploadRuntime => {- let runtime = uploadRuntimeMap.get(md5);+ let runtime = uploadRuntimeMap.get(md5)if (runtime) {- return runtime;+ return runtime}- const controller = new AbortController();+ const controller = new AbortController()runtime = {controller,progress: 0,taskIds: new Set<string>(),completed: false,// 占位,实际 promise 下面会重写- promise: Promise.resolve({ ossKey: "", ossUrl: "" }),- };+ promise: Promise.resolve({ ossKey: '', ossUrl: '' }),+ }- uploadRuntimeMap.set(md5, runtime);+ uploadRuntimeMap.set(md5, runtime)runtime.promise = uploadToOss(file, {signal: controller.signal,onProgress: (prog) => {- runtime!.progress = prog;+ runtime!.progress = progupdateTasksForMd5(md5, (task) => {if (- task.status === UploadTaskStatusEnum.Canceled ||- task.status === UploadTaskStatusEnum.Error ||- task.status === UploadTaskStatusEnum.Success+ task.status === UploadTaskStatusEnum.Canceled+ || task.status === UploadTaskStatusEnum.Error+ || task.status === UploadTaskStatusEnum.Success) {- return null;+ return null}return {...task,status: UploadTaskStatusEnum.Uploading,progress: prog >= 100 ? 99 : prog,updatedAt: Date.now(),- };- });+ }+ })},}).then((ossKey) => {- runtime!.completed = true;+ runtime!.completed = trueconst result: UploadCacheItem = {ossKey,ossUrl: `${OSS_URL}${ossKey}`,- };+ }- set((state) => ({+ set(state => ({md5Cache: {...state.md5Cache,[md5]: result,},- }));+ }))- return result;+ return result}).catch((error) => {- runtime!.completed = true;- throw error;+ runtime!.completed = true+ throw error}).finally(() => {- uploadRuntimeMap.delete(md5);- });+ uploadRuntimeMap.delete(md5)+ })- return runtime;- };+ return runtime+ }/** 合并更新单个任务 */const finalizeTask = (taskId: string, patch: Partial<UploadTask>) => {set((state) => {- const task = state.tasks[taskId];- if (!task) return state;+ const task = state.tasks[taskId]+ if (!task)+ return statereturn {tasks: {...state.tasks,@@ -145,20 +147,21 @@ export const usePublishManageUpload = create(updatedAt: Date.now(),},},- };- });- };+ }+ })+ }/** 释放 runtime 的一个引用(最后一个释放会中止上传) */const releaseRuntime = (taskId: string, md5?: string) => {- if (!md5) return;- const runtime = uploadRuntimeMap.get(md5);- runtime?.taskIds.delete(taskId);+ if (!md5)+ return+ const runtime = uploadRuntimeMap.get(md5)+ runtime?.taskIds.delete(taskId)if (runtime && runtime.taskIds.size === 0 && !runtime.completed) {- runtime.controller.abort();+ runtime.controller.abort()}- };+ }// 将任务放到队列const enqueueUpload = ({@@ -167,10 +170,10 @@ export const usePublishManageUpload = create(fileName,taskId: providedTaskId,}: StartUploadOptions) => {- const taskId = providedTaskId ?? createTaskId();- const name = fileName ?? (file as File)?.name ?? "";+ const taskId = providedTaskId ?? createTaskId()+ const name = fileName ?? (file as File)?.name ?? ''- set((state) => ({+ set(state => ({tasks: {...state.tasks,[taskId]: {@@ -184,77 +187,79 @@ export const usePublishManageUpload = create(updatedAt: Date.now(),},},- }));+ }))const promise = (async (): Promise<UploadResult> => {- let currentMd5: string | undefined;+ let currentMd5: string | undefinedtry {- const md5 = await computeFileMd5(file);- currentMd5 = md5;+ const md5 = await computeFileMd5(file)+ currentMd5 = md5if (canceledTasks.has(taskId)) {- throw new DOMException("Upload canceled", "AbortError");+ throw new DOMException('Upload canceled', 'AbortError')}- taskMd5Map.set(taskId, md5);+ taskMd5Map.set(taskId, md5)finalizeTask(taskId, {md5,status: UploadTaskStatusEnum.Pending,- });+ })- const cache = get().md5Cache[md5];+ const cache = get().md5Cache[md5]if (cache) {- const result: UploadResult = { ...cache, fromCache: true };+ const result: UploadResult = { ...cache, fromCache: true }finalizeTask(taskId, {status: UploadTaskStatusEnum.Success,progress: 100,fromCache: true,- });- return result;+ })+ return result}- const runtime = ensureRuntime(md5, file);- runtime.taskIds.add(taskId);+ const runtime = ensureRuntime(md5, file)+ runtime.taskIds.add(taskId)if (runtime.progress > 0) {updateTasksForMd5(md5, (task) => {- if (task.id !== taskId) return null;+ if (task.id !== taskId)+ return nullif (- task.status === UploadTaskStatusEnum.Canceled ||- task.status === UploadTaskStatusEnum.Error+ task.status === UploadTaskStatusEnum.Canceled+ || task.status === UploadTaskStatusEnum.Error) {- return null;+ return null}return {...task,status: UploadTaskStatusEnum.Uploading,progress: runtime.progress >= 100 ? 99 : runtime.progress,updatedAt: Date.now(),- };- });+ }+ })}- const result = await runtime.promise;+ const result = await runtime.promiseif (canceledTasks.has(taskId)) {- throw new DOMException("Upload canceled", "AbortError");+ throw new DOMException('Upload canceled', 'AbortError')}const uploadResult: UploadResult = {...result,fromCache: false,- };+ }finalizeTask(taskId, {status: UploadTaskStatusEnum.Success,progress: 100,fromCache: false,- });+ })- return uploadResult;- } catch (error) {- const aborted = isAbortError(error);+ return uploadResult+ }+ catch (error) {+ const aborted = isAbortError(error)finalizeTask(taskId, {status: aborted@@ -262,70 +267,73 @@ export const usePublishManageUpload = create(: UploadTaskStatusEnum.Error,errorMessage:aborted || !(error instanceof Error) ? undefined : error.message,- });-- throw error;- } finally {- const md5 = currentMd5 ?? taskMd5Map.get(taskId);- releaseRuntime(taskId, md5);- taskMd5Map.delete(taskId);- canceledTasks.delete(taskId);+ })++ throw error}- })();+ finally {+ const md5 = currentMd5 ?? taskMd5Map.get(taskId)+ releaseRuntime(taskId, md5)+ taskMd5Map.delete(taskId)+ canceledTasks.delete(taskId)+ }+ })()const cancel = () => {if (canceledTasks.has(taskId)) {- return;+ return}- canceledTasks.add(taskId);+ canceledTasks.add(taskId)- const md5 = taskMd5Map.get(taskId);- releaseRuntime(taskId, md5);+ const md5 = taskMd5Map.get(taskId)+ releaseRuntime(taskId, md5)finalizeTask(taskId, {status: UploadTaskStatusEnum.Canceled,- });- };+ })+ }return {taskId,promise,cancel,- };- };+ }+ }return {...getStore(),enqueueUpload,cancelUpload: (taskId: string) => {- if (!taskId) return;- if (canceledTasks.has(taskId)) return;+ if (!taskId)+ return+ if (canceledTasks.has(taskId))+ return- canceledTasks.add(taskId);+ canceledTasks.add(taskId)- const md5 = taskMd5Map.get(taskId);- releaseRuntime(taskId, md5);+ const md5 = taskMd5Map.get(taskId)+ releaseRuntime(taskId, md5)finalizeTask(taskId, {status: UploadTaskStatusEnum.Canceled,- });+ })},removeTask: (taskId: string) => {- canceledTasks.delete(taskId);- taskMd5Map.delete(taskId);+ canceledTasks.delete(taskId)+ taskMd5Map.delete(taskId)set((state) => {if (!(taskId in state.tasks)) {- return state;+ return state}- const { [taskId]: _removed, ...rest } = state.tasks;- return { tasks: rest };- });+ const { [taskId]: _removed, ...rest } = state.tasks+ return { tasks: rest }+ })},updateTask: (taskId: string, patch: Partial<UploadTask>) => {- finalizeTask(taskId, patch);+ finalizeTask(taskId, patch)},- };+ }}),-);+)diff --git a/project/web/src/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload.type.ts b/project/web/src/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload.type.tsindex de574316..5e7255fe 100644--- a/project/web/src/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload.type.ts+++ b/project/web/src/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload.type.ts@@ -1,7 +1,7 @@-import {+import type {UploadTaskStatusEnum,UploadTaskTypeEnum,-} from "./publishManageUpload.enum";+} from './publishManageUpload.enum'/*** 上传任务状态机@@ -12,37 +12,37 @@ import {* - error: 上传失败* - canceled: 用户取消*/-export type UploadTaskStatus = UploadTaskStatusEnum;+export type UploadTaskStatus = UploadTaskStatusEnum/** 上传任务类型:图片/视频/视频封面 */-export type UploadTaskType = UploadTaskTypeEnum;+export type UploadTaskType = UploadTaskTypeEnum/*** 单个上传任务的状态记录(Zustand 中保存)*/export interface UploadTask {- id: string;- fileName: string;- size: number;- type: UploadTaskType;- status: UploadTaskStatus;- progress: number;- md5?: string;- fromCache?: boolean;- errorMessage?: string;- createdAt: number;- updatedAt: number;+ id: string+ fileName: string+ size: number+ type: UploadTaskType+ status: UploadTaskStatus+ progress: number+ md5?: string+ fromCache?: boolean+ errorMessage?: string+ createdAt: number+ updatedAt: number}/** 缓存项:按 MD5 复用上传结果 */export interface UploadCacheItem {- ossKey: string;- ossUrl: string;+ ossKey: string+ ossUrl: string}/** 返回给调用方的上传结果(包含是否命中缓存) */export interface UploadResult extends UploadCacheItem {- fromCache: boolean;+ fromCache: boolean}/**@@ -50,23 +50,23 @@ export interface UploadResult extends UploadCacheItem {* - 多任务复用相同 runtime(节省带宽)*/export interface UploadRuntime {- controller: AbortController;- promise: Promise<UploadCacheItem>;- progress: number;- taskIds: Set<string>;- completed: boolean;+ controller: AbortController+ promise: Promise<UploadCacheItem>+ progress: number+ taskIds: Set<string>+ completed: boolean}/** 新建上传任务的参数 */export interface StartUploadOptions {- file: Blob;- type: UploadTaskType;- fileName?: string;- taskId?: string;+ file: Blob+ type: UploadTaskType+ fileName?: string+ taskId?: string}/** 全局上传管理的状态 */export interface IPublishManageUploadState {- tasks: Record<string, UploadTask>;- md5Cache: Record<string, UploadCacheItem>;+ tasks: Record<string, UploadTask>+ md5Cache: Record<string, UploadCacheItem>}diff --git a/project/web/src/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload.utils.ts b/project/web/src/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload.utils.tsindex ebb76a82..da51e303 100644--- a/project/web/src/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload.utils.ts+++ b/project/web/src/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload.utils.ts@@ -1,27 +1,27 @@-import CryptoJS from "crypto-js";+import CryptoJS from 'crypto-js'/** 生成任务 ID(优先使用 crypto.randomUUID) */-export const createTaskId = () => {+export function createTaskId() {if (- typeof crypto !== "undefined" &&- typeof crypto.randomUUID === "function"+ typeof crypto !== 'undefined'+ && typeof crypto.randomUUID === 'function') {- return crypto.randomUUID();+ return crypto.randomUUID()}- return `upload_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;-};+ return `upload_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`+}/** 判断是否为中断错误 */-export const isAbortError = (error: unknown): boolean => {+export function isAbortError(error: unknown): boolean {if (error instanceof DOMException) {- return error.name === "AbortError";+ return error.name === 'AbortError'}- return Boolean((error as { name?: string })?.name === "AbortError");-};+ return Boolean((error as { name?: string })?.name === 'AbortError')+}/** 计算文件 MD5(用于去重与缓存键) */-export const computeFileMd5 = async (file: Blob): Promise<string> => {- const buffer = await file.arrayBuffer();- const wordArray = CryptoJS.lib.WordArray.create(new Uint8Array(buffer));- return CryptoJS.MD5(wordArray).toString();-};+export async function computeFileMd5(file: Blob): Promise<string> {+ const buffer = await file.arrayBuffer()+ const wordArray = CryptoJS.lib.WordArray.create(new Uint8Array(buffer))+ return CryptoJS.MD5(wordArray).toString()+}diff --git a/project/web/src/components/PublishDialog/hooks/usePubParamsVerify.tsx b/project/web/src/components/PublishDialog/hooks/usePubParamsVerify.tsxindex 6989b528..24285bfd 100644--- a/project/web/src/components/PublishDialog/hooks/usePubParamsVerify.tsx+++ b/project/web/src/components/PublishDialog/hooks/usePubParamsVerify.tsx@@ -1,25 +1,25 @@-import { memo, useMemo } from "react";-import { parseTopicString } from "@/utils";-import { AccountPlatInfoMap, PlatType } from "@/app/config/platConfig";-import { PubItem } from "@/components/PublishDialog/publishDialog.type";-import { Alert } from "antd";-import { useTransClient } from "@/app/i18n/client";-import { PubType } from "@/app/config/publishConfig";+import type { PubItem } from '@/components/PublishDialog/publishDialog.type'+import { Alert } from 'antd'+import { memo, useMemo } from 'react'+import { AccountPlatInfoMap, PlatType } from '@/app/config/platConfig'+import { PubType } from '@/app/config/publishConfig'+import { useTransClient } from '@/app/i18n/client'+import { UploadTaskStatusEnum } from '@/components/PublishDialog/compoents/PublishManageUpload/publishManageUpload.enum'+import { usePublishManageUpload } from '@/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload'import {- isAspectRatioMatch,isAspectRatioInRange,-} from "@/components/PublishDialog/PublishDialog.util";-import { usePublishManageUpload } from "@/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload";-import { UploadTaskStatusEnum } from "@/components/PublishDialog/compoents/PublishManageUpload/publishManageUpload.enum";+ isAspectRatioMatch,+} from '@/components/PublishDialog/PublishDialog.util'+import { parseTopicString } from '@/utils'export interface ErrPubParamsItem {// 参数错误提示消息- parErrMsg?: string;+ parErrMsg?: string// 错误状态- errStatus?: boolean;+ errStatus?: boolean}-export type ErrPubParamsMapType = Map<string | number, ErrPubParamsItem>;+export type ErrPubParamsMapType = Map<string | number, ErrPubParamsItem>/*** 发布参数校验是否复合平台规范@@ -27,154 +27,156 @@ export type ErrPubParamsMapType = Map<string | number, ErrPubParamsItem>;*/export default function usePubParamsVerify(data: PubItem[]) {// 用于判断描述中的话题是否符合规范- const descTopicRegex = /#\S+#\S+/;- const { t } = useTransClient("publish");- const tasks = usePublishManageUpload((state) => state.tasks);+ const descTopicRegex = /#\S+#\S+/+ const { t } = useTransClient('publish')+ const tasks = usePublishManageUpload(state => state.tasks)// 错误参数,发布之前会检测错误参数,防止平台无法发布const errParamsMap = useMemo(() => {- const errParamsMapTemp: ErrPubParamsMapType = new Map();+ const errParamsMapTemp: ErrPubParamsMapType = new Map()for (const v of data) {- const platInfo = AccountPlatInfoMap.get(v.account!.type)!;- const { topics } = parseTopicString(v.params.des || "");- const topicsAll = [...new Set((v.params.topics ?? []).concat(topics))];- const { topicMax } = platInfo.commonPubParamsConfig;- const video = v.params.video;+ const platInfo = AccountPlatInfoMap.get(v.account!.type)!+ const { topics } = parseTopicString(v.params.des || '')+ const topicsAll = [...new Set((v.params.topics ?? []).concat(topics))]+ const { topicMax } = platInfo.commonPubParamsConfig+ const video = v.params.videoconst setErrorMsg = (msg: string) => {errParamsMapTemp.set(v.account.id, {parErrMsg: msg,- });+ })};(() => {// ------------------------ 通用参数校验 ------------------------// 媒体上传完成校验(阻止在上传未完成时发布)- const hasImages = (v.params.images?.length || 0) > 0;- const hasVideo = Boolean(v.params.video);+ const hasImages = (v.params.images?.length || 0) > 0+ const hasVideo = Boolean(v.params.video)const isImageUploaded = (img: any) => {return (- !!img?.ossUrl ||- (img?.uploadTaskId &&- tasks[img.uploadTaskId]?.status === UploadTaskStatusEnum.Success)- );- };+ !!img?.ossUrl+ || (img?.uploadTaskId+ && tasks[img.uploadTaskId]?.status === UploadTaskStatusEnum.Success)+ )+ }const isVideoUploaded = (vd: any) => {- const videoOk =- !!vd?.ossUrl ||- (vd?.uploadTaskIds?.video &&- tasks[vd.uploadTaskIds.video]?.status ===- UploadTaskStatusEnum.Success);-- const coverOk =- !!vd?.cover?.ossUrl ||- (vd?.uploadTaskIds?.cover &&- tasks[vd.uploadTaskIds.cover]?.status ===- UploadTaskStatusEnum.Success);- return videoOk && coverOk;- };+ const videoOk+ = !!vd?.ossUrl+ || (vd?.uploadTaskIds?.video+ && tasks[vd.uploadTaskIds.video]?.status+ === UploadTaskStatusEnum.Success)++ const coverOk+ = !!vd?.cover?.ossUrl+ || (vd?.uploadTaskIds?.cover+ && tasks[vd.uploadTaskIds.cover]?.status+ === UploadTaskStatusEnum.Success)+ return videoOk && coverOk+ }if (hasImages) {const notFinished = (v.params.images || []).some(- (img) => !isImageUploaded(img),- );+ img => !isImageUploaded(img),+ )if (notFinished) {- return setErrorMsg(t("upload.finishingUp"));+ return setErrorMsg(t('upload.finishingUp'))}}if (hasVideo) {if (!isVideoUploaded(v.params.video)) {- return setErrorMsg(t("upload.finishingUp"));+ return setErrorMsg(t('upload.finishingUp'))}}// 描述校验if (- (v.account.type === PlatType.Threads ||- v.account.type === PlatType.Twitter) &&- !v.params.des+ (v.account.type === PlatType.Threads+ || v.account.type === PlatType.Twitter)+ && !v.params.des) {- return setErrorMsg(t("validation.descriptionRequired"));+ return setErrorMsg(t('validation.descriptionRequired'))}// 标题字数校验if (- v.params.title &&- v.params.title.length > platInfo.commonPubParamsConfig.titleMax!+ v.params.title+ && v.params.title.length > platInfo.commonPubParamsConfig.titleMax!) {return setErrorMsg(- t("validation.titleMaxExceeded", {+ t('validation.titleMaxExceeded', {platformName: platInfo.name,maxCount: platInfo.commonPubParamsConfig.titleMax,}),- );+ )}// 描述字数校验if (- v.params.des &&- v.params.des.length > platInfo.commonPubParamsConfig.desMax+ v.params.des+ && v.params.des.length > platInfo.commonPubParamsConfig.desMax) {return setErrorMsg(- t("validation.descriptionMaxExceeded", {+ t('validation.descriptionMaxExceeded', {platformName: platInfo.name,maxCount: platInfo.commonPubParamsConfig.desMax,}),- );+ )}// 图片数量校验if (- platInfo.pubTypes.has(PubType.ImageText) &&- (v.params.images?.length || 0) > 1 &&- v.params.images!.length > platInfo.commonPubParamsConfig.imagesMax!+ platInfo.pubTypes.has(PubType.ImageText)+ && (v.params.images?.length || 0) > 1+ && v.params.images!.length > platInfo.commonPubParamsConfig.imagesMax!) {return setErrorMsg(- t("validation.imageMaxExceeded", {+ t('validation.imageMaxExceeded', {platformName: platInfo.name,maxCount: platInfo.commonPubParamsConfig.imagesMax,}),- );+ )}// 图片或者视频校验,视频和图片必须要上传一个if (- !platInfo.pubTypes.has(PubType.Article) &&- v.params.images?.length === 0 &&- !v.params.video+ !platInfo.pubTypes.has(PubType.Article)+ && v.params.images?.length === 0+ && !v.params.video) {- let msgs: any = t("validation.uploadImageOrVideo");+ let msgs: any = t('validation.uploadImageOrVideo')if (- platInfo.pubTypes.has(PubType.ImageText) &&- platInfo.pubTypes.has(PubType.VIDEO)+ platInfo.pubTypes.has(PubType.ImageText)+ && platInfo.pubTypes.has(PubType.VIDEO)) {- msgs = t("validation.uploadImageOrVideo");- } else if (platInfo.pubTypes.has(PubType.ImageText)) {- msgs = t("validation.uploadImage");- } else if (platInfo.pubTypes.has(PubType.VIDEO)) {- msgs = t("validation.uploadVideo");+ msgs = t('validation.uploadImageOrVideo')}- return setErrorMsg(msgs);+ else if (platInfo.pubTypes.has(PubType.ImageText)) {+ msgs = t('validation.uploadImage')+ }+ else if (platInfo.pubTypes.has(PubType.VIDEO)) {+ msgs = t('validation.uploadVideo')+ }+ return setErrorMsg(msgs)}// 话题数量校验if (topicsAll.length > topicMax) {return setErrorMsg(- t("validation.topicMaxExceeded", {+ t('validation.topicMaxExceeded', {platformName: platInfo.name,maxCount: topicMax,}),- );+ )}// 判断描述中的话题中间是否用空格分割,如:#话题1#话题2#话题3 这种格式错误- if (descTopicRegex.test(v.params.des || "")) {- return setErrorMsg(t("validation.topicFormatError"));+ if (descTopicRegex.test(v.params.des || '')) {+ return setErrorMsg(t('validation.topicFormatError'))}// ------------------------ 单个平台参数校验 ------------------------@@ -183,64 +185,64 @@ export default function usePubParamsVerify(data: PubItem[]) {if (v.account.type === PlatType.BILIBILI) {// 强制需要标题if (!v.params.title) {- return setErrorMsg(t("validation.titleRequired"));+ return setErrorMsg(t('validation.titleRequired'))}// 强制需要话题if (topicsAll.length === 0) {- return setErrorMsg(t("validation.topicRequired"));+ return setErrorMsg(t('validation.topicRequired'))}if (!v.params.option.bilibili?.tid) {- return setErrorMsg(t("validation.partitionRequired"));+ return setErrorMsg(t('validation.partitionRequired'))}if (- v.params.option.bilibili.copyright === 2 &&- !v.params.option.bilibili.source+ v.params.option.bilibili.copyright === 2+ && !v.params.option.bilibili.source) {- return setErrorMsg(t("validation.sourceRequired"));+ return setErrorMsg(t('validation.sourceRequired'))}}// facebook的强制校验if (v.account.type === PlatType.Facebook) {switch (v.params.option.facebook?.content_category) {- case "post":+ case 'post':// facebook post 图片上限 ≤ 10MBif (v.params.images) {for (const img of v.params.images) {if (img.size > 10 * 1024 * 1024) {- return setErrorMsg(t("validation.facebookPostImageSize"));+ return setErrorMsg(t('validation.facebookPostImageSize'))}}}- break;- case "reel":+ break+ case 'reel':// facebook reel 不支持图片,只支持视频 + 描述if ((v.params.images?.length || 0) !== 0) {- return setErrorMsg(t("validation.facebookReelNoImage"));+ return setErrorMsg(t('validation.facebookReelNoImage'))}// facebook reel 视频时长 3–90 秒if (video && (video.duration > 90 || video.duration < 3)) {- return setErrorMsg(t("validation.facebookReelDuration"));+ return setErrorMsg(t('validation.facebookReelDuration'))}- break;- case "story":+ break+ case 'story':// facebook story 只能选择图片、视频,不能有描述if (v.params.des) {- return setErrorMsg(t("validation.facebookStoryNoDes"));+ return setErrorMsg(t('validation.facebookStoryNoDes'))}// facebook story 视频时长 3–4小时if (video && (video.duration > 14400 || video.duration < 3)) {- return setErrorMsg(t("validation.facebookStoryDuration"));+ return setErrorMsg(t('validation.facebookStoryDuration'))}// facebook story 图片上限 ≤ 4MBif (v.params.images) {for (const img of v.params.images) {if (img.size > 4 * 1024 * 1024) {- return setErrorMsg(t("validation.facebookStoryImageSize"));+ return setErrorMsg(t('validation.facebookStoryImageSize'))}}}- break;+ break}}@@ -248,79 +250,79 @@ export default function usePubParamsVerify(data: PubItem[]) {if (v.account.type === PlatType.Instagram) {// 视频大小 ≤ 100MBif (video && video.size > 100 * 1024 * 1024) {- return setErrorMsg(t("validation.instagramVideoSize"));+ return setErrorMsg(t('validation.instagramVideoSize'))}// instagram 图片size上限8MBif (v.params.images) {for (const img of v.params.images) {if (img.size > 8 * 1024 * 1024) {- return setErrorMsg(t("validation.instagramImageSize"));+ return setErrorMsg(t('validation.instagramImageSize'))}}}// 图片比例判断if (- v.params.option.instagram?.content_category === "post" &&- v.params.images &&- v.params.images.length > 0+ v.params.option.instagram?.content_category === 'post'+ && v.params.images+ && v.params.images.length > 0) {for (const img of v.params.images) {// Instagram Post 图片比例范围:4:5 ~ 1.91:1 (0.8 ~ 1.91)if (!isAspectRatioInRange(img.width, img.height, 4 / 5, 1.91)) {- setErrorMsg(t("validation.instagramImageValidation"));- break;+ setErrorMsg(t('validation.instagramImageValidation'))+ break}}}switch (v.params.option.instagram?.content_category) {- case "post":+ case 'post':// instagram post不能上传视频,必须上传图片if (video) {- return setErrorMsg(t("validation.instagramPostNoVideo"));+ return setErrorMsg(t('validation.instagramPostNoVideo'))}- break;- case "reel":+ break+ case 'reel':// instagram reel 不能上传图片,必须上传视频 1if ((v.params.images?.length || 0) !== 0) {- return setErrorMsg(t("validation.instagramReelNoImage"));+ return setErrorMsg(t('validation.instagramReelNoImage'))}// instagram reel 视频时长 5秒 – 15 分钟if (video && (video.duration > 900 || video.duration < 5)) {- return setErrorMsg(t("validation.instagramReelDuration"));+ return setErrorMsg(t('validation.instagramReelDuration'))}// instagram reel 视频宽高比限制:4:5 ~ 9:16 (0.8 ~ 0.5625)if (- video &&- !isAspectRatioInRange(video.width, video.height, 9 / 16, 4 / 5)+ video+ && !isAspectRatioInRange(video.width, video.height, 9 / 16, 4 / 5)) {return setErrorMsg(- t("validation.instagramReelAspectRatio" as any),- );+ t('validation.instagramReelAspectRatio' as any),+ )}- break;- case "story":+ break+ case 'story':// instagram story 只能选择图片/视频,不能有描述if (v.params.des) {- return setErrorMsg(t("validation.instagramStoryNoDes"));+ return setErrorMsg(t('validation.instagramStoryNoDes'))}// instagram story 视频时长 3–60 秒if (video && (video.duration > 60 || video.duration < 3)) {- return setErrorMsg(t("validation.instagramStoryDuration"));+ return setErrorMsg(t('validation.instagramStoryDuration'))}- break;+ break}}if (v.account.type === PlatType.Threads) {// Threads 视频大小限制 最大 1GBif (video && video.size > 1024 * 1024 * 1024) {- return setErrorMsg(t("validation.threadsVideoSize"));+ return setErrorMsg(t('validation.threadsVideoSize'))}// Threads视频限制,最长 5 分钟,最短 > 0 秒if (video && (video.duration > 300 || video.duration <= 0)) {- return setErrorMsg(t("validation.threadsVideoDuration"));+ return setErrorMsg(t('validation.threadsVideoDuration'))}}@@ -328,25 +330,25 @@ export default function usePubParamsVerify(data: PubItem[]) {if (v.account.type === PlatType.Pinterest) {// 强制需要标题if (!v.params.title) {- return setErrorMsg(t("validation.titleRequired"));+ return setErrorMsg(t('validation.titleRequired'))}// 强制需要 选择Boardif (!v.params.option.pinterest?.boardId) {- return setErrorMsg(t("validation.boardRequired"));+ return setErrorMsg(t('validation.boardRequired'))}// Pinterest 视频限制,4 秒–15 分钟if (video && (video.duration > 900 || video.duration < 4)) {- return setErrorMsg(t("validation.pinterestVideoDuration"));+ return setErrorMsg(t('validation.pinterestVideoDuration'))}// Pinterest 视频大小≤ 1GBif (video && video.size > 1024 * 1024 * 1024) {- return setErrorMsg(t("validation.pinterestVideoSize"));+ return setErrorMsg(t('validation.pinterestVideoSize'))}// Pinterest图片size ≤ 10MBif (v.params.images) {for (const img of v.params.images) {if (img.size > 10 * 1024 * 1024) {- return setErrorMsg(t("validation.pinterestImageSize"));+ return setErrorMsg(t('validation.pinterestImageSize'))}}}@@ -356,45 +358,45 @@ export default function usePubParamsVerify(data: PubItem[]) {if (v.account.type === PlatType.YouTube) {// 强制需要标题if (!v.params.title) {- return setErrorMsg(t("validation.titleRequired"));+ return setErrorMsg(t('validation.titleRequired'))}// 强制需要描述if (!v.params.des) {- return setErrorMsg(t("validation.descriptionRequired"));+ return setErrorMsg(t('validation.descriptionRequired'))}// 强制需要选择视频分类if (!v.params.option.youtube?.categoryId) {- return setErrorMsg(t("validation.categoryRequired" as any));+ return setErrorMsg(t('validation.categoryRequired' as any))}// YouTube 视频大小限制 ≤ 256GBif (video && video.size > 256 * 1024 * 1024 * 1024) {- return setErrorMsg(t("validation.youtubeVideoSize" as any));+ return setErrorMsg(t('validation.youtubeVideoSize' as any))}// YouTube 视频时长限制 ≤ 12小时if (video && video.duration > 43200) {- return setErrorMsg(t("validation.youtubeVideoDuration" as any));+ return setErrorMsg(t('validation.youtubeVideoDuration' as any))}}// TikTok 的强制校验if (v.account.type === PlatType.Tiktok) {- // TikTok 视频时长限制 3 秒至 10 分钟+ // TikTok 视频时长限制 3 秒至 10 分钟if (video && (video.duration > 600 || video.duration < 3)) {- return setErrorMsg(t("validation.tiktokVideoDuration"));+ return setErrorMsg(t('validation.tiktokVideoDuration'))}// TikTok视频大小限制1GB或更小if (video && video.size > 1024 * 1024 * 1024) {- return setErrorMsg(t("validation.tiktokVideoSize"));+ return setErrorMsg(t('validation.tiktokVideoSize'))}// TikTok限制视频最小高度和宽度为 360 像素if (video && (video.width < 360 || video.height < 360)) {- return setErrorMsg(t("validation.tiktokVideoMinResolution"));+ return setErrorMsg(t('validation.tiktokVideoMinResolution'))}// TikTok 图片size限制 最多 20MBif (v.params.images) {for (const img of v.params.images) {if (img.size > 20 * 1024 * 1024) {- return setErrorMsg(t("validation.tiktokImageSize"));+ return setErrorMsg(t('validation.tiktokImageSize'))}}}@@ -402,12 +404,12 @@ export default function usePubParamsVerify(data: PubItem[]) {if (v.params.images) {for (const img of v.params.images) {if (- img.width > 1920 ||- img.height > 1920 ||- (img.width !== 1080 && img.width !== 1920) ||- (img.height !== 1080 && img.height !== 1920)+ img.width > 1920+ || img.height > 1920+ || (img.width !== 1080 && img.width !== 1920)+ || (img.height !== 1080 && img.height !== 1920)) {- return setErrorMsg(t("validation.tiktokImageResolution"));+ return setErrorMsg(t('validation.tiktokImageResolution'))}}}@@ -419,41 +421,41 @@ export default function usePubParamsVerify(data: PubItem[]) {for (const img of v.params.images) {// Twitter图片大小限制最大 5MBif (img.size > 5 * 1024 * 1024) {- return setErrorMsg(t("validation.twitterImageSize"));+ return setErrorMsg(t('validation.twitterImageSize'))}// Twitter最大 8192 × 8192 像素if (img.width > 8192 || img.height > 8192) {- return setErrorMsg(t("validation.twitterImageResolution"));+ return setErrorMsg(t('validation.twitterImageResolution'))}}}}- })();+ })()}- return errParamsMapTemp;- }, [data, t]);+ return errParamsMapTemp+ }, [data, t])// 警告参数,警告参数不会阻止发布,只是提示用户可能存在的问题const warningParamsMap = useMemo(() => {- const warningParamsMapTemp: ErrPubParamsMapType = new Map();+ const warningParamsMapTemp: ErrPubParamsMapType = new Map()for (const v of data) {const setWarningMsg = (msg: string) => {warningParamsMapTemp.set(v.account.id, {parErrMsg: msg,- });- };+ })+ }// YouTube 警告消息if (v.account.type === PlatType.YouTube) {// 建议分辨率:1920×1080(16:9)或 1080×1920(9:16)。if (v.params.video) {- const video = v.params.video;+ const video = v.params.videoif (- !isAspectRatioMatch(video.width, video.height, 16 / 9) &&- !isAspectRatioMatch(video.width, video.height, 9 / 16)+ !isAspectRatioMatch(video.width, video.height, 16 / 9)+ && !isAspectRatioMatch(video.width, video.height, 9 / 16)) {- setWarningMsg(t("validation.youtubeResolutionSuggestion"));+ setWarningMsg(t('validation.youtubeResolutionSuggestion'))}}}@@ -462,27 +464,27 @@ export default function usePubParamsVerify(data: PubItem[]) {if (v.account.type === PlatType.KWAI) {// 推荐分辨率:1080x1920(竖屏)if (v.params.video) {- const video = v.params.video;+ const video = v.params.videoif (!isAspectRatioMatch(video.width, video.height, 9 / 16)) {- setWarningMsg(t("validation.kwaiResolutionSuggestion"));+ setWarningMsg(t('validation.kwaiResolutionSuggestion'))}}// 时长建议:15 秒 - 3 分钟if (v.params.video) {- const video = v.params.video;+ const video = v.params.videoif (video.duration < 15 || video.duration > 180) {- setWarningMsg(t("validation.kwaiDurationSuggestion"));+ setWarningMsg(t('validation.kwaiDurationSuggestion'))}}}}- return warningParamsMapTemp;- }, [data, t]);+ return warningParamsMapTemp+ }, [data, t])return {errParamsMap,warningParamsMap,- };+ }}// 用于展示校验的结果@@ -494,15 +496,15 @@ export const PubParamsVerifyInfo = memo(<Alerttype="warning"showIcon- message={<p style={{ textAlign: "left" }}>{errItem.parErrMsg}</p>}+ message={<p style={{ textAlign: 'left' }}>{errItem.parErrMsg}</p>}style={{- marginBottom: "15px",- padding: "6px 10px",- fontSize: "12px",+ marginBottom: '15px',+ padding: '6px 10px',+ fontSize: '12px',}}/>)}</>- );+ )},-);+)diff --git a/project/web/src/components/PublishDialog/index.tsx b/project/web/src/components/PublishDialog/index.tsxindex b8d012cb..79305e6a 100644--- a/project/web/src/components/PublishDialog/index.tsx+++ b/project/web/src/components/PublishDialog/index.tsx@@ -1,5 +1,14 @@-import {+import type {ForwardedRef,+} from 'react'+import type { SocialAccount } from '@/api/types/account.type'+import {+ ArrowRightOutlined,+ ExclamationCircleFilled,+ InfoCircleOutlined,+} from '@ant-design/icons'+import { Button, message, Modal, Tooltip } from 'antd'+import {forwardRef,memo,useCallback,@@ -7,71 +16,64 @@ import {useImperativeHandle,useMemo,useState,-} from "react";-import styles from "./publishDialog.module.scss";-import { Button, message, Modal, Tooltip } from "antd";-import DownloadAppModal from "@/components/common/DownloadAppModal";-import {- ArrowRightOutlined,- ExclamationCircleFilled,- InfoCircleOutlined,-} from "@ant-design/icons";-import PublishDialogAi from "@/components/PublishDialog/compoents/PublishDialogAi";-import { CSSTransition } from "react-transition-group";-import { SocialAccount } from "@/api/types/account.type";-import { AccountPlatInfoMap, PlatType } from "@/app/config/platConfig";-import AvatarPlat from "@/components/AvatarPlat";-import { usePublishDialog } from "@/components/PublishDialog/usePublishDialog";-import { useShallow } from "zustand/react/shallow";-import PlatParamsSetting from "@/components/PublishDialog/compoents/PlatParamsSetting";-import PubParmasTextarea from "@/components/PublishDialog/compoents/PubParmasTextarea";-import usePubParamsVerify from "@/components/PublishDialog/hooks/usePubParamsVerify";-import PublishDialogDataPicker from "@/components/PublishDialog/compoents/PublishDialogDataPicker";-import { apiCreatePublish } from "@/api/plat/publish";-import { PubType } from "@/app/config/publishConfig";+} from 'react'+import { CSSTransition } from 'react-transition-group'+import { useWindowSize } from 'react-use'+import { useShallow } from 'zustand/react/shallow'+import { apiCreatePublish } from '@/api/plat/publish'+import { toolsApi } from '@/api/tools'import {getDays,getUtcDays,-} from "@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils";-import { generateUUID } from "@/utils";-import { useTransClient } from "@/app/i18n/client";-import { toolsApi } from "@/api/tools";-// 导入各平台授权函数-import { kwaiSkip } from "@/app/[lng]/accounts/plat/kwaiLogin";-import { bilibiliSkip } from "@/app/[lng]/accounts/plat/BilibiliLogin";-import { youtubeSkip } from "@/app/[lng]/accounts/plat/YoutubeLogin";-import { twitterSkip } from "@/app/[lng]/accounts/plat/TwtterLogin";-import { tiktokSkip } from "@/app/[lng]/accounts/plat/TiktokLogin";+} from '@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils'+import { bilibiliSkip } from '@/app/[lng]/accounts/plat/BilibiliLogin'import {FacebookPagesModal,facebookSkip,-} from "@/app/[lng]/accounts/plat/FacebookLogin";-import { instagramSkip } from "@/app/[lng]/accounts/plat/InstagramLogin";-import { threadsSkip } from "@/app/[lng]/accounts/plat/ThreadsLogin";-import { wxGzhSkip } from "@/app/[lng]/accounts/plat/WxGzh";-import { pinterestSkip } from "@/app/[lng]/accounts/plat/PinterestLogin";-import { linkedinSkip } from "@/app/[lng]/accounts/plat/LinkedinLogin";-import { useAccountStore } from "@/store/account";-import PublishDialogPreview from "@/components/PublishDialog/compoents/PublishDialogPreview";-import { useWindowSize } from "react-use";-import { usePublishManageUpload } from "@/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload";+} from '@/app/[lng]/accounts/plat/FacebookLogin'+import { instagramSkip } from '@/app/[lng]/accounts/plat/InstagramLogin'+// 导入各平台授权函数+import { kwaiSkip } from '@/app/[lng]/accounts/plat/kwaiLogin'+import { linkedinSkip } from '@/app/[lng]/accounts/plat/LinkedinLogin'+import { pinterestSkip } from '@/app/[lng]/accounts/plat/PinterestLogin'+import { threadsSkip } from '@/app/[lng]/accounts/plat/ThreadsLogin'+import { tiktokSkip } from '@/app/[lng]/accounts/plat/TiktokLogin'+import { twitterSkip } from '@/app/[lng]/accounts/plat/TwtterLogin'+import { wxGzhSkip } from '@/app/[lng]/accounts/plat/WxGzh'+import { youtubeSkip } from '@/app/[lng]/accounts/plat/YoutubeLogin'+import { AccountPlatInfoMap, PlatType } from '@/app/config/platConfig'+import { PubType } from '@/app/config/publishConfig'+import { useTransClient } from '@/app/i18n/client'+import AvatarPlat from '@/components/AvatarPlat'+import DownloadAppModal from '@/components/common/DownloadAppModal'+import PlatParamsSetting from '@/components/PublishDialog/compoents/PlatParamsSetting'+import PublishDialogAi from '@/components/PublishDialog/compoents/PublishDialogAi'+import PublishDialogDataPicker from '@/components/PublishDialog/compoents/PublishDialogDataPicker'+import PublishDialogPreview from '@/components/PublishDialog/compoents/PublishDialogPreview'+import { usePublishManageUpload } from '@/components/PublishDialog/compoents/PublishManageUpload/usePublishManageUpload'+import PubParmasTextarea from '@/components/PublishDialog/compoents/PubParmasTextarea'+import usePubParamsVerify from '@/components/PublishDialog/hooks/usePubParamsVerify'+import { usePublishDialog } from '@/components/PublishDialog/usePublishDialog'+import { useAccountStore } from '@/store/account'+import { generateUUID } from '@/utils'+import styles from './publishDialog.module.scss'export interface IPublishDialogRef {// 设置发布时间- setPubTime: (pubTime?: string) => void;+ setPubTime: (pubTime?: string) => void}export interface IPublishDialogProps {- open: boolean;- onClose: () => void;- accounts: SocialAccount[];+ open: boolean+ onClose: () => void+ accounts: SocialAccount[]// 发布成功事件- onPubSuccess?: () => void;+ onPubSuccess?: () => void// 默认选中的账户Id- defaultAccountId?: string;+ defaultAccountId?: string}-const { confirm } = Modal;+const { confirm } = Modal// 发布作品弹框const PublishDialog = memo(@@ -86,7 +88,7 @@ const PublishDialog = memo(}: IPublishDialogProps,ref: ForwardedRef<IPublishDialogRef>,) => {- const { width } = useWindowSize();+ const { width } = useWindowSize()const {pubListChoosed,setPubListChoosed,@@ -108,7 +110,7 @@ const PublishDialog = memo(openLeft,setPubList,} = usePublishDialog(- useShallow((state) => ({+ useShallow(state => ({pubListChoosed: state.pubListChoosed,setPubListChoosed: state.setPubListChoosed,init: state.init,@@ -129,377 +131,393 @@ const PublishDialog = memo(openLeft: state.openLeft,setOpenLeft: state.setOpenLeft,})),- );- const { errParamsMap, warningParamsMap } =- usePubParamsVerify(pubListChoosed);- const [createLoading, setCreateLoading] = useState(false);+ )+ const { errParamsMap, warningParamsMap }+ = usePubParamsVerify(pubListChoosed)+ const [createLoading, setCreateLoading] = useState(false)// 内容安全检测状态- const [moderationLoading, setModerationLoading] = useState(false);+ const [moderationLoading, setModerationLoading] = useState(false)const [moderationResult, setModerationResult] = useState<boolean | null>(null,- );- const [moderationDesc, setModerationDesc] = useState<string>("");- const [moderationLevel, setModerationLevel] = useState<any>(null);+ )+ const [moderationDesc, setModerationDesc] = useState<string>('')+ const [moderationLevel, setModerationLevel] = useState<any>(null)// 下载App弹窗状态- const [downloadModalVisible, setDownloadModalVisible] = useState(false);- const [currentPlatform, setCurrentPlatform] = useState<string>("");+ const [downloadModalVisible, setDownloadModalVisible] = useState(false)+ const [currentPlatform, setCurrentPlatform] = useState<string>('')// Facebook页面选择弹窗状态- const [showFacebookPagesModal, setShowFacebookPagesModal] =- useState(false);- const { t } = useTransClient("publish");+ const [showFacebookPagesModal, setShowFacebookPagesModal]+ = useState(false)+ const { t } = useTransClient('publish')const { tasks, md5Cache } = usePublishManageUpload(- useShallow((state) => ({+ useShallow(state => ({tasks: state.tasks,md5Cache: state.md5Cache,})),- );+ )// 获取账户storeconst { accountGroupList, getAccountList } = useAccountStore(- useShallow((state) => ({+ useShallow(state => ({accountGroupList: state.accountGroupList,getAccountList: state.getAccountList,})),- );+ )// 匹配上传结果的ossUrl到发布参数中useEffect(() => {const newPubList = pubListChoosed.map((v) => {- const newPubItem = { ...v };- const video = newPubItem.params.video;- const images = newPubItem.params.images;+ const newPubItem = { ...v }+ const video = newPubItem.params.video+ const images = newPubItem.params.images// 视频匹配if (video && !video.ossUrl) {- newPubItem.params.video!.ossUrl =- md5Cache[tasks[video.uploadTaskIds!.video!].md5!]?.ossUrl;- newPubItem.params.video!.cover.ossUrl =- md5Cache[tasks[video.uploadTaskIds!.cover!].md5!]?.ossUrl;- return newPubItem;+ newPubItem.params.video!.ossUrl+ = md5Cache[tasks[video.uploadTaskIds!.video!].md5!]?.ossUrl+ newPubItem.params.video!.cover.ossUrl+ = md5Cache[tasks[video.uploadTaskIds!.cover!].md5!]?.ossUrl+ return newPubItem}// 图片匹配if (images) {newPubItem.params.images = images.map((img) => {- img.ossUrl = md5Cache[tasks[img.uploadTaskId!].md5!]?.ossUrl;- return img;- });- return newPubItem;+ img.ossUrl = md5Cache[tasks[img.uploadTaskId!].md5!]?.ossUrl+ return img+ })+ return newPubItem}- return newPubItem;- });- setPubListChoosed(newPubList);- }, [md5Cache, tasks]);+ return newPubItem+ })+ setPubListChoosed(newPubList)+ }, [md5Cache, tasks])++ // 处理Facebook授权成功后的页面选择+ const handleFacebookAuthSuccess = () => {+ setShowFacebookPagesModal(true)+ }// 处理离线账户头像点击,直接跳转到对应平台授权页面const handleOfflineAvatarClick = useCallback(async (account: SocialAccount) => {- const platform = account.type;- const targetSpaceId = account.groupId; // 使用账户原本的空间ID+ const platform = account.type+ const targetSpaceId = account.groupId // 使用账户原本的空间IDtry {// 记录授权前的账号数量,用于后续识别新账号const beforeAuthCount = accountGroupList.reduce((total, group) => total + group.children.length,0,- );+ )// 根据平台类型调用对应的授权函数,传递目标空间IDswitch (platform) {case PlatType.KWAI:- await kwaiSkip(platform, targetSpaceId);- break;+ await kwaiSkip(platform, targetSpaceId)+ breakcase PlatType.BILIBILI:- await bilibiliSkip(platform, targetSpaceId);- break;+ await bilibiliSkip(platform, targetSpaceId)+ breakcase PlatType.YouTube:- await youtubeSkip(platform, targetSpaceId);- break;+ await youtubeSkip(platform, targetSpaceId)+ breakcase PlatType.Twitter:- await twitterSkip(platform, targetSpaceId);- break;+ await twitterSkip(platform, targetSpaceId)+ breakcase PlatType.Tiktok:- await tiktokSkip(platform, targetSpaceId);- break;+ await tiktokSkip(platform, targetSpaceId)+ breakcase PlatType.Facebook:try {- await facebookSkip(platform, targetSpaceId);+ await facebookSkip(platform, targetSpaceId)// Facebook授权成功后显示页面选择弹窗- handleFacebookAuthSuccess();- } catch (error) {- console.error(t("messages.facebookAuthFailed" as any), error);+ handleFacebookAuthSuccess()+ }+ catch (error) {+ console.error(t('messages.facebookAuthFailed' as any), error)}- break;+ breakcase PlatType.Instagram:- await instagramSkip(platform, targetSpaceId);- break;+ await instagramSkip(platform, targetSpaceId)+ breakcase PlatType.Threads:- await threadsSkip(platform, targetSpaceId);- break;+ await threadsSkip(platform, targetSpaceId)+ breakcase PlatType.WxGzh:- await wxGzhSkip(platform, targetSpaceId);- break;+ await wxGzhSkip(platform, targetSpaceId)+ breakcase PlatType.Pinterest:- await pinterestSkip(platform, targetSpaceId);- break;+ await pinterestSkip(platform, targetSpaceId)+ breakcase PlatType.LinkedIn:- await linkedinSkip(platform, targetSpaceId);- break;+ await linkedinSkip(platform, targetSpaceId)+ breakdefault:console.warn(- `${t("messages.unsupportedPlatformType" as any)}: ${platform}`,- );+ `${t('messages.unsupportedPlatformType' as any)}: ${platform}`,+ )message.warning(- t("messages.platformNotSupportedDirect" as any, { platform }),- );- return;+ t('messages.platformNotSupportedDirect' as any, { platform }),+ )+ return}// 授权完成后刷新账号列表setTimeout(async () => {try {- await getAccountList();- console.log(t("messages.accountListRefreshed" as any));- } catch (error) {+ await getAccountList()+ console.log(t('messages.accountListRefreshed' as any))+ }+ catch (error) {console.error(- t("messages.refreshAccountListFailed" as any),+ t('messages.refreshAccountListFailed' as any),error,- );+ )}- }, 3000); // 等待3秒让授权完成- } catch (error) {- console.error(t("messages.authFailed" as any), error);- message.error(t("messages.authFailedRetry" as any));+ }, 3000) // 等待3秒让授权完成+ }+ catch (error) {+ console.error(t('messages.authFailed' as any), error)+ message.error(t('messages.authFailedRetry' as any))}},[accountGroupList, getAccountList],- );-- // 处理Facebook授权成功后的页面选择- const handleFacebookAuthSuccess = () => {- setShowFacebookPagesModal(true);- };+ )// 处理Facebook页面选择成功const handleFacebookPagesSuccess = () => {- setShowFacebookPagesModal(false);+ setShowFacebookPagesModal(false)// 可以在这里添加成功提示或其他逻辑- };+ }// 内容安全检测函数const handleContentModeration = useCallback(async () => {// 获取当前描述内容- let contentToCheck = "";+ let contentToCheck = ''if (step === 0 && pubListChoosed.length >= 2) {- contentToCheck = commonPubParams.des || "";- } else if (step === 1 && expandedPubItem) {- contentToCheck = expandedPubItem.params.des || "";- } else if (pubListChoosed.length === 1) {- contentToCheck = pubListChoosed[0].params.des || "";+ contentToCheck = commonPubParams.des || ''+ }+ else if (step === 1 && expandedPubItem) {+ contentToCheck = expandedPubItem.params.des || ''+ }+ else if (pubListChoosed.length === 1) {+ contentToCheck = pubListChoosed[0].params.des || ''}if (!contentToCheck.trim()) {- message.warning(t("messages.pleaseInputContent" as any));- return;+ message.warning(t('messages.pleaseInputContent' as any))+ return}try {- setModerationLoading(true);- setModerationResult(null);- setModerationDesc("");- setModerationLevel(null);- const result = await toolsApi.textModeration(contentToCheck);- console.log("result", result);+ setModerationLoading(true)+ setModerationResult(null)+ setModerationDesc('')+ setModerationLevel(null)+ const result = await toolsApi.textModeration(contentToCheck)+ console.log('result', result)if (result?.code === 0) {- const data: any = result?.data || ({} as any);- const descriptions: string =- (data && (data.descriptions as string)) || "";- const labels: string = (data && (data.labels as string)) || "";- const reason: any =- data && (data.reason ? JSON.parse(data.reason) : "");- const isSafe = !descriptions && !labels && !reason;- setModerationResult(isSafe);- setModerationLevel(reason);+ const data: any = result?.data || ({} as any)+ const descriptions: string+ = (data && (data.descriptions as string)) || ''+ const labels: string = (data && (data.labels as string)) || ''+ const reason: any+ = data && (data.reason ? JSON.parse(data.reason) : '')+ const isSafe = !descriptions && !labels && !reason+ setModerationResult(isSafe)+ setModerationLevel(reason)setModerationDesc(isSafe- ? ""- : descriptions || reason || t("actions.contentUnsafe" as any),- );+ ? ''+ : descriptions || reason || t('actions.contentUnsafe' as any),+ )if (isSafe) {- message.success(t("actions.contentSafe" as any));- } else {- message.error(t("actions.contentUnsafe" as any));+ message.success(t('actions.contentSafe' as any))+ }+ else {+ message.error(t('actions.contentUnsafe' as any))}}- } catch (error) {- console.error(t("messages.contentModerationError" as any), error);- message.error(t("messages.contentModerationFailed" as any));- } finally {- setModerationLoading(false);}- }, [step, pubListChoosed, commonPubParams, expandedPubItem, t]);+ catch (error) {+ console.error(t('messages.contentModerationError' as any), error)+ message.error(t('messages.contentModerationFailed' as any))+ }+ finally {+ setModerationLoading(false)+ }+ }, [step, pubListChoosed, commonPubParams, expandedPubItem, t])// 检查是否有描述内容const hasDescription = useMemo(() => {if (step === 0 && pubListChoosed.length >= 2) {- return !!(commonPubParams.des && commonPubParams.des.trim());- } else if (step === 1 && expandedPubItem) {+ return !!(commonPubParams.des && commonPubParams.des.trim())+ }+ else if (step === 1 && expandedPubItem) {return !!(expandedPubItem.params.des && expandedPubItem.params.des.trim()- );- } else if (pubListChoosed.length === 1) {+ )+ }+ else if (pubListChoosed.length === 1) {return !!(pubListChoosed[0].params.des && pubListChoosed[0].params.des.trim()- );+ )}- return false;- }, [step, pubListChoosed, commonPubParams, expandedPubItem]);+ return false+ }, [step, pubListChoosed, commonPubParams, expandedPubItem])// 检查选中的平台是否需要内容安全检测const needsContentModeration = useMemo(() => {- if (pubListChoosed.length === 0) return false;+ if (pubListChoosed.length === 0)+ return false// 检查所有选中的账户对应的平台是否需要内容检测return pubListChoosed.some((pubItem) => {const platInfo = AccountPlatInfoMap.get(pubItem.account.type as PlatType,- );- return platInfo?.jiancha === true;- });- }, [pubListChoosed]);+ )+ return platInfo?.jiancha === true+ })+ }, [pubListChoosed])// 监听内容变化,重置内容安全检测状态useEffect(() => {- setModerationResult(null);- setModerationDesc("");- setModerationLevel(null);+ setModerationResult(null)+ setModerationDesc('')+ setModerationLevel(null)}, [commonPubParams.des,expandedPubItem?.params.des,- pubListChoosed.map((item) => item.params.des).join(","),- ]);+ pubListChoosed.map(item => item.params.des).join(','),+ ])// 当内容被清空时,也重置检测状态useEffect(() => {if (!hasDescription) {- setModerationResult(null);- setModerationDesc("");- setModerationLevel(null);+ setModerationResult(null)+ setModerationDesc('')+ setModerationLevel(null)}- }, [hasDescription]);+ }, [hasDescription])useEffect(() => {if (open) {- init(accounts, defaultAccountId);- } else {- setPubListChoosed([]);- clear();+ init(accounts, defaultAccountId)+ }+ else {+ setPubListChoosed([])+ clear()}- }, [accounts, open]);+ }, [accounts, open])// 离线账号(status === 0)不可参与发布:如被默认选中则自动移除useEffect(() => {const filtered = pubListChoosed.filter(- (item) => item.account.status !== 0,- );+ item => item.account.status !== 0,+ )if (filtered.length !== pubListChoosed.length) {- setPubListChoosed(filtered);+ setPubListChoosed(filtered)}- }, [pubListChoosed, setPubListChoosed]);+ }, [pubListChoosed, setPubListChoosed])// 移除PC端不支持的平台账户过滤逻辑,改为在UI中显示遮罩// 关闭弹框并确认关闭const closeDialog = useCallback(() => {confirm({- title: t("confirmClose.title"),+ title: t('confirmClose.title'),icon: <ExclamationCircleFilled />,- content: t("confirmClose.content"),- okType: "danger",+ content: t('confirmClose.content'),+ okType: 'danger',okButtonProps: {- type: "primary",+ type: 'primary',},cancelButtonProps: {- type: "text",+ type: 'text',},centered: true,onOk() {- onClose();+ onClose()},- });- }, [onClose, t]);+ })+ }, [onClose, t])// 是否打开右侧预览const openRight = useMemo(() => {if (step === 0) {- return pubListChoosed.length !== 0;- } else {- return expandedPubItem !== undefined;+ return pubListChoosed.length !== 0+ }+ else {+ return expandedPubItem !== undefined}- }, [pubListChoosed, expandedPubItem, step]);+ }, [pubListChoosed, expandedPubItem, step])// 是否打开左侧const openLeftSide = useMemo(() => {- if (!openLeft) return false;+ if (!openLeft)+ return falseif (step === 0) {- return pubListChoosed.length !== 0;- } else {- return expandedPubItem !== undefined;+ return pubListChoosed.length !== 0}- }, [openLeft, step, pubListChoosed.length, expandedPubItem]);+ else {+ return expandedPubItem !== undefined+ }+ }, [openLeft, step, pubListChoosed.length, expandedPubItem])useEffect(() => {- setErrParamsMap(errParamsMap);- }, [errParamsMap]);+ setErrParamsMap(errParamsMap)+ }, [errParamsMap])useEffect(() => {- setWarningParamsMap(warningParamsMap);- }, [warningParamsMap]);+ setWarningParamsMap(warningParamsMap)+ }, [warningParamsMap])const pubClick = useCallback(async () => {- setCreateLoading(true);+ setCreateLoading(true)const publishTime = getUtcDays(- pubTime ? pubTime : getDays().add(6, "minute"),- ).format();+ pubTime || getDays().add(6, 'minute'),+ ).format()- const flowId = generateUUID();+ const flowId = generateUUID()for (const item of pubListChoosed) {const res = await apiCreatePublish({topics: [],- flowId: flowId,+ flowId,type: item.params.video?.cover.ossUrl? PubType.VIDEO: PubType.ImageText,- title: item.params.title || "",+ title: item.params.title || '',desc: item.params.des,accountId: item.account.id,accountType: item.account.type,videoUrl: item.params.video?.ossUrl,coverUrl:- item.params.video?.cover.ossUrl ||- (item.params.images && item.params.images.length > 0+ item.params.video?.cover.ossUrl+ || (item.params.images && item.params.images.length > 0? item.params.images[0].ossUrl: undefined),imgUrlList:item.params.images- ?.map((v) => v.ossUrl)+ ?.map(v => v.ossUrl).filter((url): url is string => url !== undefined) || [],publishTime,option: item.params.option,- });+ })if (res?.code !== 0) {- return setCreateLoading(false);+ return setCreateLoading(false)}}- onClose();- setCreateLoading(false);+ onClose()+ setCreateLoading(false)- if (onPubSuccess) onPubSuccess();- }, [pubListChoosed]);+ if (onPubSuccess)+ onPubSuccess()+ }, [pubListChoosed])const imperativeHandle: IPublishDialogRef = {setPubTime,- };- useImperativeHandle(ref, () => imperativeHandle);+ }+ useImperativeHandle(ref, () => imperativeHandle)return (<>@@ -509,7 +527,7 @@ const PublishDialog = memo(open={open}onCancel={closeDialog}footer={null}- styles={{ wrapper: { textAlign: "center" } }}+ styles={{ wrapper: { textAlign: 'center' } }}>{width >= 1400 && (<CSSTransition@@ -526,106 +544,107 @@ const PublishDialog = memo(className="publishDialog-wrapper"onClick={() => {if (step === 1) {- setExpandedPubItem(undefined);+ setExpandedPubItem(undefined)}}}><div className="publishDialog-con"><div className="publishDialog-con-head"><span className="publishDialog-con-head-title">- {t("title")}+ {t('title')}</span></div><div className="publishDialog-con-acconts">{pubList.map((pubItem) => {const platConfig = AccountPlatInfoMap.get(pubItem.account.type,- )!;+ )!const isChoosed = pubListChoosed.find(- (v) => v.account.id === pubItem.account.id,- );- const isOffline = pubItem.account.status === 0;- const isPcNotSupported =- platConfig && platConfig.pcNoThis === true;+ v => v.account.id === pubItem.account.id,+ )+ const isOffline = pubItem.account.status === 0+ const isPcNotSupported+ = platConfig && platConfig.pcNoThis === truereturn (<Tooltiptitle={isPcNotSupported- ? t("tips.pcNotSupported" as any)+ ? t('tips.pcNotSupported' as any): isOffline- ? t("tips.accountOffline" as any)+ ? t('tips.accountOffline' as any): undefined}key={pubItem.account.id}><divclassName={[- "publishDialog-con-acconts-item",+ 'publishDialog-con-acconts-item',isChoosed- ? "publishDialog-con-acconts-item--active"- : "",- ].join(" ")}+ ? 'publishDialog-con-acconts-item--active'+ : '',+ ].join(' ')}style={{borderColor: isChoosed? platConfig.themeColor- : "transparent",+ : 'transparent',}}onClick={(e) => {- e.stopPropagation();+ e.stopPropagation()// 离线账户的点击由头像容器处理,这里不处理if (isOffline) {- return;+ return}if (isPcNotSupported) {- setCurrentPlatform(platConfig?.name || "");- setDownloadModalVisible(true);- return;+ setCurrentPlatform(platConfig?.name || '')+ setDownloadModalVisible(true)+ return}- const newPubListChoosed = [...pubListChoosed];+ const newPubListChoosed = [...pubListChoosed]// 查找当前账户是否已被选择const index = newPubListChoosed.findIndex(- (v) => v.account.id === pubItem.account.id,- );+ v => v.account.id === pubItem.account.id,+ )if (index !== -1) {- newPubListChoosed.splice(index, 1);- } else {- newPubListChoosed.push(pubItem);+ newPubListChoosed.splice(index, 1)+ }+ else {+ newPubListChoosed.push(pubItem)}// 是否自动回到第一步if (newPubListChoosed.length === 0 && step === 1) {const isBack = newPubListChoosed.every(- (v) =>- !v.params.des &&- !v.params.video &&- !v.params.images?.length,- );+ v =>+ !v.params.des+ && !v.params.video+ && !v.params.images?.length,+ )if (isBack) {- setStep(0);+ setStep(0)}}// 是否自动前往第二步if (step === 0 && newPubListChoosed.length !== 0) {const isFront = newPubListChoosed.every(- (v) =>- v.params.des ||- v.params.video ||- v.params.images?.length !== 0,- );+ v =>+ v.params.des+ || v.params.video+ || v.params.images?.length !== 0,+ )if (isFront) {- setStep(1);+ setStep(1)}}if (newPubListChoosed.length === 1) {- setExpandedPubItem(newPubListChoosed[0]);+ setExpandedPubItem(newPubListChoosed[0])}- setPubListChoosed(newPubListChoosed);+ setPubListChoosed(newPubListChoosed)}}>{/* 账号头像:离线或PC不支持显示遮罩并禁用 */}- <div style={{ position: "relative" }}>+ <div style={{ position: 'relative' }}><AvatarPlat- className={`publishDialog-con-acconts-item-avatar ${!isChoosed || isOffline || isPcNotSupported ? "disabled" : ""}`}+ className={`publishDialog-con-acconts-item-avatar ${!isChoosed || isOffline || isPcNotSupported ? 'disabled' : ''}`}account={pubItem.account}size="large"disabled={@@ -637,49 +656,49 @@ const PublishDialog = memo(onClick={(e) => {// 小红书平台即使是掉线状态也显示下载App弹窗if (pubItem.account.type === PlatType.Xhs) {- setCurrentPlatform(t("rednote" as any));- setDownloadModalVisible(true);- return;+ setCurrentPlatform(t('rednote' as any))+ setDownloadModalVisible(true)+ return}// 其他平台的离线账户触发授权跳转if (isOffline) {- handleOfflineAvatarClick(pubItem.account);+ handleOfflineAvatarClick(pubItem.account)}// 正常账户的点击事件由父容器处理,这里不需要额外处理}}style={{- position: "absolute",+ position: 'absolute',inset: 0,- background: "rgba(0,0,0,0.45)",- borderRadius: "50%",- display: "flex",- alignItems: "center",- justifyContent: "center",- color: "#fff",+ background: 'rgba(0,0,0,0.45)',+ borderRadius: '50%',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ color: '#fff',fontSize: 12,fontWeight: 600,- pointerEvents: "auto",- cursor: "pointer",+ pointerEvents: 'auto',+ cursor: 'pointer',}}>- {t("badges.offline" as any)}+ {t('badges.offline' as any)}</div>)}{isPcNotSupported && !isOffline && (<divstyle={{- position: "absolute",+ position: 'absolute',inset: 0,- background: "rgba(0,0,0,0.6)",- borderRadius: "50%",- display: "flex",- alignItems: "center",- justifyContent: "center",- color: "#fff",+ background: 'rgba(0,0,0,0.6)',+ borderRadius: '50%',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ color: '#fff',fontSize: 10,fontWeight: 600,- pointerEvents: "none",- textAlign: "center",+ pointerEvents: 'none',+ textAlign: 'center',lineHeight: 1.2,}}>@@ -689,212 +708,218 @@ const PublishDialog = memo(</div></div></Tooltip>- );+ )})}</div><div className="publishDialog-paramsSet">- {step === 0 ? (- <>- {pubListChoosed.length == 1 && (- <PlatParamsSetting pubItem={pubListChoosed[0]} />- )}- {pubListChoosed.length >= 2 && (- <PubParmasTextarea- key={`${commonPubParams.images?.length || 0}-${commonPubParams.video ? "video" : "no-video"}`}- platType={PlatType.Instagram}- rows={16}- desValue={commonPubParams.des}- videoFileValue={commonPubParams.video}- imageFileListValue={commonPubParams.images}- onChange={(values) => {- setAccountAllParams({- des: values.value,- images: values.imgs,- video: values.video,- });- }}- />+ {step === 0+ ? (+ <>+ {pubListChoosed.length == 1 && (+ <PlatParamsSetting pubItem={pubListChoosed[0]} />+ )}+ {pubListChoosed.length >= 2 && (+ <PubParmasTextarea+ key={`${commonPubParams.images?.length || 0}-${commonPubParams.video ? 'video' : 'no-video'}`}+ platType={PlatType.Instagram}+ rows={16}+ desValue={commonPubParams.des}+ videoFileValue={commonPubParams.video}+ imageFileListValue={commonPubParams.images}+ onChange={(values) => {+ setAccountAllParams({+ des: values.value,+ images: values.imgs,+ video: values.video,+ })+ }}+ />+ )}+ </>+ )+ : (+ <>+ {pubListChoosed.map((v) => {+ return (+ <PlatParamsSetting+ pubItem={v}+ key={v.account.id}+ style={{ marginBottom: '12px' }}+ />+ )+ })}+ </>)}- </>- ) : (- <>- {pubListChoosed.map((v) => {- return (- <PlatParamsSetting- pubItem={v}- key={v.account.id}- style={{ marginBottom: "12px" }}- />- );- })}- </>- )}-- {pubListChoosed.length === 0 &&- pubList.some(- (v) =>- v.params.des ||- v.params.video ||- (v.params.images && v.params.images.length > 0),- ) ? (- <div- className="publishDialog-con-tips"- style={{ height: "400px" }}- >- {t("tips.workSaved")}- </div>- ) : (- <>- {pubListChoosed.length === 0 && (- <div className="publishDialog-con-tips">- {t("tips.selectAccount")}++ {pubListChoosed.length === 0+ && pubList.some(+ v =>+ v.params.des+ || v.params.video+ || (v.params.images && v.params.images.length > 0),+ )+ ? (+ <div+ className="publishDialog-con-tips"+ style={{ height: '400px' }}+ >+ {t('tips.workSaved')}</div>+ )+ : (+ <>+ {pubListChoosed.length === 0 && (+ <div className="publishDialog-con-tips">+ {t('tips.selectAccount')}+ </div>+ )}+ </>)}- </>- )}</div></div><divclassName="publishDialog-footer"- onClick={(e) => e.stopPropagation()}+ onClick={e => e.stopPropagation()}><PublishDialogDataPicker /><divclassName="publishDialog-footer-btns"- style={{ display: "flex", flexDirection: "row", gap: 12 }}+ style={{ display: 'flex', flexDirection: 'row', gap: 12 }}>- {step === 0 && pubListChoosed.length >= 2 ? (- <Button- size="large"- onClick={() => {- setExpandedPubItem(undefined);- setStep(1);- }}- >- {t("buttons.customizePerAccount")}- <ArrowRightOutlined />- </Button>- ) : (- <>- <div- style={{- display: "flex",- alignItems: "center",- gap: 12,- }}- >- {moderationResult !== null && (+ {step === 0 && pubListChoosed.length >= 2+ ? (+ <Button+ size="large"+ onClick={() => {+ setExpandedPubItem(undefined)+ setStep(1)+ }}+ >+ {t('buttons.customizePerAccount')}+ <ArrowRightOutlined />+ </Button>+ )+ : (+ <><div- style={{ display: "flex", flexDirection: "column" }}+ style={{+ display: 'flex',+ alignItems: 'center',+ gap: 12,+ }}>- <span- style={{- fontSize: 14,- color: moderationResult ? "#52c41a" : "#ff4d4f",- fontWeight: 500,- }}- >- {moderationResult- ? t("actions.contentSafe" as any)- : moderationLevel?.riskLevel- ? `${t("actions.riskLevel" as any)} ${moderationLevel.riskLevel}`- : t("actions.contentUnsafe" as any)}- </span>- {!moderationResult && !!moderationDesc && (- <span- style={{- fontSize: 12,- color: "#ff4d4f",- maxWidth: 360,- whiteSpace: "pre-wrap",- display: "inline-flex",- alignItems: "center",- gap: 6,- }}+ {moderationResult !== null && (+ <div+ style={{ display: 'flex', flexDirection: 'column' }}>- {moderationDesc}- <Tooltip- title={moderationLevel?.riskTips || ""}- placement="top"+ <span+ style={{+ fontSize: 14,+ color: moderationResult ? '#52c41a' : '#ff4d4f',+ fontWeight: 500,+ }}>- <InfoCircleOutlined- style={{ color: "#ff4d4f" }}- />- </Tooltip>- </span>+ {moderationResult+ ? t('actions.contentSafe' as any)+ : moderationLevel?.riskLevel+ ? `${t('actions.riskLevel' as any)} ${moderationLevel.riskLevel}`+ : t('actions.contentUnsafe' as any)}+ </span>+ {!moderationResult && !!moderationDesc && (+ <span+ style={{+ fontSize: 12,+ color: '#ff4d4f',+ maxWidth: 360,+ whiteSpace: 'pre-wrap',+ display: 'inline-flex',+ alignItems: 'center',+ gap: 6,+ }}+ >+ {moderationDesc}+ <Tooltip+ title={moderationLevel?.riskTips || ''}+ placement="top"+ >+ <InfoCircleOutlined+ style={{ color: '#ff4d4f' }}+ />+ </Tooltip>+ </span>+ )}+ </div>)}- </div>- )}-- {hasDescription && needsContentModeration && (- <Button- size="large"- loading={moderationLoading}- onClick={handleContentModeration}- type={- moderationResult === true- ? "primary"- : moderationResult === false- ? "default"- : "default"- }- style={{- backgroundColor:++ {hasDescription && needsContentModeration && (+ <Button+ size="large"+ loading={moderationLoading}+ onClick={handleContentModeration}+ type={+ moderationResult === true+ ? 'primary'+ : moderationResult === false+ ? 'default'+ : 'default'+ }+ style={{+ backgroundColor:moderationResult === true- ? "#52c41a"+ ? '#52c41a': moderationResult === false- ? "#ff4d4f"+ ? '#ff4d4f': undefined,- borderColor:+ borderColor:moderationResult === true- ? "#52c41a"+ ? '#52c41a': moderationResult === false- ? "#ff4d4f"+ ? '#ff4d4f': undefined,- color:- moderationResult === true ||- moderationResult === false- ? "#fff"+ color:+ moderationResult === true+ || moderationResult === false+ ? '#fff': undefined,- }}- >- {moderationLoading- ? t("actions.checkingContent" as any)- : t("actions.contentModeration" as any)}- </Button>- )}- </div>- <div style={{ display: "flex", gap: 12 }}>- <Button size="large" onClick={closeDialog}>- {t("buttons.cancelPublish")}- </Button>- <Button- size="large"- type="primary"- loading={createLoading}- onClick={() => {- for (const [key, errVideoItem] of errParamsMap) {- if (errVideoItem) {- const pubItem = pubListChoosed.find(- (v) => v.account.id === key,- )!;- if (step === 1) {- setExpandedPubItem(pubItem);+ }}+ >+ {moderationLoading+ ? t('actions.checkingContent' as any)+ : t('actions.contentModeration' as any)}+ </Button>+ )}+ </div>+ <div style={{ display: 'flex', gap: 12 }}>+ <Button size="large" onClick={closeDialog}>+ {t('buttons.cancelPublish')}+ </Button>+ <Button+ size="large"+ type="primary"+ loading={createLoading}+ onClick={() => {+ for (const [key, errVideoItem] of errParamsMap) {+ if (errVideoItem) {+ const pubItem = pubListChoosed.find(+ v => v.account.id === key,+ )!+ if (step === 1) {+ setExpandedPubItem(pubItem)+ }+ message.warning(errVideoItem.parErrMsg)+ return+ }}- message.warning(errVideoItem.parErrMsg);- return;- }- }- pubClick();- }}- >- {t("buttons.schedulePublish")}- </Button>- </div>- </>- )}+ pubClick()+ }}+ >+ {t('buttons.schedulePublish')}+ </Button>+ </div>+ </>+ )}</div></div></div>@@ -936,9 +961,9 @@ const PublishDialog = memo(onSuccess={handleFacebookPagesSuccess}/></>- );+ )},),-);+)-export default PublishDialog;+export default PublishDialogdiff --git a/project/web/src/components/PublishDialog/publishDialog.module.scss b/project/web/src/components/PublishDialog/publishDialog.module.scssindex d6b078e9..92a32123 100644--- a/project/web/src/components/PublishDialog/publishDialog.module.scss+++ b/project/web/src/components/PublishDialog/publishDialog.module.scss@@ -69,7 +69,7 @@ $assistantWidth: 380px;filter: grayscale(0);}}-+// 未选中状态:保持置灰&.disabled {& > img {@@ -111,7 +111,6 @@ $assistantWidth: 380px;}}&-time {-}}.ant-modal-body {@@ -123,24 +122,29 @@ $assistantWidth: 380px;box-shadow: none !important;}- .right-enter, .left-enter {+ .right-enter,+ .left-enter {width: 0;}- .right-enter-active, .left-enter-active {+ .right-enter-active,+ .left-enter-active {width: $assistantWidth;transition: all 300ms;}- .right-exit, .left-exit {+ .right-exit,+ .left-exit {width: $assistantWidth;}- .right-exit-active, .left-exit-active {+ .right-exit-active,+ .left-exit-active {width: 0;transition: all 300ms;}}}-.publishDialogAi, .publishDialogPreview {+.publishDialogAi,+.publishDialogPreview {background: #fff;width: $assistantWidth;overflow: hidden;diff --git a/project/web/src/components/PublishDialog/publishDialog.type.ts b/project/web/src/components/PublishDialog/publishDialog.type.tsindex 047a7950..13ee51e1 100644--- a/project/web/src/components/PublishDialog/publishDialog.type.ts+++ b/project/web/src/components/PublishDialog/publishDialog.type.ts@@ -1,145 +1,145 @@-import { SocialAccount } from "@/api/types/account.type";+import type { SocialAccount } from '@/api/types/account.type'export interface IImgFile {- id: string;- size: number;- file: File;+ id: string+ size: number+ file: File// 前端临时路径,注意不要存到数据库- imgUrl: string;- filename: string;+ imgUrl: string+ filename: string// 图片在硬盘上的路径- imgPath: string;+ imgPath: string// 图片宽度- width: number;+ width: number// 图片高度- height: number;+ height: number// 前端上传到oss后的url- ossUrl?: string;+ ossUrl?: string// 上传任务ID(用于取消/进度追踪)- uploadTaskId?: string;+ uploadTaskId?: string}export interface IVideoFile {- size: number;- file: Blob;+ size: number+ file: Blob// 前端临时路径,注意不要存到数据库- videoUrl: string;+ videoUrl: string// 前端上传到oss后的url- ossUrl?: string;- filename: string;+ ossUrl?: string+ filename: string// 视频宽度- width: number;+ width: number// 视频高度- height: number;+ height: number// 视频下取整的时长,单位秒- duration: number;+ duration: number// 视频首帧图片- cover: IImgFile;+ cover: IImgFile// 上传任务ID(用于取消/进度追踪)uploadTaskIds?: {- video?: string;- cover?: string;- };+ video?: string+ cover?: string+ }}// 发布 每个平台的独有参数export interface IPlatOption {bilibili?: {// 分区ID,由获取分区信息接口得到- tid?: number;+ tid?: number// 1-原创,2-转载(转载时source必填)- copyright?: number;+ copyright?: number// 如果copyright为转载,则此字段表示转载来源- source?: string;- };+ source?: string+ }wxGzh?: {// 平台独立标题,仅用于微信公众号- title?: string;- };+ title?: string+ }facebook?: {// 页面ID,由获取Facebook页面信息接口得到- page_id?: string;+ page_id?: string// 内容类型:post(Post)、reel(Reel)、story(Story)- content_category?: string;- };+ content_category?: string+ }instagram?: {// 内容类型:post(Post)、reel(Reel)、story(Story)- content_category?: string;- };+ content_category?: string+ }youtube?: {// 隐私状态:public、unlisted、private- privacyStatus?: string;+ privacyStatus?: string// 许可证类型:youtube、creativeCommon- license?: string;+ license?: string// 视频分类ID- categoryId?: string;+ categoryId?: string// 是否通知订阅者- notifySubscribers?: boolean;+ notifySubscribers?: boolean// 是否允许嵌入- embeddable?: boolean;+ embeddable?: boolean// 是否为儿童内容- selfDeclaredMadeForKids?: boolean;- };+ selfDeclaredMadeForKids?: boolean+ }pinterest?: {// Board ID,由获取Pinterest Board信息接口得到- boardId?: string;- };+ boardId?: string+ }tiktok?: {// 隐私级别:PUBLIC_TO_EVERYONE、MUTUAL_FOLLOW_FRIENDS、SELF_ONLY- privacy_level?: string;+ privacy_level?: string// 是否禁用评论- comment_disabled?: boolean;+ comment_disabled?: boolean// 是否禁用合拍- duet_disabled?: boolean;+ duet_disabled?: boolean// 是否禁用拼接- stitch_disabled?: boolean;+ stitch_disabled?: boolean// 品牌有机内容开关- brand_organic_toggle?: boolean;+ brand_organic_toggle?: boolean// 品牌内容开关- brand_content_toggle?: boolean;- };+ brand_content_toggle?: boolean+ }threads?: {// 位置信息- location_id?: string | null;- };+ location_id?: string | null+ }}// 发布参数export interface IPubParams {- des: string;+ des: string// 视频和图片不能同时存在,存在图片本次发布则为图文,存在视频则本次发布为视频发布 --------------// 图片- images?: IImgFile[];+ images?: IImgFile[]// 视频- video?: IVideoFile;+ video?: IVideoFile// 话题- topics?: string[];+ topics?: string[]// 标题- title?: string;+ title?: string// 发布 每个平台的独有参数- option: IPlatOption;+ option: IPlatOption}// 发布数据 itemexport interface PubItem {- account: SocialAccount;- params: IPubParams;+ account: SocialAccount+ params: IPubParams}// b站分区 itemexport interface BiblPartItem {- description: string;- id: number;- name: string;- parent: number;- children: BiblPartItem[];+ description: string+ id: number+ name: string+ parent: number+ children: BiblPartItem[]}// YouTube视频分类 itemexport interface YouTubeCategoryItem {- id: string;+ id: stringsnippet: {- title: string;- description?: string;- };+ title: string+ description?: string+ }}diff --git a/project/web/src/components/PublishDialog/usePublishDialog.ts b/project/web/src/components/PublishDialog/usePublishDialog.tsindex 63278ec2..b8c80bd0 100644--- a/project/web/src/components/PublishDialog/usePublishDialog.ts+++ b/project/web/src/components/PublishDialog/usePublishDialog.ts@@ -1,32 +1,32 @@-import { create } from "zustand";-import { combine } from "zustand/middleware";-import lodash from "lodash";-import { SocialAccount } from "@/api/types/account.type";-import {+import type { SocialAccount } from '@/api/types/account.type'+import type { ErrPubParamsMapType } from '@/components/PublishDialog/hooks/usePubParamsVerify'+import type {IPubParams,PubItem,-} from "@/components/PublishDialog/publishDialog.type";-import { ErrPubParamsMapType } from "@/components/PublishDialog/hooks/usePubParamsVerify";-import { AccountPlatInfoMap } from "@/app/config/platConfig";-import { PubType } from "@/app/config/publishConfig";+} from '@/components/PublishDialog/publishDialog.type'+import lodash from 'lodash'+import { create } from 'zustand'+import { combine } from 'zustand/middleware'+import { AccountPlatInfoMap } from '@/app/config/platConfig'+import { PubType } from '@/app/config/publishConfig'export interface IPublishDialogStore {// 选择的发布列表- pubListChoosed: PubItem[];+ pubListChoosed: PubItem[]// 所有发布列表- pubList: PubItem[];+ pubList: PubItem[]// 通用发布参数- commonPubParams: IPubParams;+ commonPubParams: IPubParams// 当前步骤,0=所有账号没有参数,要设置参数。 1=所有账号有参数,详细设置参数- step: number;+ step: number// 第二步时需要,展开的账户参数- expandedPubItem?: PubItem;+ expandedPubItem?: PubItem// 错误提示- errParamsMap?: ErrPubParamsMapType;- warningParamsMap?: ErrPubParamsMapType;+ errParamsMap?: ErrPubParamsMapType+ warningParamsMap?: ErrPubParamsMapType// 发布时间- pubTime?: string;- openLeft: boolean;+ pubTime?: string+ openLeft: boolean}const store: IPublishDialogStore = {@@ -35,15 +35,15 @@ const store: IPublishDialogStore = {pubList: [],step: 0,commonPubParams: {- title: "",- des: "",+ title: '',+ des: '',video: undefined,images: [],option: {bilibili: {tid: undefined,copyright: 1,- source: "",+ source: '',},facebook: {page_id: undefined,@@ -57,11 +57,11 @@ const store: IPublishDialogStore = {errParamsMap: undefined,warningParamsMap: undefined,openLeft: false,-};+}-const getStore = () => {- return lodash.cloneDeep(store);-};+function getStore() {+ return lodash.cloneDeep(store)+}export const usePublishDialog = create(combine(@@ -73,48 +73,48 @@ export const usePublishDialog = create(setOpenLeft(openLeft: boolean) {set({openLeft,- });+ })},setPubListChoosed(pubListChoosed: PubItem[]) {set({pubListChoosed,- });+ })},setExpandedPubItem(expandedPubItem: PubItem | undefined) {set({expandedPubItem,- });+ })},setErrParamsMap(errParamsMap: ErrPubParamsMapType) {set({errParamsMap,- });+ })},setWarningParamsMap(warningParamsMap: ErrPubParamsMapType) {set({warningParamsMap,- });+ })},setStep(step: number) {- set({ step });+ set({ step })},setPubTime(pubTime: string | undefined) {- set({ pubTime });+ set({ pubTime })},setPubList(pubList: PubItem[]) {- set({ pubList });+ set({ pubList })},// 清空所有数据clear() {set({...getStore(),- });+ })},// 初始化发布参数pubParamsInit(): IPubParams {- return lodash.cloneDeep(get().commonPubParams);+ return lodash.cloneDeep(get().commonPubParams)},/**@@ -123,68 +123,68 @@ export const usePublishDialog = create(* @param defaultAccountId 默认选中的账户Id*/init(account: SocialAccount[], defaultAccountId?: string) {- const pubList: PubItem[] = [];+ const pubList: PubItem[] = []account.map((v) => {pubList.push({account: v,params: methods.pubParamsInit(),- });- });+ })+ })if (defaultAccountId) {methods.setPubListChoosed([- pubList.find((v) => v.account.id === defaultAccountId)!,- ]);+ pubList.find(v => v.account.id === defaultAccountId)!,+ ])}set({pubList,- });+ })},// 参数设置到所有账户setAccountAllParams(pubParmas: Partial<IPubParams>) {- const pubList = [...get().pubList];- const commonPubParams = { ...get().commonPubParams };- let pubListChoosed = [...get().pubListChoosed];+ const pubList = [...get().pubList]+ const commonPubParams = { ...get().commonPubParams }+ let pubListChoosed = [...get().pubListChoosed]// 更新 commonPubParamsfor (const key in pubParmas) {- if (pubParmas.hasOwnProperty(key)) {- (commonPubParams as any)[key] = (pubParmas as any)[key];+ if (Object.hasOwn(pubParmas, key)) {+ (commonPubParams as any)[key] = (pubParmas as any)[key]}}// 更新所有账户的参数for (let i = 0; i < pubList.length; i++) {- const v = pubList[i];- const platConfig = AccountPlatInfoMap.get(v.account.type)!;+ const v = pubList[i]+ const platConfig = AccountPlatInfoMap.get(v.account.type)!// 更新描述if (pubParmas.des !== undefined) {- v.params.des = pubParmas.des;+ v.params.des = pubParmas.des}// 更新标题if (pubParmas.title !== undefined) {- v.params.title = pubParmas.title;+ v.params.title = pubParmas.title}// 更新视频(如果平台支持)if (- pubParmas.video !== undefined &&- platConfig.pubTypes.has(PubType.VIDEO)+ pubParmas.video !== undefined+ && platConfig.pubTypes.has(PubType.VIDEO)) {- v.params.video = pubParmas.video;+ v.params.video = pubParmas.video}// 更新图片(如果平台支持)if (- pubParmas.images !== undefined &&- platConfig.pubTypes.has(PubType.ImageText)+ pubParmas.images !== undefined+ && platConfig.pubTypes.has(PubType.ImageText)) {- v.params.images = pubParmas.images;+ v.params.images = pubParmas.images}// 更新选项@@ -193,15 +193,16 @@ export const usePublishDialog = create({},v.params.option,pubParmas.option,- );+ )}}pubListChoosed = pubListChoosed.map((v) => {- const findData = pubList.find((k) => k.account.id === v.account.id);- if (findData) return findData;- return v;- });+ const findData = pubList.find(k => k.account.id === v.account.id)+ if (findData)+ return findData+ return v+ })set({pubList,@@ -209,18 +210,19 @@ export const usePublishDialog = create(pubListChoosed,expandedPubItem: get().expandedPubItem? pubList.find(- (v) => v.account.id === get().expandedPubItem!.account.id,+ v => v.account.id === get().expandedPubItem!.account.id,): undefined,- });+ })},// 设置单个账号的参数setOnePubParams(pubParmas: Partial<IPubParams>, accountId: string) {- const pubList = [...get().pubList];- let pubListChoosed = [...get().pubListChoosed];- const findedData = pubList.find((v) => v.account.id === accountId);- if (!findedData) return;+ const pubList = [...get().pubList]+ let pubListChoosed = [...get().pubListChoosed]+ const findedData = pubList.find(v => v.account.id === accountId)+ if (!findedData)+ return// 使用lodash的merge来正确处理嵌套对象if (pubParmas.option) {@@ -228,53 +230,54 @@ export const usePublishDialog = create({},findedData.params.option,pubParmas.option,- );+ )}for (const key in pubParmas) {- if (pubParmas.hasOwnProperty(key) && key !== "option") {- (findedData.params as any)[key] = (pubParmas as any)[key];+ if (Object.hasOwn(pubParmas, key) && key !== 'option') {+ (findedData.params as any)[key] = (pubParmas as any)[key]}}for (let i = 0; i < pubList.length; i++) {- const v = pubList[i];- const platConfig = AccountPlatInfoMap.get(v.account.type)!;- if (!pubListChoosed.some((k) => k.account.id === v.account.id)) {+ const v = pubList[i]+ const platConfig = AccountPlatInfoMap.get(v.account.type)!+ if (!pubListChoosed.some(k => k.account.id === v.account.id)) {if (pubParmas.des !== undefined) {- v.params.des = pubParmas.des || "";+ v.params.des = pubParmas.des || ''}if (platConfig.pubTypes.has(PubType.VIDEO) && pubParmas.video) {- v.params.video = pubParmas.video;+ v.params.video = pubParmas.video}if (- platConfig.pubTypes.has(PubType.ImageText) &&- pubParmas.images+ platConfig.pubTypes.has(PubType.ImageText)+ && pubParmas.images) {- v.params.images = pubParmas.images;+ v.params.images = pubParmas.images}}}pubListChoosed = pubListChoosed.map((v) => {- const findData = pubList.find((k) => k.account.id === v.account.id);- if (findData) return findData;- return v;- });+ const findData = pubList.find(k => k.account.id === v.account.id)+ if (findData)+ return findData+ return v+ })set({pubList,pubListChoosed,expandedPubItem: get().expandedPubItem? pubList.find(- (v) => v.account.id === get().expandedPubItem!.account.id,+ v => v.account.id === get().expandedPubItem!.account.id,): undefined,- });+ })},- };+ }- return methods;+ return methods},),-);+)diff --git a/project/web/src/components/PublishDialog/usePublishDialogData.ts b/project/web/src/components/PublishDialog/usePublishDialogData.tsindex c88a63b1..9191b718 100644--- a/project/web/src/components/PublishDialog/usePublishDialogData.ts+++ b/project/web/src/components/PublishDialog/usePublishDialogData.ts@@ -1,29 +1,30 @@-import { create } from "zustand";-import { combine } from "zustand/middleware";-import lodash from "lodash";-import { BiblPartItem, YouTubeCategoryItem } from "@/components/PublishDialog/publishDialog.type";-import { apiGetBilibiliPartitions } from "@/api/plat/bilibili";-import { apiGetFacebookPages, FacebookPageItem } from "@/api/plat/facebook";-import { apiGetYouTubeCategories, apiGetYouTubeRegions } from "@/api/plat/youtube";-import { getPinterestBoardListApi } from "@/api/pinterest";-import { useAccountStore } from "@/store/account";-import { PlatType } from "@/app/config/platConfig";+import type { FacebookPageItem } from '@/api/plat/facebook'+import type { BiblPartItem, YouTubeCategoryItem } from '@/components/PublishDialog/publishDialog.type'+import lodash from 'lodash'+import { create } from 'zustand'+import { combine } from 'zustand/middleware'+import { getPinterestBoardListApi } from '@/api/pinterest'+import { apiGetBilibiliPartitions } from '@/api/plat/bilibili'+import { apiGetFacebookPages } from '@/api/plat/facebook'+import { apiGetYouTubeCategories, apiGetYouTubeRegions } from '@/api/plat/youtube'+import { PlatType } from '@/app/config/platConfig'+import { useAccountStore } from '@/store/account'export interface IPublishDialogDataStore {// b站分区列表- bilibiliPartitions: BiblPartItem[];+ bilibiliPartitions: BiblPartItem[]// Facebook页面列表- facebookPages: FacebookPageItem[];+ facebookPages: FacebookPageItem[]// YouTube视频分类列表- youTubeCategories: YouTubeCategoryItem[];+ youTubeCategories: YouTubeCategoryItem[]// YouTube国区列表- youTubeRegions: string[];+ youTubeRegions: string[]// Pinterest Board列表pinterestBoards: Array<{- id: string;- name: string;- description?: string;- }>;+ id: string+ name: string+ description?: string+ }>}const store: IPublishDialogDataStore = {@@ -32,11 +33,11 @@ const store: IPublishDialogDataStore = {youTubeCategories: [],youTubeRegions: [],pinterestBoards: [],-};+}-const getStore = () => {- return lodash.cloneDeep(store);-};+function getStore() {+ return lodash.cloneDeep(store)+}/*** 存放发布弹框一些平台获取的三方数据@@ -51,137 +52,154 @@ export const usePublishDialogData = create(const methods = {// 获取b站分区列表async getBilibiliPartitions() {- if (get().bilibiliPartitions.length !== 0) return;+ if (get().bilibiliPartitions.length !== 0)+ returnconst res = await apiGetBilibiliPartitions(useAccountStore.getState()- .accountList.find((v) => v.type === PlatType.BILIBILI)!.id,- );+ .accountList+ .find(v => v.type === PlatType.BILIBILI)!.id,+ )set({bilibiliPartitions: res?.data,- });- return res?.data;+ })+ return res?.data},// 获取Facebook页面列表async getFacebookPages(accountId?: string) {- if (get().facebookPages.length !== 0) return;-- let facebookAccount;-+ if (get().facebookPages.length !== 0)+ return++ let facebookAccount+if (accountId) {// 如果提供了账户ID,使用指定的账户facebookAccount = useAccountStore.getState()- .accountList.find((v) => v.id === accountId && v.type === PlatType.Facebook);- } else {+ .accountList+ .find(v => v.id === accountId && v.type === PlatType.Facebook)+ }+ else {// 如果没有提供账户ID,使用第一个找到的Facebook账户(保持向后兼容)facebookAccount = useAccountStore.getState()- .accountList.find((v) => v.type === PlatType.Facebook);+ .accountList+ .find(v => v.type === PlatType.Facebook)}if (!facebookAccount) {- console.warn('没有找到Facebook账户');- return;+ console.warn('没有找到Facebook账户')+ return}- const res: any = await apiGetFacebookPages(facebookAccount.account);+ const res: any = await apiGetFacebookPages(facebookAccount.account)set({facebookPages: res?.data || [],- });- return res?.data;+ })+ return res?.data},// 获取YouTube国区列表async getYouTubeRegions(accountId?: string) {- if (get().youTubeRegions.length !== 0) return;-- let youtubeAccount;-+ if (get().youTubeRegions.length !== 0)+ return++ let youtubeAccount+if (accountId) {// 如果提供了账户ID,使用指定的账户youtubeAccount = useAccountStore.getState()- .accountList.find((v) => v.id === accountId && v.type === PlatType.YouTube);- } else {+ .accountList+ .find(v => v.id === accountId && v.type === PlatType.YouTube)+ }+ else {// 如果没有提供账户ID,使用第一个找到的YouTube账户(保持向后兼容)youtubeAccount = useAccountStore.getState()- .accountList.find((v) => v.type === PlatType.YouTube);+ .accountList+ .find(v => v.type === PlatType.YouTube)}if (!youtubeAccount) {- console.warn('没有找到YouTube账户');- return;+ console.warn('没有找到YouTube账户')+ return}- const res: any = await apiGetYouTubeRegions(youtubeAccount.id);+ const res: any = await apiGetYouTubeRegions(youtubeAccount.id)set({youTubeRegions: res?.data?.regionCode || [],- });- return res?.data?.regionCode;+ })+ return res?.data?.regionCode},// 获取YouTube视频分类async getYouTubeCategories(accountId?: string, regionCode?: string) {- let youtubeAccount;-+ let youtubeAccount+if (accountId) {// 如果提供了账户ID,使用指定的账户youtubeAccount = useAccountStore.getState()- .accountList.find((v) => v.id === accountId && v.type === PlatType.YouTube);- } else {+ .accountList+ .find(v => v.id === accountId && v.type === PlatType.YouTube)+ }+ else {// 如果没有提供账户ID,使用第一个找到的YouTube账户(保持向后兼容)youtubeAccount = useAccountStore.getState()- .accountList.find((v) => v.type === PlatType.YouTube);+ .accountList+ .find(v => v.type === PlatType.YouTube)}if (!youtubeAccount) {- console.warn('没有找到YouTube账户');- return;+ console.warn('没有找到YouTube账户')+ return}// 如果没有提供 regionCode,使用默认值 "US"- const defaultRegionCode = regionCode || 'US';+ const defaultRegionCode = regionCode || 'US'- const res: any = await apiGetYouTubeCategories(youtubeAccount?.id || '', defaultRegionCode);+ const res: any = await apiGetYouTubeCategories(youtubeAccount?.id || '', defaultRegionCode)set({youTubeCategories: res?.data.items || [],- });- return res?.data;+ })+ return res?.data},// 获取Pinterest Board列表async getPinterestBoards(forceRefresh = false, accountId?: string) {- if (!forceRefresh && get().pinterestBoards.length !== 0) return;-- let pinterestAccount;-+ if (!forceRefresh && get().pinterestBoards.length !== 0)+ return++ let pinterestAccount+if (accountId) {// 如果提供了账户ID,使用指定的账户pinterestAccount = useAccountStore.getState()- .accountList.find((v) => v.id === accountId && v.type === PlatType.Pinterest);- } else {+ .accountList+ .find(v => v.id === accountId && v.type === PlatType.Pinterest)+ }+ else {// 如果没有提供账户ID,使用第一个找到的Pinterest账户(保持向后兼容)pinterestAccount = useAccountStore.getState()- .accountList.find((v) => v.type === PlatType.Pinterest);+ .accountList+ .find(v => v.type === PlatType.Pinterest)}if (!pinterestAccount) {- console.warn('没有找到Pinterest账户');- return;+ console.warn('没有找到Pinterest账户')+ return}- const res: any = await getPinterestBoardListApi({ page: 1, size: 100 }, pinterestAccount.id);+ const res: any = await getPinterestBoardListApi({ page: 1, size: 100 }, pinterestAccount.id)set({pinterestBoards: res?.data?.list || [],- });- return res?.data?.list;+ })+ return res?.data?.list},- };+ }- return methods;+ return methods},),-);+)diff --git a/project/web/src/components/ScrollButtonContainer/index.tsx b/project/web/src/components/ScrollButtonContainer/index.tsxindex 5950909b..36664448 100644--- a/project/web/src/components/ScrollButtonContainer/index.tsx+++ b/project/web/src/components/ScrollButtonContainer/index.tsx@@ -1,117 +1,127 @@-import {+import type {ForwardedRef,+ PropsWithChildren,+} from 'react'+import { LeftOutlined, RightOutlined } from '@ant-design/icons'+import { Button } from 'antd'+import {forwardRef,memo,- PropsWithChildren,useCallback,- useRef,useEffect,+ useRef,useState,-} from "react";-import styles from "./scrollButtonContainer.module.scss";-import { Button } from "antd";-import { LeftOutlined, RightOutlined } from "@ant-design/icons";+} from 'react'+import styles from './scrollButtonContainer.module.scss'export interface IScrollButtonContainerRef {}export interface IScrollButtonContainerProps {- width?: string;- step?: number;- duration?: number; // 降级动画时长(ms)- edgeOffset?: number; // 边界容差+ width?: string+ step?: number+ duration?: number // 降级动画时长(ms)+ edgeOffset?: number // 边界容差}const ScrollButtonContainer = memo(- forwardRef(function ScrollButtonContainerInner(+ forwardRef(({children,- width = "100%",+ width = '100%',step = 200,duration = 300,edgeOffset = 2,}: PropsWithChildren<IScrollButtonContainerProps>,ref: ForwardedRef<IScrollButtonContainerRef>,- ) {- const scrollContentRef = useRef<HTMLDivElement>(null);- const [atStart, setAtStart] = useState(true);- const [atEnd, setAtEnd] = useState(false);+ ) => {+ const scrollContentRef = useRef<HTMLDivElement>(null)+ const [atStart, setAtStart] = useState(true)+ const [atEnd, setAtEnd] = useState(false)const updateEdgeState = useCallback(() => {- const el = scrollContentRef.current;- if (!el) return;- const { scrollLeft, scrollWidth, clientWidth } = el;- const noOverflow = scrollWidth <= clientWidth + edgeOffset;+ const el = scrollContentRef.current+ if (!el)+ return+ const { scrollLeft, scrollWidth, clientWidth } = el+ const noOverflow = scrollWidth <= clientWidth + edgeOffsetif (noOverflow) {- setAtStart(true);- setAtEnd(true);- return;+ setAtStart(true)+ setAtEnd(true)+ return}- setAtStart(scrollLeft <= edgeOffset);- setAtEnd(scrollLeft >= scrollWidth - clientWidth - edgeOffset);- }, [edgeOffset]);+ setAtStart(scrollLeft <= edgeOffset)+ setAtEnd(scrollLeft >= scrollWidth - clientWidth - edgeOffset)+ }, [edgeOffset])useEffect(() => {- updateEdgeState();- const el = scrollContentRef.current;- if (!el) return;- const handler = () => updateEdgeState();- el.addEventListener("scroll", handler, { passive: true });+ updateEdgeState()+ const el = scrollContentRef.current+ if (!el)+ return+ const handler = () => updateEdgeState()+ el.addEventListener('scroll', handler, { passive: true })// 尺寸变化时也重算- const ro = new ResizeObserver(() => updateEdgeState());- ro.observe(el);+ const ro = new ResizeObserver(() => updateEdgeState())+ ro.observe(el)return () => {- el.removeEventListener("scroll", handler);- ro.disconnect();- };- }, [updateEdgeState, children]);+ el.removeEventListener('scroll', handler)+ ro.disconnect()+ }+ }, [updateEdgeState, children])const fallbackAnimate = useCallback((target: number) => {- const el = scrollContentRef.current;- if (!el) return;- const start = el.scrollLeft;- const diff = target - start;- if (diff === 0) return;- const startTime = performance.now();+ const el = scrollContentRef.current+ if (!el)+ return+ const start = el.scrollLeft+ const diff = target - start+ if (diff === 0)+ return+ const startTime = performance.now()const animate = (now: number) => {- const progress = Math.min((now - startTime) / duration, 1);+ const progress = Math.min((now - startTime) / duration, 1)// ease-out- const eased = 1 - Math.pow(1 - progress, 3);- el.scrollLeft = start + diff * eased;+ const eased = 1 - (1 - progress) ** 3+ el.scrollLeft = start + diff * easedif (progress < 1) {- requestAnimationFrame(animate);+ requestAnimationFrame(animate)}- };- requestAnimationFrame(animate);+ }+ requestAnimationFrame(animate)},[duration],- );+ )const smoothScrollTo = useCallback((delta: number) => {- const el = scrollContentRef.current;- if (!el) return;- const target = el.scrollLeft + delta;- if ("scrollBy" in el) {+ const el = scrollContentRef.current+ if (!el)+ return+ const target = el.scrollLeft + delta+ if ('scrollBy' in el) {try {- el.scrollBy({ left: delta, behavior: "smooth" });- return;- } catch {+ el.scrollBy({ left: delta, behavior: 'smooth' })+ return+ }+ catch {// fallback}}- fallbackAnimate(target);+ fallbackAnimate(target)},[fallbackAnimate],- );+ )const leftMove = useCallback(() => {- if (!atStart) smoothScrollTo(-step);- }, [smoothScrollTo, step, atStart]);+ if (!atStart)+ smoothScrollTo(-step)+ }, [smoothScrollTo, step, atStart])const rightMove = useCallback(() => {- if (!atEnd) smoothScrollTo(step);- }, [smoothScrollTo, step, atEnd]);+ if (!atEnd)+ smoothScrollTo(step)+ }, [smoothScrollTo, step, atEnd])return (<div className={styles.scrollButtonContainer}>@@ -139,8 +149,8 @@ const ScrollButtonContainer = memo(/>)}</div>- );+ )}),-);+)-export default ScrollButtonContainer;+export default ScrollButtonContainerdiff --git a/project/web/src/components/ScrollButtonContainer/scrollButtonContainer.module.scss b/project/web/src/components/ScrollButtonContainer/scrollButtonContainer.module.scssindex f1481a7c..36edf941 100644--- a/project/web/src/components/ScrollButtonContainer/scrollButtonContainer.module.scss+++ b/project/web/src/components/ScrollButtonContainer/scrollButtonContainer.module.scss@@ -3,7 +3,9 @@:global {.scrollButtonContainer-content {overflow-x: auto;- &::-webkit-scrollbar { display: none; }+ &::-webkit-scrollbar {+ display: none;+ }scrollbar-width: none;-ms-overflow-style: none;}diff --git a/project/web/src/components/SignInCalendar/SignInCalendar.module.scss b/project/web/src/components/SignInCalendar/SignInCalendar.module.scssindex 48b6fa65..15f7b7c0 100644--- a/project/web/src/components/SignInCalendar/SignInCalendar.module.scss+++ b/project/web/src/components/SignInCalendar/SignInCalendar.module.scss@@ -6,12 +6,12 @@height: 40px;border-radius: 50%;transition: all 0.3s ease;-+&:hover {background-color: #f5f5f5;transform: scale(1.05);}-+.anticon {font-size: 18px;color: #666;@@ -23,10 +23,10 @@border-bottom: 1px solid #f0f0f0;padding: 16px 24px;}-- .ant-modal-body {- padding: 28px;- }++ .ant-modal-body {+ padding: 28px;+ }}.modalHeader {@@ -35,7 +35,7 @@align-items: center;width: 100%;padding-top: 20px;-+span {font-size: 16px;font-weight: 600;@@ -48,7 +48,7 @@font-size: 14px;padding: 0;height: auto;-+&:hover {color: #9254de;}@@ -58,35 +58,35 @@padding-top: 0px;.ant-picker-calendar {border: none;-+.ant-picker-calendar-header {padding: 0;margin-bottom: 16px;}-- .ant-picker-calendar-date {- border: none;- padding: 6px;- height: 40px;- display: flex;- align-items: center;- justify-content: center;-- &:hover {- background-color: #f5f5f5;- }- }-++ .ant-picker-calendar-date {+ border: none;+ padding: 6px;+ height: 40px;+ display: flex;+ align-items: center;+ justify-content: center;++ &:hover {+ background-color: #f5f5f5;+ }+ }+.ant-picker-calendar-date-today {background-color: #e6f7ff;border: 1px solid #1890ff;}-- .ant-picker-calendar-date-value {- font-size: 14px;- line-height: 1;- }-++ .ant-picker-calendar-date-value {+ font-size: 14px;+ line-height: 1;+ }+.ant-picker-calendar-date-content {height: auto;line-height: 1;@@ -144,13 +144,11 @@background-color: transparent;}--.dateText {font-size: 12px;color: #333;line-height: 1;-+&.today {color: #1890ff;font-weight: 600;@@ -162,29 +160,29 @@padding: 20px;background-color: #f8f9fa;border-radius: 8px;-- h4 {- margin: 0 0 12px 0;- font-size: 16px;- font-weight: 600;- color: #333;- }-- ul {- margin: 0;- padding-left: 16px;-- li {- margin-bottom: 8px;- font-size: 14px;- color: #666;- line-height: 1.4;-- &:last-child {- margin-bottom: 0;- }- }- }++ h4 {+ margin: 0 0 12px 0;+ font-size: 16px;+ font-weight: 600;+ color: #333;+ }++ ul {+ margin: 0;+ padding-left: 16px;++ li {+ margin-bottom: 8px;+ font-size: 14px;+ color: #666;+ line-height: 1.4;++ &:last-child {+ margin-bottom: 0;+ }+ }+ }}.signInInfo {@@ -194,12 +192,12 @@padding: 16px 20px;background-color: #f0f8ff;border-radius: 6px;-- .infoItem {- font-size: 15px;- color: #1890ff;- font-weight: 500;- }++ .infoItem {+ font-size: 15px;+ color: #1890ff;+ font-weight: 500;+ }}.signInActionButton {@@ -209,13 +207,13 @@border-radius: 8px;background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);border: none;-+&:hover {background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);transform: translateY(-1px);box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);}-+&:disabled {background: #f5f5f5;color: #999;@@ -232,27 +230,27 @@max-width: 550px;}}-- .calendarContainer {- .ant-picker-calendar-date {- height: 36px;- }-- .dateText {- font-size: 13px;- }-- .signedCircle,- .emptyCircle {- width: 6px;- height: 6px;- }- }-++ .calendarContainer {+ .ant-picker-calendar-date {+ height: 36px;+ }++ .dateText {+ font-size: 13px;+ }++ .signedCircle,+ .emptyCircle {+ width: 6px;+ height: 6px;+ }+ }+.signInInfo {flex-direction: column;gap: 8px;-+.infoItem {text-align: center;}diff --git a/project/web/src/components/SignInCalendar/index.tsx b/project/web/src/components/SignInCalendar/index.tsxindex 40ba191c..429ec054 100644--- a/project/web/src/components/SignInCalendar/index.tsx+++ b/project/web/src/components/SignInCalendar/index.tsx@@ -1,90 +1,92 @@-"use client";+'use client'-import React, { useState, useEffect, useMemo } from 'react';-import { Button, Modal, Calendar, Badge, message, Image } from 'antd';-import { BranchesOutlined, CheckOutlined } from '@ant-design/icons';-import { useTransClient } from '@/app/i18n/client';-import { signInApi, SignInType, SignInResponse, PublishDayInfoResponse, PublishInfoResponse } from '@/api/signIn';-import { useUserStore } from '@/store/user';-import { useRouter } from 'next/navigation';-import styles from './SignInCalendar.module.scss';+import { BranchesOutlined, CheckOutlined } from '@ant-design/icons'+import { Badge, Button, Calendar, Image, message, Modal } from 'antd'+import { useRouter } from 'next/navigation'+import React, { useEffect, useMemo, useState } from 'react'+import { PublishDayInfoResponse, PublishInfoResponse, signInApi, SignInResponse, SignInType } from '@/api/signIn'+import { useTransClient } from '@/app/i18n/client'+import faya from '@/assets/images/faya.png'+import { useUserStore } from '@/store/user'-import faya from "@/assets/images/faya.png";+import styles from './SignInCalendar.module.scss'interface SignInCalendarProps {- className?: string;+ className?: string}interface CalendarData {- signedDates: string[]; // 已签到的日期数组,格式: "YYYY-MM-DD"- todaySigned: boolean; // 今天是否已签到- consecutiveDays: number; // 连续签到天数+ signedDates: string[] // 已签到的日期数组,格式: "YYYY-MM-DD"+ todaySigned: boolean // 今天是否已签到+ consecutiveDays: number // 连续签到天数}const SignInCalendar: React.FC<SignInCalendarProps> = ({ className }) => {- const { t } = useTransClient('common');- const userStore = useUserStore();- const router = useRouter();- const [visible, setVisible] = useState(false);- const [loading, setLoading] = useState(false);+ const { t } = useTransClient('common')+ const userStore = useUserStore()+ const router = useRouter()+ const [visible, setVisible] = useState(false)+ const [loading, setLoading] = useState(false)const [calendarData, setCalendarData] = useState<CalendarData>({signedDates: [],todaySigned: false,- consecutiveDays: 0- });- const [currentDate, setCurrentDate] = useState(new Date());+ consecutiveDays: 0,+ })+ const [currentDate, setCurrentDate] = useState(new Date())// 获取当前年月- const currentYear = currentDate.getFullYear();- const currentMonth = currentDate.getMonth() + 1;+ const currentYear = currentDate.getFullYear()+ const currentMonth = currentDate.getMonth() + 1// 获取日历数据const fetchCalendarData = async () => {try {- setLoading(true);-+ setLoading(true)+// 并行获取日历数据和连续签到天数const [calendarResponse, consecutiveResponse] = await Promise.all([signInApi.getSignInCalendar(currentYear, currentMonth),- signInApi.getConsecutiveDays()- ]);-+ signInApi.getConsecutiveDays(),+ ])+// 处理日历数据,将 createdAt 转换为签到日期- const signedDates: string[] = [];- let todaySigned = false;- let consecutiveDays = 0;-+ const signedDates: string[] = []+ let todaySigned = false+ let consecutiveDays = 0+if (calendarResponse.list && calendarResponse.list.length > 0) {// 提取所有签到日期- calendarResponse.list.forEach(item => {- const date = new Date(item.createdAt);- const dateStr = date.toISOString().split('T')[0]; // 格式: YYYY-MM-DD- signedDates.push(dateStr);-+ calendarResponse.list.forEach((item) => {+ const date = new Date(item.createdAt)+ const dateStr = date.toISOString().split('T')[0] // 格式: YYYY-MM-DD+ signedDates.push(dateStr)+// 检查今天是否已签到- const today = new Date().toISOString().split('T')[0];+ const today = new Date().toISOString().split('T')[0]if (dateStr === today) {- todaySigned = true;+ todaySigned = true}- });+ })}-+// 从连续签到接口获取连续签到天数if (consecutiveResponse && consecutiveResponse.data) {- consecutiveDays = consecutiveResponse.data.days || 0;+ consecutiveDays = consecutiveResponse.data.days || 0}-+setCalendarData({signedDates,todaySigned,- consecutiveDays- });- } catch (error) {- console.error('获取签到日历数据失败:', error);- } finally {- setLoading(false);+ consecutiveDays,+ })+ }+ catch (error) {+ console.error('获取签到日历数据失败:', error)+ }+ finally {+ setLoading(false)}- };+ }// 签到const handleSignIn = async () => {@@ -94,27 +96,28 @@ const SignInCalendar: React.FC<SignInCalendarProps> = ({ className }) => {// }// 关闭当前弹窗- setVisible(false);-+ setVisible(false)+// 跳转到 accounts 页面并传递参数表示需要打开发布弹窗- const currentPath = window.location.pathname;+ const currentPath = window.location.pathnameif (currentPath === '/accounts' || currentPath.startsWith('/accounts/')) {// 如果已经在 accounts 页面,触发打开发布弹窗的事件window.dispatchEvent(new CustomEvent('openPublishDialog', {- detail: { fromSignIn: true }- }));- } else {+ detail: { fromSignIn: true },+ }))+ }+ else {// 如果不在 accounts 页面,使用路由跳转并传递参数- router.push('/accounts?openPublish=true&fromSignIn=true');+ router.push('/accounts?openPublish=true&fromSignIn=true')}- };+ }// 日历日期渲染const dateCellRender = (value: any) => {- const dateStr = value.format('YYYY-MM-DD');- const isSigned = calendarData.signedDates.includes(dateStr);- const isToday = value.isSame(new Date(), 'day');-+ const dateStr = value.format('YYYY-MM-DD')+ const isSigned = calendarData.signedDates.includes(dateStr)+ const isToday = value.isSame(new Date(), 'day')+return (<div className={styles.calendarCell}><div className={styles.dateContainer}>@@ -122,55 +125,59 @@ const SignInCalendar: React.FC<SignInCalendarProps> = ({ className }) => {{isToday ? t('signIn.today') : ''}</span><div className={`${styles.signInStatus} ${isSigned ? styles.signed : styles.notSigned}`}>- {isSigned ? (- <div className={styles.signedCircle} />- ) : (- <div className={styles.emptyCircle} />- )}+ {isSigned+ ? (+ <div className={styles.signedCircle} />+ )+ : (+ <div className={styles.emptyCircle} />+ )}</div></div></div>- );- };+ )+ }// 月份变化处理const onPanelChange = (value: any) => {- setCurrentDate(value.toDate());- };+ setCurrentDate(value.toDate())+ }// 监听月份变化,重新获取数据useEffect(() => {if (visible) {- fetchCalendarData();+ fetchCalendarData()}- }, [currentYear, currentMonth, visible]);+ }, [currentYear, currentMonth, visible])return (<><Buttontype="text"- icon={<Image src={faya.src} alt="faya" style={{ width: 20, height: 'auto', marginTop: -5 }} preview={false}/>}+ icon={<Image src={faya.src} alt="faya" style={{ width: 20, height: 'auto', marginTop: -5 }} preview={false} />}onClick={() => setVisible(true)}className={`${styles.signInButton} ${className || ''}`}title={t('signIn.title')}/>-+<Modal- title={+ title={(<div className={styles.modalHeader}><span>{t('signIn.title')}</span>- <Button- type="link"+ <Button+ type="link"className={styles.pointsLink}onClick={() => {// 跳转到个人中心页面- window.open('/profile', '_blank');+ window.open('/profile', '_blank')}}>- {t('signIn.myPoints')} >+ {t('signIn.myPoints')}+ {' '}+ ></Button></div>- }+ )}open={visible}onCancel={() => setVisible(false)}footer={null}@@ -183,34 +190,53 @@ const SignInCalendar: React.FC<SignInCalendarProps> = ({ className }) => {dateCellRender={dateCellRender}onPanelChange={onPanelChange}headerRender={({ value, onChange }) => {- const year = value.year();- const month = value.month() + 1;+ const year = value.year()+ const month = value.month() + 1return (<div className={styles.calendarHeader}>- <span>{year} / {month.toString().padStart(2, '0')}</span>+ <span>+ {year}+ {' '}+ /+ {' '}+ {month.toString().padStart(2, '0')}+ </span></div>- );+ )}}/>-+<div className={styles.signInRules}>- <h4>{t('signIn.rules')}:</h4>+ <h4>+ {t('signIn.rules')}+ :+ </h4><ul><li>{t('signIn.rules1')}</li><li>{t('signIn.rules2')}</li><li>{t('signIn.rules3')}</li></ul></div>-+<div className={styles.signInInfo}><div className={styles.infoItem}>- <span>{t('signIn.consecutiveDays')}: {calendarData.consecutiveDays}</span>+ <span>+ {t('signIn.consecutiveDays')}+ :+ {' '}+ {calendarData.consecutiveDays}+ </span></div><div className={styles.infoItem}>- <span>{t('signIn.totalPoints')}: {userStore.userInfo?.score || 0}</span>+ <span>+ {t('signIn.totalPoints')}+ :+ {' '}+ {userStore.userInfo?.score || 0}+ </span></div></div>-+<Buttontype="primary"size="large"@@ -224,7 +250,7 @@ const SignInCalendar: React.FC<SignInCalendarProps> = ({ className }) => {</div></Modal></>- );-};+ )+}-export default SignInCalendar;+export default SignInCalendardiff --git a/project/web/src/components/VideoPreviewModal.tsx b/project/web/src/components/VideoPreviewModal.tsxindex 478be55a..8fdf26ab 100644--- a/project/web/src/components/VideoPreviewModal.tsx+++ b/project/web/src/components/VideoPreviewModal.tsx@@ -1,13 +1,14 @@-import { ForwardedRef, forwardRef, memo, useRef } from "react";-import { Modal } from "antd";-import { useTransClient } from "@/app/i18n/client";+import type { ForwardedRef } from 'react'+import { Modal } from 'antd'+import { forwardRef, memo, useRef } from 'react'+import { useTransClient } from '@/app/i18n/client'export interface IVideoPreviewModalRef {}export interface IVideoPreviewModalProps {- open: boolean;- videoUrl?: string;- onCancel: () => void;+ open: boolean+ videoUrl?: string+ onCancel: () => void}const VideoPreviewModal = memo(@@ -16,32 +17,32 @@ const VideoPreviewModal = memo({ open, videoUrl, onCancel }: IVideoPreviewModalProps,ref: ForwardedRef<IVideoPreviewModalRef>,) => {- const videoRef = useRef<HTMLVideoElement>(null);- const { t } = useTransClient("publish");+ const videoRef = useRef<HTMLVideoElement>(null)+ const { t } = useTransClient('publish')return (<Modal- title={t("previewvideo")}+ title={t('previewvideo')}open={open}footer={null}onCancel={() => {if (videoRef.current) {- videoRef.current.pause();+ videoRef.current.pause()}- onCancel();+ onCancel()}}width={720}><videoref={videoRef}controls- style={{ width: "100%", maxHeight: "80vh" }}+ style={{ width: '100%', maxHeight: '80vh' }}src={videoUrl}/></Modal>- );+ )},),-);+)-export default VideoPreviewModal;+export default VideoPreviewModaldiff --git a/project/web/src/components/WalletAccountSelect/index.tsx b/project/web/src/components/WalletAccountSelect/index.tsxindex d137927f..9e2b60ee 100644--- a/project/web/src/components/WalletAccountSelect/index.tsx+++ b/project/web/src/components/WalletAccountSelect/index.tsx@@ -1,51 +1,52 @@-"use client";+'use client'-import { useEffect, useMemo, useState } from "react";-import { Select, Spin, Empty } from "antd";-import { getUserWalletAccountList, UserWalletAccount } from "@/api/userWalletAccount";+import type { UserWalletAccount } from '@/api/userWalletAccount'+import { Empty, Select, Spin } from 'antd'+import { useEffect, useMemo, useState } from 'react'+import { getUserWalletAccountList } from '@/api/userWalletAccount'-type Props = {- value?: string;- onChange?: (val?: string) => void;- pageSize?: number;- disabled?: boolean;-};+interface Props {+ value?: string+ onChange?: (val?: string) => void+ pageSize?: number+ disabled?: boolean+}-const { Option } = Select;+const { Option } = Selectexport default function WalletAccountSelect(props: Props) {- const { value, onChange, pageSize = 50, disabled } = props;- const [loading, setLoading] = useState(false);- const [list, setList] = useState<UserWalletAccount[]>([]);- const [pageNo, setPageNo] = useState(1);- const [total, setTotal] = useState(0);+ const { value, onChange, pageSize = 50, disabled } = props+ const [loading, setLoading] = useState(false)+ const [list, setList] = useState<UserWalletAccount[]>([])+ const [pageNo, setPageNo] = useState(1)+ const [total, setTotal] = useState(0)- const hasMore = useMemo(() => list.length < total, [list.length, total]);+ const hasMore = useMemo(() => list.length < total, [list.length, total])useEffect(() => {- fetchPage(1);- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);+ fetchPage(1)+ }, [])async function fetchPage(nextPage: number) {- setLoading(true);+ setLoading(true)try {- const res = await getUserWalletAccountList(nextPage, pageSize);+ const res = await getUserWalletAccountList(nextPage, pageSize)if (res?.data) {- const newList = nextPage === 1 ? (res.data.list || []) : [...list, ...(res.data.list || [])];- setList(newList);- setTotal(res.data.total || 0);- setPageNo(nextPage);+ const newList = nextPage === 1 ? (res.data.list || []) : [...list, ...(res.data.list || [])]+ setList(newList)+ setTotal(res.data.total || 0)+ setPageNo(nextPage)}- } finally {- setLoading(false);+ }+ finally {+ setLoading(false)}}function onPopupScroll(e: any) {- const target = e.target;+ const target = e.targetif (!loading && hasMore && target.scrollTop + target.offsetHeight + 24 >= target.scrollHeight) {- fetchPage(pageNo + 1);+ fetchPage(pageNo + 1)}}@@ -57,18 +58,22 @@ export default function WalletAccountSelect(props: Props) {value={value}onChange={onChange}disabled={disabled}- style={{ width: "100%" }}+ style={{ width: '100%' }}onPopupScroll={onPopupScroll}notFoundContent={loading ? <Spin size="small" /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无账户" />}filterOption={(input, option) => (option?.children as unknown as string)?.toLowerCase().includes(input.toLowerCase())}>- {list.map((item) => (+ {list.map(item => (<Option key={item._id} value={item._id}>- {item.userName || item.mail} · {item.type} · {item.account}+ {item.userName || item.mail}+ {' '}+ ·+ {item.type}+ {' '}+ ·+ {item.account}</Option>))}</Select>- );+ )}--diff --git a/project/web/src/components/common/DownloadAppModal.tsx b/project/web/src/components/common/DownloadAppModal.tsxindex 2127f114..bab04ee3 100644--- a/project/web/src/components/common/DownloadAppModal.tsx+++ b/project/web/src/components/common/DownloadAppModal.tsx@@ -1,21 +1,21 @@-import React, { useState } from 'react';-import { Modal, Button, Space, Typography, message } from 'antd';-import { DownloadOutlined, QrcodeOutlined, CopyOutlined, CheckOutlined } from '@ant-design/icons';-import { useTransClient } from '@/app/i18n/client';-import { MAIN_APP_DOWNLOAD_URL, getMainAppDownloadUrlSync } from '@/app/config/appDownloadConfig';-import logo from '@/assets/images/logo.png';-import { QRCode } from 'react-qrcode-logo';+import { CheckOutlined, CopyOutlined, DownloadOutlined, QrcodeOutlined } from '@ant-design/icons'+import { Button, message, Modal, Space, Typography } from 'antd'+import React, { useState } from 'react'+import { QRCode } from 'react-qrcode-logo'+import { getMainAppDownloadUrlSync, MAIN_APP_DOWNLOAD_URL } from '@/app/config/appDownloadConfig'+import { useTransClient } from '@/app/i18n/client'+import logo from '@/assets/images/logo.png'-const { Text, Paragraph } = Typography;+const { Text, Paragraph } = Typographyinterface DownloadAppModalProps {- visible: boolean;- onClose: () => void;- platform?: string; // 平台名称,如"小红书"- appName?: string; // app名称- downloadUrl?: string; // 下载链接- qrCodeUrl?: string; // 二维码图片URL- zIndex?: number; // 弹窗层级+ visible: boolean+ onClose: () => void+ platform?: string // 平台名称,如"小红书"+ appName?: string // app名称+ downloadUrl?: string // 下载链接+ qrCodeUrl?: string // 二维码图片URL+ zIndex?: number // 弹窗层级}/**@@ -25,54 +25,55 @@ interface DownloadAppModalProps {const DownloadAppModal: React.FC<DownloadAppModalProps> = ({visible,onClose,- platform = "",- appName = "Aitoearn App",+ platform = '',+ appName = 'Aitoearn App',downloadUrl,qrCodeUrl = '',- zIndex = 1000+ zIndex = 1000,}) => {- const { t } = useTransClient("common");- const [copySuccess, setCopySuccess] = useState(false);+ const { t } = useTransClient('common')+ const [copySuccess, setCopySuccess] = useState(false)const handleDownload = () => {- const linkToOpen = downloadUrl || getMainAppDownloadUrlSync();- window.open(linkToOpen, '_blank');- };+ const linkToOpen = downloadUrl || getMainAppDownloadUrlSync()+ window.open(linkToOpen, '_blank')+ }const handleCopyLink = async () => {- const linkToCopy = downloadUrl || getMainAppDownloadUrlSync();+ const linkToCopy = downloadUrl || getMainAppDownloadUrlSync()try {- await navigator.clipboard.writeText(linkToCopy);- setCopySuccess(true);- message.success(t('downloadApp.copySuccess' as any));- setTimeout(() => setCopySuccess(false), 2000);- } catch (error) {- message.error(t('downloadApp.copyFailed' as any));+ await navigator.clipboard.writeText(linkToCopy)+ setCopySuccess(true)+ message.success(t('downloadApp.copySuccess' as any))+ setTimeout(() => setCopySuccess(false), 2000)}- };+ catch (error) {+ message.error(t('downloadApp.copyFailed' as any))+ }+ }return (<Modal- title={+ title={(<Space><img src={logo.src} alt="Aitoearn" style={{ width: 20, height: 20, borderRadius: 4 }} /><span>Download Aitoearn App</span></Space>- }+ )}open={visible}onCancel={onClose}footer={[<Button key="close" onClick={onClose}>{t('downloadApp.close')}</Button>,- <Button- key="download"- type="primary"+ <Button+ key="download"+ type="primary"icon={<DownloadOutlined />}onClick={handleDownload}>{t('downloadApp.downloadNow' as any)}- </Button>+ </Button>,]}width={520}centered@@ -84,76 +85,81 @@ const DownloadAppModal: React.FC<DownloadAppModalProps> = ({<div style={{ marginBottom: '24px' }}><img src={logo.src} alt="Aitoearn" style={{ width: 64, height: 64, borderRadius: 16, boxShadow: '0 4px 12px rgba(0,0,0,0.1)' }} /></div>-+{/* 标题 */}<Typography.Title level={4} style={{ marginBottom: '16px', color: '#1f2937' }}>Aitoearn</Typography.Title>-+{/* 描述 */}<Paragraph style={{ color: '#6b7280', marginBottom: '32px', fontSize: '14px', lineHeight: '1.6' }}><span dangerouslySetInnerHTML={{ __html: t('downloadApp.operationDescription' as any, { platform }) }} /></Paragraph>{/* 二维码区域 */}- <div style={{- marginBottom: '32px',+ <div style={{+ marginBottom: '32px',padding: '20px',backgroundColor: '#f9fafb',borderRadius: '12px',- border: '1px solid #e5e7eb'- }}>- {qrCodeUrl ? (- <img- src={qrCodeUrl}- alt="QR Code"- style={{- width: 120,- height: 120,- borderRadius: '8px',- boxShadow: '0 2px 8px rgba(0,0,0,0.1)'- }}- />- ) : (- <QRCode- value={downloadUrl || getMainAppDownloadUrlSync()}- size={120}- logoImage={logo.src}- logoWidth={30}- logoHeight={30}- logoOpacity={0.8}- qrStyle="squares"- eyeRadius={0}- style={{ borderRadius: '8px' }}- />- )}+ border: '1px solid #e5e7eb',+ }}+ >+ {qrCodeUrl+ ? (+ <img+ src={qrCodeUrl}+ alt="QR Code"+ style={{+ width: 120,+ height: 120,+ borderRadius: '8px',+ boxShadow: '0 2px 8px rgba(0,0,0,0.1)',+ }}+ />+ )+ : (+ <QRCode+ value={downloadUrl || getMainAppDownloadUrlSync()}+ size={120}+ logoImage={logo.src}+ logoWidth={30}+ logoHeight={30}+ logoOpacity={0.8}+ qrStyle="squares"+ eyeRadius={0}+ style={{ borderRadius: '8px' }}+ />+ )}</div>{/* 下载链接区域 */}- <div style={{+ <div style={{marginBottom: '24px',padding: '16px',backgroundColor: '#f3f4f6',borderRadius: '8px',- border: '1px solid #d1d5db'- }}>+ border: '1px solid #d1d5db',+ }}+ ><Text type="secondary" style={{ fontSize: '12px', display: 'block', marginBottom: '8px' }}>{t('downloadApp.downloadLink')}</Text>- <div style={{- display: 'flex',- alignItems: 'center',+ <div style={{+ display: 'flex',+ alignItems: 'center',justifyContent: 'space-between',- gap: '8px'- }}>- <Text- // code- style={{- flex: 1,- fontSize: '13px',+ gap: '8px',+ }}+ >+ <Text+ // code+ style={{+ flex: 1,+ fontSize: '13px',wordBreak: 'break-all',textAlign: 'left',-+}}>{downloadUrl || getMainAppDownloadUrlSync()}@@ -162,7 +168,7 @@ const DownloadAppModal: React.FC<DownloadAppModalProps> = ({size="small"icon={copySuccess ? <CheckOutlined /> : <CopyOutlined />}onClick={handleCopyLink}- type={copySuccess ? "primary" : "default"}+ type={copySuccess ? 'primary' : 'default'}>{copySuccess ? t('downloadApp.copied' as any) : t('downloadApp.copy' as any)}</Button>@@ -170,19 +176,20 @@ const DownloadAppModal: React.FC<DownloadAppModalProps> = ({</div>{/* 提示信息 */}- <div style={{- padding: '16px',- backgroundColor: '#eff6ff',+ <div style={{+ padding: '16px',+ backgroundColor: '#eff6ff',borderRadius: '8px',- border: '1px solid #dbeafe'- }}>+ border: '1px solid #dbeafe',+ }}+ ><Text type="secondary" style={{ fontSize: '13px', color: '#1e40af' }}>{t('downloadApp.tip')}</Text></div></div></Modal>- );-};+ )+}-export default DownloadAppModal;\ No newline at end of file+export default DownloadAppModaldiff --git a/project/web/src/components/common/LanguageSwitcher.tsx b/project/web/src/components/common/LanguageSwitcher.tsxindex 307dd0e8..e21d269a 100644--- a/project/web/src/components/common/LanguageSwitcher.tsx+++ b/project/web/src/components/common/LanguageSwitcher.tsx@@ -1,130 +1,131 @@-"use client";+'use client'-import { Button, Dropdown, MenuProps } from "antd";-import { CaretDownOutlined } from "@ant-design/icons";-import Image from "next/image";-import { useRouter } from "next/navigation";-import zhLang from "@/assets/images/zh.png";-import enLang from "@/assets/images/us.png";-import { useGetClientLng } from "@/hooks/useSystem";+import type { MenuProps } from 'antd'+import { CaretDownOutlined } from '@ant-design/icons'+import { Button, Dropdown } from 'antd'+import Image from 'next/image'+import { useRouter } from 'next/navigation'+import enLang from '@/assets/images/us.png'+import zhLang from '@/assets/images/zh.png'+import { useGetClientLng } from '@/hooks/useSystem'export interface LanguageSwitcherProps {- className?: string;- style?: React.CSSProperties;- size?: "small" | "middle" | "large";+ className?: string+ style?: React.CSSProperties+ size?: 'small' | 'middle' | 'large'}-const LanguageSwitcher = ({+function LanguageSwitcher({className,style,- size = "middle",-}: LanguageSwitcherProps) => {- const lang = useGetClientLng();- const router = useRouter();+ size = 'middle',+}: LanguageSwitcherProps) {+ const lang = useGetClientLng()+ const router = useRouter()const handleLanguageChange = (newLng: string) => {// 获取当前路径并替换语言前缀- const currentPath = location.pathname;- const pathWithoutLang = currentPath.replace(`/${lang}`, "") || "/";- const newPath = `/${newLng}${pathWithoutLang}`;+ const currentPath = location.pathname+ const pathWithoutLang = currentPath.replace(`/${lang}`, '') || '/'+ const newPath = `/${newLng}${pathWithoutLang}`- router.push(newPath);- };+ router.push(newPath)+ }// 语言选项配置const languageOptions = [{- key: "en",- label: "English",+ key: 'en',+ label: 'English',flag: enLang,- current: lang === "en",+ current: lang === 'en',},{- key: "zh-CN",- label: "简体中文",+ key: 'zh-CN',+ label: '简体中文',flag: zhLang,- current: lang === "zh-CN",+ current: lang === 'zh-CN',},- ];+ ]- const currentLanguage =- languageOptions.find((lang) => lang.current) || languageOptions[0];+ const currentLanguage+ = languageOptions.find(lang => lang.current) || languageOptions[0]- const languageMenuItems: MenuProps["items"] = languageOptions.map(- (option) => ({+ const languageMenuItems: MenuProps['items'] = languageOptions.map(+ option => ({key: option.key,label: (<divstyle={{- display: "flex",- alignItems: "center",- justifyContent: "space-between",- width: "100%",+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ width: '100%',}}>- <div style={{ display: "flex", alignItems: "center", gap: "8px" }}>+ <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><Imagesrc={option.flag}alt={option.label}width={16}height={16}- style={{ borderRadius: "50%" }}+ style={{ borderRadius: '50%' }}/>- <span style={{ color: option.current ? "#52c41a" : "#000" }}>+ <span style={{ color: option.current ? '#52c41a' : '#000' }}>{option.label}</span></div>- {option.current && <span style={{ color: "#52c41a" }}>✓</span>}+ {option.current && <span style={{ color: '#52c41a' }}>✓</span>}</div>),onClick: () => handleLanguageChange(option.key),}),- );+ )const getButtonSize = () => {switch (size) {- case "small":+ case 'small':return {- padding: "2px 6px",- fontSize: "10px",+ padding: '2px 6px',+ fontSize: '10px',iconSize: 12,- };- case "large":+ }+ case 'large':return {- padding: "6px 12px",- fontSize: "14px",+ padding: '6px 12px',+ fontSize: '14px',iconSize: 16,- };+ }default:return {- padding: "4px 8px",- fontSize: "12px",+ padding: '4px 8px',+ fontSize: '12px',iconSize: 14,- };+ }}- };+ }- const buttonConfig = getButtonSize();+ const buttonConfig = getButtonSize()return (<Dropdownmenu={{ items: languageMenuItems }}- trigger={["click"]}+ trigger={['click']}placement="bottomRight"><Buttontype="text"className={className}style={{- display: "flex",- alignItems: "center",- gap: "8px",- padding: "4px 8px",- height: "auto",- fontSize: "12px",- backgroundColor: "#fff",- border: "1px solid #EBEDEC",- borderRadius: "30px",+ display: 'flex',+ alignItems: 'center',+ gap: '8px',+ padding: '4px 8px',+ height: 'auto',+ fontSize: '12px',+ backgroundColor: '#fff',+ border: '1px solid #EBEDEC',+ borderRadius: '30px',...style,}}>@@ -133,13 +134,13 @@ const LanguageSwitcher = ({alt={currentLanguage.label}width={buttonConfig.iconSize}height={buttonConfig.iconSize}- style={{ borderRadius: "50%" }}+ style={{ borderRadius: '50%' }}/>- <span style={{ fontSize: "12px" }}>{currentLanguage.label}</span>+ <span style={{ fontSize: '12px' }}>{currentLanguage.label}</span><CaretDownOutlined style={{ fontSize: buttonConfig.fontSize }} /></Button></Dropdown>- );-};+ )+}-export default LanguageSwitcher;+export default LanguageSwitcherdiff --git a/project/web/src/components/common/index.ts b/project/web/src/components/common/index.tsindex 2c993189..8ae06881 100644--- a/project/web/src/components/common/index.ts+++ b/project/web/src/components/common/index.ts@@ -1,4 +1,3 @@// 通用组件导出-export { default as DownloadAppModal } from './DownloadAppModal';-export { default as LanguageSwitcher } from './LanguageSwitcher';-+export { default as DownloadAppModal } from './DownloadAppModal'+export { default as LanguageSwitcher } from './LanguageSwitcher'diff --git a/project/web/src/components/modals/PointsDetailModal.tsx b/project/web/src/components/modals/PointsDetailModal.tsxindex 4273e878..0806726f 100644--- a/project/web/src/components/modals/PointsDetailModal.tsx+++ b/project/web/src/components/modals/PointsDetailModal.tsx@@ -1,69 +1,74 @@-"use client";+'use client'-import { memo, useEffect, useState } from "react";-import { Modal, Tabs, Spin, Popover } from "antd";-import { InfoCircleOutlined } from "@ant-design/icons";-import { useTransClient } from "@/app/i18n/client";-import styles from "./outsideCloseModal.module.css";-import { getPointsRecordsApi } from "@/api/apiReq";-import { useUserStore } from "@/store/user";+import { InfoCircleOutlined } from '@ant-design/icons'+import { Modal, Popover, Spin, Tabs } from 'antd'+import { memo, useEffect, useState } from 'react'+import { getPointsRecordsApi } from '@/api/apiReq'+import { useTransClient } from '@/app/i18n/client'+import { useUserStore } from '@/store/user'+import styles from './outsideCloseModal.module.css'interface PointsDetailModalProps {- open: boolean;- onClose: () => void;+ open: boolean+ onClose: () => void}-type PointsRecord = {- _id: string;- amount: number; // 正数获得 负数消耗- type?: string;- description?: string;- createdAt: string | Date;-};+interface PointsRecord {+ _id: string+ amount: number // 正数获得 负数消耗+ type?: string+ description?: string+ createdAt: string | Date+}const PointsDetailModal = memo(({ open, onClose }: PointsDetailModalProps) => {- const [loading, setLoading] = useState(false);- const [records, setRecords] = useState<PointsRecord[]>([]);- const [activeKey, setActiveKey] = useState<string>('all');- const { userInfo } = useUserStore();- const { t } = useTransClient('vip');-+ const [loading, setLoading] = useState(false)+ const [records, setRecords] = useState<PointsRecord[]>([])+ const [activeKey, setActiveKey] = useState<string>('all')+ const { userInfo } = useUserStore()+ const { t } = useTransClient('vip')+// 辅助函数处理翻译- const translate = (key: string) => t(key as any);+ const translate = (key: string) => t(key as any)const fetchRecords = async () => {- setLoading(true);+ setLoading(true)try {- const res: any = await getPointsRecordsApi({ page: 1, pageSize: 50 });- const list = res?.data?.list || [];- setRecords(list);- } finally {- setLoading(false);+ const res: any = await getPointsRecordsApi({ page: 1, pageSize: 50 })+ const list = res?.data?.list || []+ setRecords(list)+ }+ finally {+ setLoading(false)}- };+ }useEffect(() => {- if (open) fetchRecords();- }, [open]);+ if (open)+ fetchRecords()+ }, [open])const filtered = records.filter((r) => {- if (activeKey === 'all') return true;- if (activeKey === 'spend') return r.amount < 0;- if (activeKey === 'earn') return r.amount > 0;- return true;- });+ if (activeKey === 'all')+ return true+ if (activeKey === 'spend')+ return r.amount < 0+ if (activeKey === 'earn')+ return r.amount > 0+ return true+ })// 剩余积分以用户信息中的 score 为准- const remain = Math.floor((userInfo?.score as number) || 0);- const subscribed = 0;- const recharged = records.filter(r => r.amount > 0 && (r as any).source === 'recharge').reduce((s, r) => s + r.amount, 0);- const gifted = records.filter(r => r.amount > 0 && (r as any).source === 'gift').reduce((s, r) => s + r.amount, 0);+ const remain = Math.floor((userInfo?.score as number) || 0)+ const subscribed = 0+ const recharged = records.filter(r => r.amount > 0 && (r as any).source === 'recharge').reduce((s, r) => s + r.amount, 0)+ const gifted = records.filter(r => r.amount > 0 && (r as any).source === 'gift').reduce((s, r) => s + r.amount, 0)const endOfToday = (() => {- const d = new Date();- d.setHours(23, 59, 0, 0);- return d.toLocaleString();- })();+ const d = new Date()+ d.setHours(23, 59, 0, 0)+ return d.toLocaleString()+ })()return (<Modal@@ -81,46 +86,49 @@ const PointsDetailModal = memo(({ open, onClose }: PointsDetailModalProps) => {<div style={{ padding: '16px 20px 0 20px' }}><h3 style={{ margin: 0, fontSize: 18, fontWeight: 700, color: '#0f172a' }}>{translate('points.title')}</h3><div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 16, color: '#111827', flexWrap: 'wrap' }}>- <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, flex: 1, justifyContent: 'center', flexDirection:'column' }}>+ <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, flex: 1, justifyContent: 'center', flexDirection: 'column' }}><div style={{ fontSize: 12, color: '#6b7280' }}>{translate('points.remaining')}</div><div style={{ fontWeight: 700 }}>{remain}</div></div><div style={{ color: '#6b7280' }}>=</div>- <div style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 1, justifyContent: 'center' , flexDirection:'column'}}>+ <div style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 1, justifyContent: 'center', flexDirection: 'column' }}><div style={{ fontSize: 12, color: '#6b7280' }}>{translate('points.subscribed')}</div><div style={{ fontWeight: 700 }}>{subscribed}</div></div><div style={{ color: '#6b7280' }}>+</div>- <div style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 1, justifyContent: 'center' , flexDirection:'column'}}>+ <div style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 1, justifyContent: 'center', flexDirection: 'column' }}><div style={{ fontSize: 12, color: '#6b7280' }}>{translate('points.recharged')}</div><div style={{ fontWeight: 700 }}>{recharged}</div></div><div style={{ color: '#6b7280' }}>+</div>- <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, flex: 1 , justifyContent: 'flex-end', flexDirection:'column'}}>+ <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, flex: 1, justifyContent: 'flex-end', flexDirection: 'column' }}><div style={{ fontSize: 12, color: '#6b7280' }}>{translate('points.gifted')}</div>- <div style={{ fontWeight: 700 }}>{gifted } - <Popover- trigger="hover"- placement="bottomRight"- content={- <div style={{ padding: 8 }}>- <div style={{ border: '1px solid #eef2f7', borderRadius: 10, padding: 12, minWidth: 260 }}>- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>- <span style={{ color: '#6b7280' }}>{translate('points.remaining')}</span>- <span style={{ fontWeight: 700 }}>{remain}</span>- </div>- <div style={{ display: 'flex', justifyContent: 'space-between' }}>- <span style={{ color: '#6b7280' }}>{translate('points.validity')}</span>- <span style={{ fontWeight: 700 }}>{endOfToday}</span>+ <div style={{ fontWeight: 700 }}>+ {gifted }+ {' '}+ + <Popover+ trigger="hover"+ placement="bottomRight"+ content={(+ <div style={{ padding: 8 }}>+ <div style={{ border: '1px solid #eef2f7', borderRadius: 10, padding: 12, minWidth: 260 }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>+ <span style={{ color: '#6b7280' }}>{translate('points.remaining')}</span>+ <span style={{ fontWeight: 700 }}>{remain}</span>+ </div>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}>+ <span style={{ color: '#6b7280' }}>{translate('points.validity')}</span>+ <span style={{ fontWeight: 700 }}>{endOfToday}</span>+ </div></div></div>- </div>- }- >- <InfoCircleOutlined style={{ color: '#9ca3af' }} />- </Popover>+ )}+ >+ <InfoCircleOutlined style={{ color: '#9ca3af' }} />+ </Popover></div>-+</div></div></div>@@ -141,25 +149,30 @@ const PointsDetailModal = memo(({ open, onClose }: PointsDetailModalProps) => {{/* 列表 */}<div style={{ padding: '0 20px 16px 20px', minHeight: 550, maxHeight: '60vh', overflowY: 'auto' }}><Spin spinning={loading}>- {filtered.length === 0 ? (- <div style={{ textAlign: 'center', padding: '60px 0', color: '#9ca3af' }}>{translate('points.noData')}</div>- ) : (- <div style={{ display: 'grid', gap: 12 }}>- {filtered.map((r, index) => (- <div key={r._id || `record-${index}`} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 14px', border: '1px solid #eef2f7', borderRadius: 10 }}>- <div>- <div style={{ fontWeight: 600, color: '#111827' }}>- {translate('points.recordChange')} - {r.type ? translate(`points.recordTypes.${r.type}`) : translate('points.recordChange')}+ {filtered.length === 0+ ? (+ <div style={{ textAlign: 'center', padding: '60px 0', color: '#9ca3af' }}>{translate('points.noData')}</div>+ )+ : (+ <div style={{ display: 'grid', gap: 12 }}>+ {filtered.map((r, index) => (+ <div key={r._id || `record-${index}`} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 14px', border: '1px solid #eef2f7', borderRadius: 10 }}>+ <div>+ <div style={{ fontWeight: 600, color: '#111827' }}>+ {translate('points.recordChange')}+ {' '}+ -+ {r.type ? translate(`points.recordTypes.${r.type}`) : translate('points.recordChange')}+ </div>+ <div style={{ fontSize: 12, color: '#6b7280', marginTop: 4 }}>{new Date(r.createdAt).toLocaleString()}</div>+ </div>+ <div style={{ fontWeight: 700, color: r.amount >= 0 ? '#10b981' : '#ef4444' }}>+ {r.amount >= 0 ? `+${r.amount}` : r.amount}+ </div></div>- <div style={{ fontSize: 12, color: '#6b7280', marginTop: 4 }}>{new Date(r.createdAt).toLocaleString()}</div>- </div>- <div style={{ fontWeight: 700, color: r.amount >= 0 ? '#10b981' : '#ef4444' }}>- {r.amount >= 0 ? `+${r.amount}` : r.amount}- </div>+ ))}</div>- ))}- </div>- )}+ )}</Spin></div>@@ -168,9 +181,7 @@ const PointsDetailModal = memo(({ open, onClose }: PointsDetailModalProps) => {</div></div></Modal>- );-});--export default PointsDetailModal;-+ )+})+export default PointsDetailModaldiff --git a/project/web/src/components/modals/PointsRechargeModal.tsx b/project/web/src/components/modals/PointsRechargeModal.tsxindex f827bbbc..70326193 100644--- a/project/web/src/components/modals/PointsRechargeModal.tsx+++ b/project/web/src/components/modals/PointsRechargeModal.tsx@@ -1,68 +1,69 @@-"use client";+'use client'-import { memo, useEffect, useMemo, useRef, useState } from "react";-import { Modal, Button, InputNumber, Typography, Space, message } from "antd";-import { useTransClient } from "@/app/i18n/client";-import styles from "./outsideCloseModal.module.css";-import { createPaymentOrderApi, PaymentType } from "@/api/vip";-import { useUserStore } from "@/store/user";+import { Button, InputNumber, message, Modal, Space, Typography } from 'antd'+import { memo, useEffect, useMemo, useRef, useState } from 'react'+import { createPaymentOrderApi, PaymentType } from '@/api/vip'+import { useTransClient } from '@/app/i18n/client'+import { useUserStore } from '@/store/user'+import styles from './outsideCloseModal.module.css'interface PointsRechargeModalProps {- open: boolean;- onClose: () => void;+ open: boolean+ onClose: () => void}const PointsRechargeModal = memo(({ open, onClose }: PointsRechargeModalProps) => {- const [rechargeAmount, setRechargeAmount] = useState<number>(8);- const [buyLoading, setBuyLoading] = useState(false);- const userStore = useUserStore();- const { t } = useTransClient('vip');- const modalWidth = useMemo(() => 520, []);- const sliderTrackRef = useRef<HTMLDivElement | null>(null);- const [dragging, setDragging] = useState(false);-+ const [rechargeAmount, setRechargeAmount] = useState<number>(8)+ const [buyLoading, setBuyLoading] = useState(false)+ const userStore = useUserStore()+ const { t } = useTransClient('vip')+ const modalWidth = useMemo(() => 520, [])+ const sliderTrackRef = useRef<HTMLDivElement | null>(null)+ const [dragging, setDragging] = useState(false)+// 辅助函数处理翻译- const translate = (key: string) => t(key as any);+ const translate = (key: string) => t(key as any)- const amountToPercent = (amount: number) => ((amount - 1) / 49) * 100; // 1..50+ const amountToPercent = (amount: number) => ((amount - 1) / 49) * 100 // 1..50const percentToAmount = (percent: number) => {- const clamped = Math.max(0, Math.min(100, percent));- const val = 1 + Math.round((clamped / 100) * 49);- return val;- };+ const clamped = Math.max(0, Math.min(100, percent))+ const val = 1 + Math.round((clamped / 100) * 49)+ return val+ }const handleSliderClick = (e: React.MouseEvent<HTMLDivElement>) => {- const rect = (e.currentTarget as HTMLDivElement).getBoundingClientRect();- const percent = ((e.clientX - rect.left) / rect.width) * 100;- setRechargeAmount(percentToAmount(percent));- };+ const rect = (e.currentTarget as HTMLDivElement).getBoundingClientRect()+ const percent = ((e.clientX - rect.left) / rect.width) * 100+ setRechargeAmount(percentToAmount(percent))+ }const onMouseDownHandle = (e: React.MouseEvent<HTMLDivElement>) => {- e.stopPropagation();- setDragging(true);- };+ e.stopPropagation()+ setDragging(true)+ }useEffect(() => {const onMove = (e: MouseEvent) => {- if (!dragging || !sliderTrackRef.current) return;- const rect = sliderTrackRef.current.getBoundingClientRect();- const percent = ((e.clientX - rect.left) / rect.width) * 100;- setRechargeAmount(percentToAmount(percent));- };- const onUp = () => setDragging(false);+ if (!dragging || !sliderTrackRef.current)+ return+ const rect = sliderTrackRef.current.getBoundingClientRect()+ const percent = ((e.clientX - rect.left) / rect.width) * 100+ setRechargeAmount(percentToAmount(percent))+ }+ const onUp = () => setDragging(false)if (dragging) {- document.addEventListener('mousemove', onMove);- document.addEventListener('mouseup', onUp);+ document.addEventListener('mousemove', onMove)+ document.addEventListener('mouseup', onUp)}return () => {- document.removeEventListener('mousemove', onMove);- document.removeEventListener('mouseup', onUp);- };- }, [dragging]);+ document.removeEventListener('mousemove', onMove)+ document.removeEventListener('mouseup', onUp)+ }+ }, [dragging])return (<Modal- title={<span style={{fontWeight:700}}>{translate('recharge.title')}</span>}+ title={<span style={{ fontWeight: 700 }}>{translate('recharge.title')}</span>}open={open}onCancel={onClose}footer={null}@@ -71,10 +72,10 @@ const PointsRechargeModal = memo(({ open, onClose }: PointsRechargeModalProps) =className={styles.outsideCloseModal}destroyOnHidden>- <Space direction="vertical" size={16} style={{width:'100%'}}>- <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:18}}>- <span style={{color:'#6b7280'}}>{translate('recharge.current')}</span>- <span style={{fontWeight:700}}>{Math.floor(userStore.userInfo?.score || 0)}</span>+ <Space direction="vertical" size={16} style={{ width: '100%' }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 18 }}>+ <span style={{ color: '#6b7280' }}>{translate('recharge.current')}</span>+ <span style={{ fontWeight: 700 }}>{Math.floor(userStore.userInfo?.score || 0)}</span></div><div><Typography.Text type="secondary">{translate('recharge.price')}</Typography.Text>@@ -88,7 +89,7 @@ const PointsRechargeModal = memo(({ open, onClose }: PointsRechargeModalProps) =height: 8,background: '#e5e7eb',borderRadius: 6,- cursor: 'pointer'+ cursor: 'pointer',}}><div@@ -99,7 +100,7 @@ const PointsRechargeModal = memo(({ open, onClose }: PointsRechargeModalProps) =height: '100%',width: `${amountToPercent(rechargeAmount)}%`,background: '#a66ae4',- borderRadius: 6+ borderRadius: 6,}}/><div@@ -115,58 +116,72 @@ const PointsRechargeModal = memo(({ open, onClose }: PointsRechargeModalProps) =borderRadius: '50%',transform: 'translateY(-50%)',boxShadow: '0 1px 4px rgba(0,0,0,0.15)',- cursor: 'grab'+ cursor: 'grab',}}/></div>- <div style={{ display:'flex', justifyContent:'space-between', fontSize:12, color:'#6b7280', marginTop:6 }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: '#6b7280', marginTop: 6 }}><span>{translate('recharge.range').split('-')[0]}</span><span>{translate('recharge.range').split('-')[1]}</span></div></div>- <div style={{marginTop:28, display:'flex', alignItems:'center', gap:12}}>- <InputNumber min={1} max={50} value={rechargeAmount} onChange={(v) => setRechargeAmount(Number(v) || 1)} />- <span>* 1000 {translate('recharge.unit')}</span>+ <div style={{ marginTop: 28, display: 'flex', alignItems: 'center', gap: 12 }}>+ <InputNumber min={1} max={50} value={rechargeAmount} onChange={v => setRechargeAmount(Number(v) || 1)} />+ <span>+ * 1000+ {translate('recharge.unit')}+ </span></div></div>- <div style={{display:'flex', justifyContent:'space-between'}}>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>{translate('recharge.amount')}</span>- <span style={{fontWeight:700}}>{rechargeAmount * 1000}</span>+ <span style={{ fontWeight: 700 }}>{rechargeAmount * 1000}</span></div>- <div style={{display:'flex', justifyContent:'space-between'}}>+ <div style={{ display: 'flex', justifyContent: 'space-between' }}><span>{translate('recharge.total')}</span>- <span style={{fontWeight:700}}>${(rechargeAmount * 15).toFixed(2)}</span>+ <span style={{ fontWeight: 700 }}>+ $+ {(rechargeAmount * 15).toFixed(2)}+ </span></div>- <Button type="primary" block loading={buyLoading} onClick={async () => {- try {- setBuyLoading(true);- if (!userStore.userInfo?.id) {- message.error(translate('pleaseLoginFirst'));- return;+ <Button+ type="primary"+ block+ loading={buyLoading}+ onClick={async () => {+ try {+ setBuyLoading(true)+ if (!userStore.userInfo?.id) {+ message.error(translate('pleaseLoginFirst'))+ return+ }+ const res: any = await createPaymentOrderApi({+ mode: 'payment',+ payment: PaymentType.POINTS,+ metadata: { userId: userStore.userInfo.id },+ quantity: rechargeAmount,+ returnTo: userStore.lang === 'zh-CN' ? 'https://aitoearn.ai/zh-CN/profile' : 'https://aitoearn.ai/en/profile',+ })+ if (res?.code === 0 && res.data?.url) {+ window.open(res.data.url, '_blank')+ }+ else {+ message.error(res?.message || res?.msg || translate('createPaymentOrderFailed'))+ }}- const res: any = await createPaymentOrderApi({- mode: 'payment',- payment: PaymentType.POINTS,- metadata: { userId: userStore.userInfo.id },- quantity: rechargeAmount,- returnTo: userStore.lang === 'zh-CN' ? 'https://aitoearn.ai/zh-CN/profile' : 'https://aitoearn.ai/en/profile'- });- if (res?.code === 0 && res.data?.url) {- window.open(res.data.url, '_blank');- } else {- message.error(res?.message || res?.msg || translate('createPaymentOrderFailed'));+ catch (e) {+ message.error(translate('createPaymentOrderError'))}- } catch (e) {- message.error(translate('createPaymentOrderError'));- } finally {- setBuyLoading(false);- }- }}>{translate('recharge.buyNow')}</Button>+ finally {+ setBuyLoading(false)+ }+ }}+ >+ {translate('recharge.buyNow')}+ </Button></Space></Modal>- );-});--export default PointsRechargeModal;-+ )+})+export default PointsRechargeModaldiff --git a/project/web/src/components/modals/SubscriptionManagementModal.tsx b/project/web/src/components/modals/SubscriptionManagementModal.tsxindex 362430da..ae568129 100644--- a/project/web/src/components/modals/SubscriptionManagementModal.tsx+++ b/project/web/src/components/modals/SubscriptionManagementModal.tsx@@ -1,143 +1,150 @@-"use client";+'use client'-import { memo, useState, useEffect } from "react";-import { Modal, Tabs, Table, Card, Button, Tag, Descriptions, message } from "antd";-import { useTransClient } from "@/app/i18n/client";-import { useUserStore } from "@/store/user";-import {- getOrderListApi,- getSubscriptionListApi,+import type {+ Order,+ OrderListParams,+ RefundParams,+ Subscription,+ SubscriptionListParams,+} from '@/api/types/payment'+import { Button, Card, Descriptions, message, Modal, Table, Tabs, Tag } from 'antd'+import Image from 'next/image'+import { memo, useEffect, useState } from 'react'+import {+ cancelSubscriptionApi,getOrderDetailApi,+ getOrderListApi,+ getSubscriptionListApi,refundOrderApi,unsubscribeApi,- cancelSubscriptionApi-} from "@/api/payment";-import {- Order,- Subscription,- OrderListParams,- SubscriptionListParams,- RefundParams,- UnsubscribeParams,- OrderStatus,- PaymentType,+} from '@/api/payment'+import {+ OrderStatus,PaymentMode,+ PaymentType,+ SubscriptionPlan,SubscriptionStatus,- SubscriptionPlan-} from "@/api/types/payment";-import styles from "./subscriptionManagementModal.module.css";+ UnsubscribeParams,+} from '@/api/types/payment'+import { useTransClient } from '@/app/i18n/client'+import plusvip from '@/assets/images/plusvip.png'-import Image from "next/image";-import plusvip from "@/assets/images/plusvip.png";+import { useUserStore } from '@/store/user'+import styles from './subscriptionManagementModal.module.css'-const { TabPane } = Tabs;+const { TabPane } = Tabsinterface SubscriptionManagementModalProps {- open: boolean;- onClose: () => void;+ open: boolean+ onClose: () => void}const SubscriptionManagementModal = memo(({ open, onClose }: SubscriptionManagementModalProps) => {- const { t: tProfile } = useTransClient('profile');- const { t: tVip } = useTransClient('vip');- const { userInfo } = useUserStore();-+ const { t: tProfile } = useTransClient('profile')+ const { t: tVip } = useTransClient('vip')+ const { userInfo } = useUserStore()+// 状态判断辅助函数const getVipStatusInfo = (status: string) => {switch (status) {case 'none':- return { isVip: false, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false };+ return { isVip: false, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false }case 'trialing':- return { isVip: true, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false };+ return { isVip: true, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false }case 'monthly_once':- return { isVip: true, isMonthly: true, isYearly: false, isAutoRenew: false, isOnce: true };+ return { isVip: true, isMonthly: true, isYearly: false, isAutoRenew: false, isOnce: true }case 'yearly_once':- return { isVip: true, isMonthly: false, isYearly: true, isAutoRenew: false, isOnce: true };+ return { isVip: true, isMonthly: false, isYearly: true, isAutoRenew: false, isOnce: true }case 'active_monthly':- return { isVip: true, isMonthly: true, isYearly: false, isAutoRenew: true, isOnce: false };+ return { isVip: true, isMonthly: true, isYearly: false, isAutoRenew: true, isOnce: false }case 'active_yearly':- return { isVip: true, isMonthly: false, isYearly: true, isAutoRenew: true, isOnce: false };+ return { isVip: true, isMonthly: false, isYearly: true, isAutoRenew: true, isOnce: false }case 'active_nonrenewing':- return { isVip: true, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false };+ return { isVip: true, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false }case 'expired':- return { isVip: false, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false };+ return { isVip: false, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false }default:- return { isVip: false, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false };+ return { isVip: false, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false }}- };-+ }+// 订单相关状态- const [orders, setOrders] = useState<Order[]>([]);- const [subscriptions, setSubscriptions] = useState<Subscription[]>([]);- const [ordersLoading, setOrdersLoading] = useState(false);- const [subscriptionsLoading, setSubscriptionsLoading] = useState(false);+ const [orders, setOrders] = useState<Order[]>([])+ const [subscriptions, setSubscriptions] = useState<Subscription[]>([])+ const [ordersLoading, setOrdersLoading] = useState(false)+ const [subscriptionsLoading, setSubscriptionsLoading] = useState(false)const [ordersPagination, setOrdersPagination] = useState({current: 1,pageSize: 10,- total: 0- });+ total: 0,+ })const [subscriptionsPagination, setSubscriptionsPagination] = useState({current: 1,pageSize: 10,- total: 0- });-+ total: 0,+ })+// 订单详情弹窗状态- const [orderDetailVisible, setOrderDetailVisible] = useState(false);- const [orderDetailLoading, setOrderDetailLoading] = useState(false);- const [currentOrderDetail, setCurrentOrderDetail] = useState<Order | null>(null);+ const [orderDetailVisible, setOrderDetailVisible] = useState(false)+ const [orderDetailLoading, setOrderDetailLoading] = useState(false)+ const [currentOrderDetail, setCurrentOrderDetail] = useState<Order | null>(null)// 获取购买记录const fetchOrders = async (params: OrderListParams) => {- setOrdersLoading(true);+ setOrdersLoading(true)try {- const response = await getOrderListApi(params);+ const response = await getOrderListApi(params)if (response?.code === 0 && response.data) {- const data = response.data as any;- setOrders(data.list || []);+ const data = response.data as any+ setOrders(data.list || [])setOrdersPagination({current: data.page || params.page,pageSize: data.pageSize || params.size,- total: data.total || 0- });+ total: data.total || 0,+ })}- } catch (error) {- console.error('获取订单列表失败:', error);- } finally {- setOrdersLoading(false);}- };+ catch (error) {+ console.error('获取订单列表失败:', error)+ }+ finally {+ setOrdersLoading(false)+ }+ }// 获取订阅列表const fetchSubscriptions = async (params: SubscriptionListParams) => {- setSubscriptionsLoading(true);+ setSubscriptionsLoading(true)try {- const response:any = await getSubscriptionListApi(params);+ const response: any = await getSubscriptionListApi(params)if (response?.code === 0 && response.data) {- const data = response.data as any;+ const data = response.data as any// 如果返回的是数组,直接使用;如果是对象,取list字段if (Array.isArray(data)) {- setSubscriptions(data);+ setSubscriptions(data)setSubscriptionsPagination({current: params.page,pageSize: params.size,- total: data.length- });- } else {- setSubscriptions(data.list || []);+ total: data.length,+ })+ }+ else {+ setSubscriptions(data.list || [])setSubscriptionsPagination({current: data.page || params.page,pageSize: data.pageSize || params.size,- total: data.total || 0- });+ total: data.total || 0,+ })}}- } catch (error) {- console.error('获取订阅列表失败:', error);- } finally {- setSubscriptionsLoading(false);}- };+ catch (error) {+ console.error('获取订阅列表失败:', error)+ }+ finally {+ setSubscriptionsLoading(false)+ }+ }// 处理退款const handleRefund = async (order: Order) => {@@ -145,116 +152,117 @@ const SubscriptionManagementModal = memo(({ open, onClose }: SubscriptionManagemconst params: RefundParams = {charge: order.id,payment_intent: order.payment_intent || order.id,- userId: userInfo?.id || ''- };- const response = await refundOrderApi(params);+ userId: userInfo?.id || '',+ }+ const response = await refundOrderApi(params)if (response?.code === 0) {- message.success(tProfile('refundSubmitted'));- fetchOrders({ page: ordersPagination.current - 1, size: ordersPagination.pageSize });- } else {- message.error(response?.message || tProfile('refundFailed'));+ message.success(tProfile('refundSubmitted'))+ fetchOrders({ page: ordersPagination.current - 1, size: ordersPagination.pageSize })+ }+ else {+ message.error(response?.message || tProfile('refundFailed'))}- } catch (error) {- console.error('退款失败:', error);- message.error(tProfile('refundFailed'));}- };+ catch (error) {+ console.error('退款失败:', error)+ message.error(tProfile('refundFailed'))+ }+ }// 处理退订const handleUnsubscribe = async (subscription: Subscription) => {try {const params: any = {- id: subscription.id- };- const response = await unsubscribeApi(params);+ id: subscription.id,+ }+ const response = await unsubscribeApi(params)if (response?.code === 0) {- message.success(tProfile('unsubscribeSuccess'));- fetchSubscriptions({ page: subscriptionsPagination.current - 1, size: subscriptionsPagination.pageSize });+ message.success(tProfile('unsubscribeSuccess'))+ fetchSubscriptions({ page: subscriptionsPagination.current - 1, size: subscriptionsPagination.pageSize })}- } catch (error) {- console.error('退订失败:', error);}- };---+ catch (error) {+ console.error('退订失败:', error)+ }+ }const handleResumeSubscription = async (subscription: Subscription) => {try {const params: any = {- id: subscription.id- };- const response = await cancelSubscriptionApi(params);+ id: subscription.id,+ }+ const response = await cancelSubscriptionApi(params)if (response?.code === 0) {- message.success(tProfile('resumeSuccess' as any));- fetchSubscriptions({ page: subscriptionsPagination.current, size: subscriptionsPagination.pageSize });+ message.success(tProfile('resumeSuccess' as any))+ fetchSubscriptions({ page: subscriptionsPagination.current, size: subscriptionsPagination.pageSize })}- } catch (error) {- console.error('恢复订阅失败:', error);}- };-+ catch (error) {+ console.error('恢复订阅失败:', error)+ }+ }// 获取订单详情const fetchOrderDetail = async (orderId: string) => {- setOrderDetailLoading(true);+ setOrderDetailLoading(true)try {- const response: any = await getOrderDetailApi(orderId);+ const response: any = await getOrderDetailApi(orderId)if (response?.code === 0 && response.data) {- setCurrentOrderDetail(response.data[0]);- setOrderDetailVisible(true);- } else {- message.error(tProfile('getOrderDetailFailed'));+ setCurrentOrderDetail(response.data[0])+ setOrderDetailVisible(true)+ }+ else {+ message.error(tProfile('getOrderDetailFailed'))}- } catch (error) {- console.error('获取订单详情失败:', error);- message.error(tProfile('getOrderDetailFailed'));- } finally {- setOrderDetailLoading(false);}- };+ catch (error) {+ console.error('获取订单详情失败:', error)+ message.error(tProfile('getOrderDetailFailed'))+ }+ finally {+ setOrderDetailLoading(false)+ }+ }// 订单状态标签const getOrderStatusTag = (status: OrderStatus | string) => {- const statusMap: Record<string, { color: string; text: string }> = {+ const statusMap: Record<string, { color: string, text: string }> = {[OrderStatus.COMPLETE]: { color: 'green', text: tProfile('paymentSuccess') },[OrderStatus.OPEN]: { color: 'orange', text: tProfile('waitingForPayment') },- [OrderStatus.EXPIRED]: { color: 'red', text: tProfile('orderExpired' as any) }- };- const config = statusMap[status as string] || { color: 'default', text: `${tProfile('status')}${status}` };- return <Tag color={config.color}>{config.text}</Tag>;- };+ [OrderStatus.EXPIRED]: { color: 'red', text: tProfile('orderExpired' as any) },+ }+ const config = statusMap[status as string] || { color: 'default', text: `${tProfile('status')}${status}` }+ return <Tag color={config.color}>{config.text}</Tag>+ }// 支付类型文本const getPaymentTypeText = (paymentType: string) => {const typeMap: any = {[PaymentType.ONCE_MONTH]: tProfile('oneTimeMonthly'),[PaymentType.MONTH]: tProfile('monthlySubscription'),- [PaymentType.YEAR]: tProfile('yearlySubscription')- };- return typeMap[paymentType as PaymentType] || paymentType || tProfile('unknown');- };+ [PaymentType.YEAR]: tProfile('yearlySubscription'),+ }+ return typeMap[paymentType as PaymentType] || paymentType || tProfile('unknown')+ }// 获取订阅模式文本 (根据 mode 字段)const getSubscriptionModeText = (mode: PaymentMode | string) => {if (mode === PaymentMode.PAYMENT) {- return tVip('oneTimePurchase' as any); // 一次性支付- } else if (mode === PaymentMode.SUBSCRIPTION) {- return tProfile('subscription' as any); // 订阅+ return tVip('oneTimePurchase' as any) // 一次性支付}- return mode || tProfile('unknown');- };-+ else if (mode === PaymentMode.SUBSCRIPTION) {+ return tProfile('subscription' as any) // 订阅+ }+ return mode || tProfile('unknown')+ }// 弹窗打开时加载数据useEffect(() => {if (open) {- fetchOrders({ page: 1, size: 10 });- fetchSubscriptions({ page: 1, size: 10 });-+ fetchOrders({ page: 1, size: 10 })+ fetchSubscriptions({ page: 1, size: 10 })}- }, [open]);-+ }, [open])return (<>@@ -277,234 +285,270 @@ const SubscriptionManagementModal = memo(({ open, onClose }: SubscriptionManagem<div className={styles.membershipCard}><div className={styles.membershipInfo}><div className={styles.membershipIcon}>- <Image src={plusvip} alt="plusvip" style={{ width: 28, height: 'auto', marginTop: -5 }}/>+ <Image src={plusvip} alt="plusvip" style={{ width: 28, height: 'auto', marginTop: -5 }} /></div><div className={styles.membershipDetails}><div className={styles.membershipName}>{(() => {- if (!userInfo?.vipInfo) return tVip('modal.vipInfo.monthly' as any);- const statusInfo = getVipStatusInfo(userInfo.vipInfo.status);+ if (!userInfo?.vipInfo)+ return tVip('modal.vipInfo.monthly' as any)+ const statusInfo = getVipStatusInfo(userInfo.vipInfo.status)if (statusInfo.isYearly && statusInfo.isAutoRenew) {- return tVip('modal.vipInfo.yearly' as any);- } else if (statusInfo.isYearly && !statusInfo.isAutoRenew) {- return tVip('modal.vipInfo.yearly' as any) + ` (${tVip('modal.vipInfo.singleMonth' as any)})`;- } else if (statusInfo.isMonthly && statusInfo.isAutoRenew) {- return tVip('modal.vipInfo.monthly' as any);- } else if (statusInfo.isMonthly && !statusInfo.isAutoRenew) {- return tVip('modal.vipInfo.monthly' as any) + ` (${tVip('modal.vipInfo.singleMonth' as any)})`;- } else if (statusInfo.isOnce) {- return statusInfo.isYearly ? tVip('modal.vipInfo.yearly' as any) + ` (${tVip('modal.vipInfo.singleMonth' as any)})` : tVip('modal.vipInfo.monthly' as any) + ` (${tVip('modal.vipInfo.singleMonth' as any)})`;- } else if (userInfo.vipInfo.status === 'trialing') {- return tVip('modal.vipInfo.monthly' as any) + ` (${tVip('modal.vipInfo.trial' as any)})`;- } else if (userInfo.vipInfo.status === 'active_nonrenewing') {- return tVip('modal.vipInfo.cancelled' as any);+ return tVip('modal.vipInfo.yearly' as any)+ }+ else if (statusInfo.isYearly && !statusInfo.isAutoRenew) {+ return `${tVip('modal.vipInfo.yearly' as any)} (${tVip('modal.vipInfo.singleMonth' as any)})`+ }+ else if (statusInfo.isMonthly && statusInfo.isAutoRenew) {+ return tVip('modal.vipInfo.monthly' as any)+ }+ else if (statusInfo.isMonthly && !statusInfo.isAutoRenew) {+ return `${tVip('modal.vipInfo.monthly' as any)} (${tVip('modal.vipInfo.singleMonth' as any)})`+ }+ else if (statusInfo.isOnce) {+ return statusInfo.isYearly ? `${tVip('modal.vipInfo.yearly' as any)} (${tVip('modal.vipInfo.singleMonth' as any)})` : `${tVip('modal.vipInfo.monthly' as any)} (${tVip('modal.vipInfo.singleMonth' as any)})`+ }+ else if (userInfo.vipInfo.status === 'trialing') {+ return `${tVip('modal.vipInfo.monthly' as any)} (${tVip('modal.vipInfo.trial' as any)})`}- return tVip('modal.vipInfo.monthly' as any);+ else if (userInfo.vipInfo.status === 'active_nonrenewing') {+ return tVip('modal.vipInfo.cancelled' as any)+ }+ return tVip('modal.vipInfo.monthly' as any)})()}</div><div>-- <div className={styles.membershipExpire}>- {- tVip('membershipExpires' as any)- }- </div>- <div className={styles.membershipStatus}>- {userInfo?.vipInfo?.expireTime ? new Date(userInfo.vipInfo.expireTime).toLocaleString('zh-CN', {- year: 'numeric',- month: '2-digit',- day: '2-digit',- hour: '2-digit',- minute: '2-digit'- }) : '2025-09-29 15:04'}- </div>+ <div className={styles.membershipExpire}>+ {+ tVip('membershipExpires' as any)+ }+ </div>+ <div className={styles.membershipStatus}>+ {userInfo?.vipInfo?.expireTime+ ? new Date(userInfo.vipInfo.expireTime).toLocaleString('zh-CN', {+ year: 'numeric',+ month: '2-digit',+ day: '2-digit',+ hour: '2-digit',+ minute: '2-digit',+ })+ : '2025-09-29 15:04'}+ </div></div></div></div></div>{/* 根据 autoContinue 显示不同的内容 */}- <div className={styles.autoRenewal}>-- {- subscriptions.length ?(- <div className={styles.subscriptionCards}>- {subscriptions.map((subscription) => (- <div key={subscription.id} className={styles.subscriptionCard}>- <div className={styles.subscriptionHeader}>- <div className={styles.subscriptionTitle}>- {subscription.plan === SubscriptionPlan.MONTH- ? tVip('modal.vipInfo.monthly2' as any)- : subscription.plan === SubscriptionPlan.CLOUD_SPACE_MONTH- ? '云空间月度'- : tVip('basicMembership' as any)}- </div>- </div>- <div className={styles.subscriptionDetails}>- <div className={styles.subscriptionDetailItem}>- <span className={styles.detailLabel}>{tProfile('subscriptionMode')}:</span>- <span className={styles.detailValue}>- {subscription.plan === SubscriptionPlan.MONTH- ? tVip('modal.vipInfo.monthly2' as any)- : subscription.plan === SubscriptionPlan.CLOUD_SPACE_MONTH- ? '云空间月度'- : subscription.plan}- </span>- </div>- <div className={styles.subscriptionDetailItem}>- <span className={styles.detailLabel}>{tProfile('createTime')}:</span>- <span className={styles.detailValue}>- {new Date(subscription.createdAt).toLocaleString('zh-CN', {- year: 'numeric',- month: '2-digit',- day: '2-digit',- hour: '2-digit',- minute: '2-digit'- })}- </span>- </div>- {subscription.canceledAt && (- <div className={styles.subscriptionDetailItem}>- <span className={styles.detailLabel}>{tProfile('cancelTime' as any)}:</span>- <span className={styles.detailValue}>- {new Date(subscription.canceledAt).toLocaleString('zh-CN', {- year: 'numeric',- month: '2-digit',- day: '2-digit',- hour: '2-digit',- minute: '2-digit'- })}- </span>- </div>- )}- {subscription.trialEndAt && (- <div className={styles.subscriptionDetailItem}>- <span className={styles.detailLabel}>{tProfile('trialEndTime' as any)}:</span>- <span className={styles.detailValue}>- {new Date(subscription.trialEndAt).toLocaleString('zh-CN', {- year: 'numeric',- month: '2-digit',- day: '2-digit',- hour: '2-digit',- minute: '2-digit'- })}- </span>- </div>- )}- <div className={styles.subscriptionDetailItem}>- <span className={styles.detailLabel}>{tProfile('subscriptionId')}:</span>- <span className={styles.detailValue}>- {subscription.id}- <Button- type="text"- size="small"- className={styles.copyBtn}- onClick={() => {- navigator.clipboard.writeText(subscription.id);- message.success(tProfile('copySuccess'));- }}- >- 📋- </Button>- </span>- </div>- <div className={styles.subscriptionDetailItem}>- <span className={styles.detailLabel}>{tProfile('status')}:</span>- <span className={styles.detailValue}>- {subscription.status === SubscriptionStatus.ACTIVE ? (- <Tag color="green" style={{marginRight: 0,marginLeft: 6}}>- {subscription.cancelAtPeriodEnd ? tProfile('willCancelAtPeriodEnd' as any) : tProfile('subscriptionSuccess')}- </Tag>- ) : subscription.status === SubscriptionStatus.CANCELED ? (- <Tag color="red" style={{marginRight: 0,marginLeft: 6}}>{tProfile('subscriptionCancelled')}</Tag>- ) : subscription.status === SubscriptionStatus.PAST_DUE ? (- <Tag color="orange" style={{marginRight: 0,marginLeft: 6}}>{tProfile('subscriptionPastDue' as any)}</Tag>- ) : (- <Tag color="default" style={{marginRight: 0,marginLeft: 6}}>{subscription.status}</Tag>- )}- </span>- </div>- <div className={styles.subscriptionDetailItem}>- <span className={styles.detailLabel}>{tProfile('actions')}:</span>- <span className={styles.detailValue}>- {(subscription.status === SubscriptionStatus.ACTIVE && !subscription.cancelAtPeriodEnd || subscription.status === SubscriptionStatus.TRIALING && !subscription.cancelAtPeriodEnd) && (- <Button- size="small"- danger- style={{fontSize: 12}}- onClick={() => handleUnsubscribe(subscription)}- >- {tProfile('cancelSubscription')}- </Button>- )}+ <div className={styles.autoRenewal}>- {- subscription.status === SubscriptionStatus.CANCELED && subscription.cancelAtPeriodEnd &&(- <Button- size="small"- type="primary"- style={{fontSize: 12}}- onClick={() => handleResumeSubscription(subscription)}- >- {tProfile('resumeSubscription' as any)}- </Button>+ {+ subscriptions.length+ ? (+ <div className={styles.subscriptionCards}>+ {subscriptions.map(subscription => (+ <div key={subscription.id} className={styles.subscriptionCard}>+ <div className={styles.subscriptionHeader}>+ <div className={styles.subscriptionTitle}>+ {subscription.plan === SubscriptionPlan.MONTH+ ? tVip('modal.vipInfo.monthly2' as any)+ : subscription.plan === SubscriptionPlan.CLOUD_SPACE_MONTH+ ? '云空间月度'+ : tVip('basicMembership' as any)}+ </div>+ </div>+ <div className={styles.subscriptionDetails}>+ <div className={styles.subscriptionDetailItem}>+ <span className={styles.detailLabel}>+ {tProfile('subscriptionMode')}+ :+ </span>+ <span className={styles.detailValue}>+ {subscription.plan === SubscriptionPlan.MONTH+ ? tVip('modal.vipInfo.monthly2' as any)+ : subscription.plan === SubscriptionPlan.CLOUD_SPACE_MONTH+ ? '云空间月度'+ : subscription.plan}+ </span>+ </div>+ <div className={styles.subscriptionDetailItem}>+ <span className={styles.detailLabel}>+ {tProfile('createTime')}+ :+ </span>+ <span className={styles.detailValue}>+ {new Date(subscription.createdAt).toLocaleString('zh-CN', {+ year: 'numeric',+ month: '2-digit',+ day: '2-digit',+ hour: '2-digit',+ minute: '2-digit',+ })}+ </span>+ </div>+ {subscription.canceledAt && (+ <div className={styles.subscriptionDetailItem}>+ <span className={styles.detailLabel}>+ {tProfile('cancelTime' as any)}+ :+ </span>+ <span className={styles.detailValue}>+ {new Date(subscription.canceledAt).toLocaleString('zh-CN', {+ year: 'numeric',+ month: '2-digit',+ day: '2-digit',+ hour: '2-digit',+ minute: '2-digit',+ })}+ </span>+ </div>+ )}+ {subscription.trialEndAt && (+ <div className={styles.subscriptionDetailItem}>+ <span className={styles.detailLabel}>+ {tProfile('trialEndTime' as any)}+ :+ </span>+ <span className={styles.detailValue}>+ {new Date(subscription.trialEndAt).toLocaleString('zh-CN', {+ year: 'numeric',+ month: '2-digit',+ day: '2-digit',+ hour: '2-digit',+ minute: '2-digit',+ })}+ </span>+ </div>+ )}+ <div className={styles.subscriptionDetailItem}>+ <span className={styles.detailLabel}>+ {tProfile('subscriptionId')}+ :+ </span>+ <span className={styles.detailValue}>+ {subscription.id}+ <Button+ type="text"+ size="small"+ className={styles.copyBtn}+ onClick={() => {+ navigator.clipboard.writeText(subscription.id)+ message.success(tProfile('copySuccess'))+ }}+ >+ 📋+ </Button>+ </span>+ </div>+ <div className={styles.subscriptionDetailItem}>+ <span className={styles.detailLabel}>+ {tProfile('status')}+ :+ </span>+ <span className={styles.detailValue}>+ {subscription.status === SubscriptionStatus.ACTIVE+ ? (+ <Tag color="green" style={{ marginRight: 0, marginLeft: 6 }}>+ {subscription.cancelAtPeriodEnd ? tProfile('willCancelAtPeriodEnd' as any) : tProfile('subscriptionSuccess')}+ </Tag>+ )+ : subscription.status === SubscriptionStatus.CANCELED+ ? (+ <Tag color="red" style={{ marginRight: 0, marginLeft: 6 }}>{tProfile('subscriptionCancelled')}</Tag>)- }- </span>- </div>- </div>- </div>- ))}- {subscriptionsPagination.total > subscriptionsPagination.pageSize ? (- <div className={styles.paginationContainer}>- <Button- disabled={subscriptionsPagination.current === 1}- onClick={() => fetchSubscriptions({- page: subscriptionsPagination.current - 1,- size: subscriptionsPagination.pageSize- })}- >- {tVip('previousPage' as any)}- </Button>- <span className={styles.paginationInfo}>- {tVip('pageInfo' as any)- .replace('{current}', subscriptionsPagination.current.toString())- .replace('{total}', Math.ceil(subscriptionsPagination.total / subscriptionsPagination.pageSize).toString())}- </span>- <Button- disabled={subscriptionsPagination.current >= Math.ceil(subscriptionsPagination.total / subscriptionsPagination.pageSize)}- onClick={() => fetchSubscriptions({- page: subscriptionsPagination.current + 1,- size: subscriptionsPagination.pageSize- })}- >- {tVip('nextPage' as any)}- </Button>- </div>- ) : (- <div className={styles.noMoreContent}>- <p>{tVip('noMoreContent' as any)}</p>- </div>- )}- </div>- ) : (- <div className={styles.emptyState}>- <p style={{marginBottom: 20}}>{tVip('noAutoRenewalItems' as any)}</p>- <Button className={styles.viewMoreBtn}>{tVip('viewMorePlans' as any)}</Button>- </div>- )- }-+ : subscription.status === SubscriptionStatus.PAST_DUE+ ? (+ <Tag color="orange" style={{ marginRight: 0, marginLeft: 6 }}>{tProfile('subscriptionPastDue' as any)}</Tag>+ )+ : (+ <Tag color="default" style={{ marginRight: 0, marginLeft: 6 }}>{subscription.status}</Tag>+ )}+ </span>+ </div>+ <div className={styles.subscriptionDetailItem}>+ <span className={styles.detailLabel}>+ {tProfile('actions')}+ :+ </span>+ <span className={styles.detailValue}>+ {(subscription.status === SubscriptionStatus.ACTIVE && !subscription.cancelAtPeriodEnd || subscription.status === SubscriptionStatus.TRIALING && !subscription.cancelAtPeriodEnd) && (+ <Button+ size="small"+ danger+ style={{ fontSize: 12 }}+ onClick={() => handleUnsubscribe(subscription)}+ >+ {tProfile('cancelSubscription')}+ </Button>+ )}- </div>-+ {+ subscription.status === SubscriptionStatus.CANCELED && subscription.cancelAtPeriodEnd && (+ <Button+ size="small"+ type="primary"+ style={{ fontSize: 12 }}+ onClick={() => handleResumeSubscription(subscription)}+ >+ {tProfile('resumeSubscription' as any)}+ </Button>+ )+ }+ </span>+ </div>+ </div>+ </div>+ ))}+ {subscriptionsPagination.total > subscriptionsPagination.pageSize+ ? (+ <div className={styles.paginationContainer}>+ <Button+ disabled={subscriptionsPagination.current === 1}+ onClick={() => fetchSubscriptions({+ page: subscriptionsPagination.current - 1,+ size: subscriptionsPagination.pageSize,+ })}+ >+ {tVip('previousPage' as any)}+ </Button>+ <span className={styles.paginationInfo}>+ {tVip('pageInfo' as any)+ .replace('{current}', subscriptionsPagination.current.toString())+ .replace('{total}', Math.ceil(subscriptionsPagination.total / subscriptionsPagination.pageSize).toString())}+ </span>+ <Button+ disabled={subscriptionsPagination.current >= Math.ceil(subscriptionsPagination.total / subscriptionsPagination.pageSize)}+ onClick={() => fetchSubscriptions({+ page: subscriptionsPagination.current + 1,+ size: subscriptionsPagination.pageSize,+ })}+ >+ {tVip('nextPage' as any)}+ </Button>+ </div>+ )+ : (+ <div className={styles.noMoreContent}>+ <p>{tVip('noMoreContent' as any)}</p>+ </div>+ )}+ </div>+ )+ : (+ <div className={styles.emptyState}>+ <p style={{ marginBottom: 20 }}>{tVip('noAutoRenewalItems' as any)}</p>+ <Button className={styles.viewMoreBtn}>{tVip('viewMorePlans' as any)}</Button>+ </div>+ )+ }++ </div></div>--+</TabPane>-+<TabPane tab={tVip('purchaseHistory' as any)} key="orders"><div className={styles.purchaseHistory}>{ordersLoading ? (@@ -513,7 +557,7 @@ const SubscriptionManagementModal = memo(({ open, onClose }: SubscriptionManagem</div>) : orders.length > 0 ? (<div className={styles.orderCards}>- {orders.map((order) => (+ {orders.map(order => (<div key={order._id} className={styles.orderCard}><div className={styles.orderHeader}>{/* <div className={styles.orderTitle}>@@ -524,54 +568,74 @@ const SubscriptionManagementModal = memo(({ open, onClose }: SubscriptionManagem</div><div className={styles.orderDetails}><div className={styles.orderDetailItem}>- <span className={styles.detailLabel}>{tProfile('subscriptionMode')}:</span>+ <span className={styles.detailLabel}>+ {tProfile('subscriptionMode')}+ :+ </span><span className={styles.detailValue}>{getSubscriptionModeText(order.mode)}</span></div><div className={styles.orderDetailItem}>- <span className={styles.detailLabel}>{tProfile('amount')}:</span>+ <span className={styles.detailLabel}>+ {tProfile('amount')}+ :+ </span><span className={styles.detailValue}>- { (order.amount / 100).toFixed(2) } - { order.currency }- </span>-+ { (order.amount / 100).toFixed(2) }+ {' '}+ + { order.currency }+ </span>+</div><div className={styles.orderDetailItem}>- <span className={styles.detailLabel}>{tProfile('quantity' as any)}:</span>+ <span className={styles.detailLabel}>+ {tProfile('quantity' as any)}+ :+ </span><span className={styles.detailValue}>- {order.quantity || 1}+ {order.quantity || 1}</span></div><div className={styles.orderDetailItem}>- <span className={styles.detailLabel}>{tProfile('status')}:</span>+ <span className={styles.detailLabel}>+ {tProfile('status')}+ :+ </span><span className={styles.detailValue}>{getOrderStatusTag(order.status)}</span></div><div className={styles.orderDetailItem}>- <span className={styles.detailLabel}>{tProfile('createTime')}:</span>+ <span className={styles.detailLabel}>+ {tProfile('createTime')}+ :+ </span><span className={styles.detailValue}>{new Date(order.created * 1000).toLocaleString('zh-CN', {year: 'numeric',month: '2-digit',day: '2-digit',hour: '2-digit',- minute: '2-digit'+ minute: '2-digit',})}</span></div><div className={styles.orderDetailItem}>- <span className={styles.detailLabel}>{tProfile('orderId')}:</span>+ <span className={styles.detailLabel}>+ {tProfile('orderId')}+ :+ </span><span className={styles.detailValue}>{order.id}- <Button- type="text"- size="small"+ <Button+ type="text"+ size="small"className={styles.copyBtn}onClick={() => {- navigator.clipboard.writeText(order.id);- message.success(tProfile('copySuccess'));+ navigator.clipboard.writeText(order.id)+ message.success(tProfile('copySuccess'))}}>📋@@ -579,7 +643,10 @@ const SubscriptionManagementModal = memo(({ open, onClose }: SubscriptionManagem</span></div><div className={styles.orderDetailItem}>- <span className={styles.detailLabel}>{tProfile('paymentMethod' as any)}:</span>+ <span className={styles.detailLabel}>+ {tProfile('paymentMethod' as any)}+ :+ </span><span className={styles.detailValue}>{(order as any).payment_method || tVip('alipayPayment' as any)}</span>@@ -587,37 +654,39 @@ const SubscriptionManagementModal = memo(({ open, onClose }: SubscriptionManagem</div></div>))}- {ordersPagination.total > ordersPagination.pageSize ? (- <div className={styles.paginationContainer}>- <Button- disabled={ordersPagination.current === 1}- onClick={() => fetchOrders({- page: ordersPagination.current - 1,- size: ordersPagination.pageSize- })}- >- {tVip('previousPage' as any)}- </Button>- <span className={styles.paginationInfo}>- {tVip('pageInfo' as any)- .replace('{current}', ordersPagination.current.toString())- .replace('{total}', Math.ceil(ordersPagination.total / ordersPagination.pageSize).toString())}- </span>- <Button- disabled={ordersPagination.current >= Math.ceil(ordersPagination.total / ordersPagination.pageSize)}- onClick={() => fetchOrders({- page: ordersPagination.current + 1,- size: ordersPagination.pageSize- })}- >- {tVip('nextPage' as any)}- </Button>- </div>- ) : (- <div className={styles.noMoreContent}>- <p>{tVip('noMoreContent' as any)}</p>- </div>- )}+ {ordersPagination.total > ordersPagination.pageSize+ ? (+ <div className={styles.paginationContainer}>+ <Button+ disabled={ordersPagination.current === 1}+ onClick={() => fetchOrders({+ page: ordersPagination.current - 1,+ size: ordersPagination.pageSize,+ })}+ >+ {tVip('previousPage' as any)}+ </Button>+ <span className={styles.paginationInfo}>+ {tVip('pageInfo' as any)+ .replace('{current}', ordersPagination.current.toString())+ .replace('{total}', Math.ceil(ordersPagination.total / ordersPagination.pageSize).toString())}+ </span>+ <Button+ disabled={ordersPagination.current >= Math.ceil(ordersPagination.total / ordersPagination.pageSize)}+ onClick={() => fetchOrders({+ page: ordersPagination.current + 1,+ size: ordersPagination.pageSize,+ })}+ >+ {tVip('nextPage' as any)}+ </Button>+ </div>+ )+ : (+ <div className={styles.noMoreContent}>+ <p>{tVip('noMoreContent' as any)}</p>+ </div>+ )}</div>) : (<div className={styles.emptyState}>@@ -639,7 +708,7 @@ const SubscriptionManagementModal = memo(({ open, onClose }: SubscriptionManagemfooter={[<Button key="close" onClick={() => setOrderDetailVisible(false)}>{tProfile('close')}- </Button>+ </Button>,]}width={600}loading={orderDetailLoading}@@ -653,7 +722,8 @@ const SubscriptionManagementModal = memo(({ open, onClose }: SubscriptionManagem</Descriptions.Item><Descriptions.Item label={tProfile('subscriptionMode')}>{currentOrderDetail.mode}</Descriptions.Item><Descriptions.Item label={tProfile('amount')}>- ¥{(currentOrderDetail.amount / 100).toFixed(2)}+ ¥+ {(currentOrderDetail.amount / 100).toFixed(2)}</Descriptions.Item><Descriptions.Item label={tProfile('status')}>{getOrderStatusTag(currentOrderDetail.status)}@@ -668,7 +738,7 @@ const SubscriptionManagementModal = memo(({ open, onClose }: SubscriptionManagem)}</Modal></>- );-});+ )+})-export default SubscriptionManagementModal;+export default SubscriptionManagementModaldiff --git a/project/web/src/components/modals/VipContentModal.tsx b/project/web/src/components/modals/VipContentModal.tsxindex cae6ce4c..74368de3 100644--- a/project/web/src/components/modals/VipContentModal.tsx+++ b/project/web/src/components/modals/VipContentModal.tsx@@ -1,72 +1,73 @@-"use client";--import { memo, useMemo, useState, useEffect } from "react";-import { Modal, Button, Tag, message } from "antd";-import { useRouter } from "next/navigation";-import { createPaymentOrderApi, PaymentType } from "@/api/vip";-import { useTransClient } from "@/app/i18n/client";-import styles from "./outsideCloseModal.module.css";-import vipStyles from "./vipContentModal.module.css";-import PointsDetailModal from "@/components/modals/PointsDetailModal";-import { useUserStore } from "@/store/user";-import PointsRechargeModal from "@/components/modals/PointsRechargeModal";-import SubscriptionManagementModal from "@/components/modals/SubscriptionManagementModal";--import logo from '@/assets/images/logo.png';-import Image from "next/image";+'use client'++import { Button, message, Modal, Tag } from 'antd'+import Image from 'next/image'+import { useRouter } from 'next/navigation'+import { memo, useEffect, useMemo, useState } from 'react'+import { createPaymentOrderApi, PaymentType } from '@/api/vip'+import { useTransClient } from '@/app/i18n/client'+import logo from '@/assets/images/logo.png'+import PointsDetailModal from '@/components/modals/PointsDetailModal'+import PointsRechargeModal from '@/components/modals/PointsRechargeModal'+import SubscriptionManagementModal from '@/components/modals/SubscriptionManagementModal'+import { useUserStore } from '@/store/user'++import styles from './outsideCloseModal.module.css'+import vipStyles from './vipContentModal.module.css'interface VipContentModalProps {- open: boolean;- onClose: () => void;+ open: boolean+ onClose: () => void}const VipContentModal = memo(({ open, onClose }: VipContentModalProps) => {- const [pointsModalVisible, setPointsModalVisible] = useState(false);- const [subscriptionModalVisible, setSubscriptionModalVisible] = useState(false);- const userStore = useUserStore();- const router = useRouter();- const { t } = useTransClient('vip');- const modalWidth = useMemo(() => "900px" as const, []);- const [rechargeVisible, setRechargeVisible] = useState(false);- const [activeTab, setActiveTab] = useState<'year' | 'month' | 'once'>('month');- const [loading, setLoading] = useState(false);- const [canUseTrial, setCanUseTrial] = useState(false);-+ const [pointsModalVisible, setPointsModalVisible] = useState(false)+ const [subscriptionModalVisible, setSubscriptionModalVisible] = useState(false)+ const userStore = useUserStore()+ const router = useRouter()+ const { t } = useTransClient('vip')+ const modalWidth = useMemo(() => '900px' as const, [])+ const [rechargeVisible, setRechargeVisible] = useState(false)+ const [activeTab, setActiveTab] = useState<'year' | 'month' | 'once'>('month')+ const [loading, setLoading] = useState(false)+ const [canUseTrial, setCanUseTrial] = useState(false)+// 辅助函数处理翻译- const translate = (key: string) => t(key as any);-+ const translate = (key: string) => t(key as any)+// 状态判断辅助函数const getVipStatusInfo = (status: string) => {switch (status) {case 'none':- return { isVip: false, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false };+ return { isVip: false, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false }case 'trialing':- return { isVip: true, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false };+ return { isVip: true, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false }case 'monthly_once':- return { isVip: true, isMonthly: true, isYearly: false, isAutoRenew: false, isOnce: true };+ return { isVip: true, isMonthly: true, isYearly: false, isAutoRenew: false, isOnce: true }case 'yearly_once':- return { isVip: true, isMonthly: false, isYearly: true, isAutoRenew: false, isOnce: true };+ return { isVip: true, isMonthly: false, isYearly: true, isAutoRenew: false, isOnce: true }case 'active_monthly':- return { isVip: true, isMonthly: true, isYearly: false, isAutoRenew: true, isOnce: false };+ return { isVip: true, isMonthly: true, isYearly: false, isAutoRenew: true, isOnce: false }case 'active_yearly':- return { isVip: true, isMonthly: false, isYearly: true, isAutoRenew: true, isOnce: false };+ return { isVip: true, isMonthly: false, isYearly: true, isAutoRenew: true, isOnce: false }case 'active_nonrenewing':- return { isVip: true, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false };+ return { isVip: true, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false }case 'expired':- return { isVip: false, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false };+ return { isVip: false, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false }default:- return { isVip: false, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false };+ return { isVip: false, isMonthly: false, isYearly: false, isAutoRenew: false, isOnce: false }}- };-+ }+// 判断用户是否为有效会员const isVip = useMemo(() => {- const vipInfo = userStore.userInfo?.vipInfo;- if (!vipInfo) return false;-- const statusInfo = getVipStatusInfo(vipInfo.status);- return statusInfo.isVip && vipInfo.expireTime && new Date(vipInfo.expireTime) > new Date();- }, [userStore.userInfo]);+ const vipInfo = userStore.userInfo?.vipInfo+ if (!vipInfo)+ return false++ const statusInfo = getVipStatusInfo(vipInfo.status)+ return statusInfo.isVip && vipInfo.expireTime && new Date(vipInfo.expireTime) > new Date()+ }, [userStore.userInfo])// 判断用户是否已经是相同类型的会员且未过期const isCurrentPlan = useMemo(() => {@@ -75,109 +76,113 @@ const VipContentModal = memo(({ open, onClose }: VipContentModalProps) => {month: false,year: false,once: false,- trial: false- };+ trial: false,+ }}-- const vipInfo = userStore.userInfo.vipInfo;- const statusInfo = getVipStatusInfo(vipInfo.status);++ const vipInfo = userStore.userInfo.vipInfo+ const statusInfo = getVipStatusInfo(vipInfo.status)return {month: statusInfo.isMonthly && statusInfo.isAutoRenew, // 连续包月- year: statusInfo.isYearly && statusInfo.isAutoRenew, // 连续包年+ year: statusInfo.isYearly && statusInfo.isAutoRenew, // 连续包年once: statusInfo.isOnce, // 一次性购买- trial: vipInfo.status === 'trialing' // 试用中- };- }, [userStore.userInfo, isVip]);-+ trial: vipInfo.status === 'trialing', // 试用中+ }+ }, [userStore.userInfo, isVip])+const handleTabClick = (tab: 'year' | 'month' | 'once') => {- setActiveTab(tab);- };+ setActiveTab(tab)+ }// 检查用户是否可以享受免费试用useEffect(() => {if (userStore.userInfo) {// 如果用户没有vipInfo,说明从未开过会员,可以享受免费试用- const hasVipInfo = userStore.userInfo.vipInfo;- setCanUseTrial(!hasVipInfo);+ const hasVipInfo = userStore.userInfo.vipInfo+ setCanUseTrial(!hasVipInfo)}- }, [userStore.userInfo]);+ }, [userStore.userInfo])// 开通会员逻辑const handleActivate = async (planType: 'year' | 'month' | 'once') => {- console.log('canUseTrial', canUseTrial);+ console.log('canUseTrial', canUseTrial)try {- setLoading(true);-+ setLoading(true)+// 检查用户是否已登录if (!userStore.userInfo?.id) {- message.error(t('pleaseLoginFirst'));- router.push('/login');- return;+ message.error(t('pleaseLoginFirst'))+ router.push('/login')+ return}// 检查用户是否已经是相同类型的会员且未过期if (isCurrentPlan[planType]) {- message.warning(translate('currentPlan'));- setLoading(false);- return;+ message.warning(translate('currentPlan'))+ setLoading(false)+ return}// 根据选择的计划映射到支付类型- let paymentType;- let paymentMethod;- let flagTrialPeriodDays = 0; // 默认不给免费试用+ let paymentType+ let paymentMethod+ let flagTrialPeriodDays = 0 // 默认不给免费试用switch (planType) {case 'once':- paymentType = PaymentType.ONCE_MONTH;- paymentMethod = 'payment';- break;+ paymentType = PaymentType.ONCE_MONTH+ paymentMethod = 'payment'+ breakcase 'month':- paymentType = PaymentType.MONTH;- paymentMethod = 'subscription';+ paymentType = PaymentType.MONTH+ paymentMethod = 'subscription'// 如果是订阅模式且用户从未开过会员,给免费试用- flagTrialPeriodDays = canUseTrial ? 1 : 0;- break;+ flagTrialPeriodDays = canUseTrial ? 1 : 0+ breakcase 'year':- paymentType = PaymentType.YEAR;- paymentMethod = 'subscription';+ paymentType = PaymentType.YEAR+ paymentMethod = 'subscription'// 如果是订阅模式且用户从未开过会员,给免费试用- flagTrialPeriodDays = canUseTrial ? 1 : 0;- break;+ flagTrialPeriodDays = canUseTrial ? 1 : 0+ breakdefault:- paymentType = PaymentType.MONTH;- paymentMethod = 'subscription';- flagTrialPeriodDays = canUseTrial ? 1 : 0;+ paymentType = PaymentType.MONTH+ paymentMethod = 'subscription'+ flagTrialPeriodDays = canUseTrial ? 1 : 0}-+// 创建支付订单const response: any = await createPaymentOrderApi({- returnTo: userStore.lang === 'zh-CN' ? "https://aitoearn.ai/zh-CN/profile" : "https://aitoearn.ai/en/profile",+ returnTo: userStore.lang === 'zh-CN' ? 'https://aitoearn.ai/zh-CN/profile' : 'https://aitoearn.ai/en/profile',mode: paymentMethod,payment: paymentType,metadata: {- userId: userStore.userInfo.id- }- });-+ userId: userStore.userInfo.id,+ },+ })+if (response?.code === 0) {- message.success(t('paymentOrderCreated'));+ message.success(t('paymentOrderCreated'))// 直接跳转到支付页面if (response.data?.url) {- window.open(response.data.url, '_blank');- } else {- message.error(t('paymentLinkNotFound'));+ window.open(response.data.url, '_blank')+ }+ else {+ message.error(t('paymentLinkNotFound'))}- } else {- message.error(response?.message || response?.msg || t('createPaymentOrderFailed'));}- } catch (error) {- console.error('Create payment order failed:', error);- message.error(t('createPaymentOrderError'));- } finally {- setLoading(false);+ else {+ message.error(response?.message || response?.msg || t('createPaymentOrderFailed'))+ }+ }+ catch (error) {+ console.error('Create payment order failed:', error)+ message.error(t('createPaymentOrderError'))}- };+ finally {+ setLoading(false)+ }+ }return (<Modaltitle={null}@@ -193,17 +198,24 @@ const VipContentModal = memo(({ open, onClose }: VipContentModalProps) => {{/* 非会员顶部区域 */}{!isVip && (- <div className={vipStyles.header}- style={{ background: 'transparent' }}>+ <div+ className={vipStyles.header}+ style={{ background: 'transparent' }}+ ><div className={vipStyles.titleBlock}><h2 className={vipStyles.title}>- {translate('modal.title')} <span className={vipStyles.highlight}>{translate('modal.highlight')}</span>+ {translate('modal.title')}+ {' '}+ <span className={vipStyles.highlight}>{translate('modal.highlight')}</span></h2><div className={vipStyles.links}><span>{translate('modal.choosePlan')}</span>- <span className={vipStyles.linkButton}+ <span+ className={vipStyles.linkButton}onClick={() => setRechargeVisible(true)}- >{translate('modal.buyPoints')}</span>+ >+ {translate('modal.buyPoints')}+ </span></div></div><div className={vipStyles.headerRight}>@@ -212,7 +224,6 @@ const VipContentModal = memo(({ open, onClose }: VipContentModalProps) => {</div>)}-{/* 会员信息区域 */}{isVip && userStore.userInfo?.vipInfo && (@@ -220,61 +231,72 @@ const VipContentModal = memo(({ open, onClose }: VipContentModalProps) => {<div className={vipStyles.vipInfoRow}><div className={vipStyles.userInfo}><div className={vipStyles.avatar}>- {userStore.userInfo.avatar ? (- <img src={userStore.userInfo.avatar} alt="用户头像" />- ) : (- <Image src={logo} alt="用户头像" style={{ padding: '3px', backgroundColor: '#e9d5ff' }} />- )}+ {userStore.userInfo.avatar+ ? (+ <img src={userStore.userInfo.avatar} alt="用户头像" />+ )+ : (+ <Image src={logo} alt="用户头像" style={{ padding: '3px', backgroundColor: '#e9d5ff' }} />+ )}</div><div className={vipStyles.userDetails}><div className={vipStyles.userName}>{userStore.userInfo.name}</div>{/* <div className={vipStyles.userEmail}>{userStore.userInfo.mail}</div> */}</div></div>- <div className={vipStyles.vipActions}>- <Button className={vipStyles.detailBtn} onClick={() => setPointsModalVisible(true)}>{translate('modal.pointsDetail')}</Button>- <Button className={vipStyles.subscriptionBtn} onClick={() => setSubscriptionModalVisible(true)}>{translate('modal.vipInfo.subscription')}</Button>- </div>+ <div className={vipStyles.vipActions}>+ <Button className={vipStyles.detailBtn} onClick={() => setPointsModalVisible(true)}>{translate('modal.pointsDetail')}</Button>+ <Button className={vipStyles.subscriptionBtn} onClick={() => setSubscriptionModalVisible(true)}>{translate('modal.vipInfo.subscription')}</Button>+ </div></div>-+<div className={vipStyles.vipPlanInfo}><div className={vipStyles.planDetails}><div className={vipStyles.planType}>- {translate('modal.vipInfo.planType')}:+ {translate('modal.vipInfo.planType')}+ :<span className={vipStyles.planValue}>{(() => {- const statusInfo: any = getVipStatusInfo(userStore.userInfo.vipInfo.status);+ const statusInfo: any = getVipStatusInfo(userStore.userInfo.vipInfo.status)if (statusInfo.isYearly && statusInfo.isAutoRenew) {- return translate('modal.vipInfo.yearly');- } else if (statusInfo.isYearly && !statusInfo.isAutoRenew) {- return translate('modal.vipInfo.yearly2');- } else if (statusInfo.isMonthly && statusInfo.isAutoRenew) {- return translate('modal.vipInfo.monthly');- } else if (statusInfo.isMonthly && !statusInfo.isAutoRenew) {- return translate('modal.vipInfo.monthly2');- } else if (statusInfo.isOnce) {- return statusInfo.isYearly ? translate('modal.vipInfo.yearly2') : translate('modal.vipInfo.monthly2');- } else if (userStore.userInfo.vipInfo.status === 'trialing') {- return ` ${translate('modal.vipInfo.trial' as any)}`;- } else if (userStore.userInfo.vipInfo.status === 'active_nonrenewing') {- return translate('modal.vipInfo.cancelled' as any);+ return translate('modal.vipInfo.yearly')+ }+ else if (statusInfo.isYearly && !statusInfo.isAutoRenew) {+ return translate('modal.vipInfo.yearly2')+ }+ else if (statusInfo.isMonthly && statusInfo.isAutoRenew) {+ return translate('modal.vipInfo.monthly')+ }+ else if (statusInfo.isMonthly && !statusInfo.isAutoRenew) {+ return translate('modal.vipInfo.monthly2')+ }+ else if (statusInfo.isOnce) {+ return statusInfo.isYearly ? translate('modal.vipInfo.yearly2') : translate('modal.vipInfo.monthly2')+ }+ else if (userStore.userInfo.vipInfo.status === 'trialing') {+ return ` ${translate('modal.vipInfo.trial' as any)}`+ }+ else if (userStore.userInfo.vipInfo.status === 'active_nonrenewing') {+ return translate('modal.vipInfo.cancelled' as any)}- return translate('modal.vipInfo.monthly');+ return translate('modal.vipInfo.monthly')})()}</span></div><div className={vipStyles.expireTime}>{(() => {- const statusInfo = getVipStatusInfo(userStore.userInfo.vipInfo.status);- return statusInfo.isAutoRenew ? translate('modal.vipInfo.xufeiTime') : translate('modal.vipInfo.expireTime');- })()}:+ const statusInfo = getVipStatusInfo(userStore.userInfo.vipInfo.status)+ return statusInfo.isAutoRenew ? translate('modal.vipInfo.xufeiTime') : translate('modal.vipInfo.expireTime')+ })()}+ :<span className={vipStyles.expireValue}>{new Date(userStore.userInfo.vipInfo.expireTime).toLocaleDateString()}</span></div><div className={vipStyles.expireTime}>- {translate('modal.vipInfo.remainingPoints')}:+ {translate('modal.vipInfo.remainingPoints')}+ :<div><span onClick={() => setPointsModalVisible(true)} className={vipStyles.expireValue} style={{ color: '#727E84' }}>@@ -288,14 +310,20 @@ const VipContentModal = memo(({ open, onClose }: VipContentModalProps) => {</div></div><div className={vipStyles.pointsInfo}>-+</div></div>-+</div>)}-{isVip && userStore.userInfo?.vipInfo && (<h5 style={{ margin: 0, fontSize: 16, fontWeight: 700, color: '#0f172a', textAlign: 'center', marginTop: 16, marginBottom: 16 }}> {translate('subscriptionPlans')} </h5>)}+ {isVip && userStore.userInfo?.vipInfo && (+ <h5 style={{ margin: 0, fontSize: 16, fontWeight: 700, color: '#0f172a', textAlign: 'center', marginTop: 16, marginBottom: 16 }}>+ {' '}+ {translate('subscriptionPlans')}+ {' '}+ </h5>+ )}{/* 选项卡 */}<div className={vipStyles.switchRow}>@@ -303,10 +331,10 @@ const VipContentModal = memo(({ open, onClose }: VipContentModalProps) => {{translate('modal.tabs.yearly')} <Tag style={{ marginLeft: 6, border: '1px solid rgba(184,221,255,.08)' }}>{translate('modal.savings.yearly')}</Tag></div> */}{/* <div onClick={() => handleTabClick('month')} className={`${vipStyles.switchBtn} ${activeTab === 'month' ? vipStyles.active : ''}`}>- {translate('modal.tabs.monthly')}+ {translate('modal.tabs.monthly')}<Tag style={{ marginLeft: 6, border: '1px solid rgba(184,221,255,.08)' }}>{translate('modal.savings.monthly')}</Tag></div> */}- {+ {// (() => {// const vipInfo = userStore.userInfo?.vipInfo;// if (!vipInfo) return true;@@ -317,24 +345,26 @@ const VipContentModal = memo(({ open, onClose }: VipContentModalProps) => {// {translate('modal.tabs.once')}// </div>// )- }+ }</div>{/* 价格区域 */}<div className={vipStyles.grid}>-{activeTab === 'year' && (<><div className={vipStyles.freeCard}><div className={vipStyles.freeTitle}>{translate('modal.free.title')}</div>- <div className={vipStyles.freePrice}><span>{translate('modal.free.price')}</span><span className={vipStyles.unit}>{translate('modal.free.period')}</span></div>+ <div className={vipStyles.freePrice}>+ <span>{translate('modal.free.price')}</span>+ <span className={vipStyles.unit}>{translate('modal.free.period')}</span>+ </div><Button disabled className={vipStyles.freeBtn}>{isVip ? translate('modal.free.freePlan') : translate('modal.free.currentPlan')}</Button><ul className={vipStyles.featureList}>- <li>{translate('modal.free.points')}</li>+ <li>{translate('modal.free.points')}</li><li>{translate('modal.free.features.dailyPoints')}</li><li>{translate('modal.free.features.maxPoints')}</li><li>{translate('modal.free.features.videos')}</li>@@ -342,21 +372,33 @@ const VipContentModal = memo(({ open, onClose }: VipContentModalProps) => {</ul></div>- <div className={`${vipStyles.planCard} ${vipStyles.premium}`} >- <div className={vipStyles.planHead}>{translate('modal.plans.yearly.title')} <Tag color="#5b7cff">{translate('modal.plans.yearly.bestValue')}</Tag></div>- <div className={vipStyles.planPriceLine}><span className={vipStyles.currency}>$</span><span className={vipStyles.bigNum}>{translate('modal.plans.yearly.price')}</span><span className={vipStyles.unit}>{translate('modal.plans.yearly.period')}</span></div>+ <div className={`${vipStyles.planCard} ${vipStyles.premium}`}>+ <div className={vipStyles.planHead}>+ {translate('modal.plans.yearly.title')}+ {' '}+ <Tag color="#5b7cff">{translate('modal.plans.yearly.bestValue')}</Tag>+ </div>+ <div className={vipStyles.planPriceLine}>+ <span className={vipStyles.currency}>$</span>+ <span className={vipStyles.bigNum}>{translate('modal.plans.yearly.price')}</span>+ <span className={vipStyles.unit}>{translate('modal.plans.yearly.period')}</span>+ </div><div className={vipStyles.planDesc}>{translate('modal.plans.yearly.button')}- </div>- <Button- className={vipStyles.primaryBtn}- onClick={() => handleActivate('year')}- loading={loading}- disabled={isCurrentPlan.year || isCurrentPlan.month}- >- {isCurrentPlan.year ? translate('currentPlan') : translate('modal.plans.goumai')}- </Button>- <div className={vipStyles.benefitBox}><span className={vipStyles.dot} /> {translate('modal.plans.yearly.features.dailyPoints')}</div>+ </div>+ <Button+ className={vipStyles.primaryBtn}+ onClick={() => handleActivate('year')}+ loading={loading}+ disabled={isCurrentPlan.year || isCurrentPlan.month}+ >+ {isCurrentPlan.year ? translate('currentPlan') : translate('modal.plans.goumai')}+ </Button>+ <div className={vipStyles.benefitBox}>+ <span className={vipStyles.dot} />+ {' '}+ {translate('modal.plans.yearly.features.dailyPoints')}+ </div><div className={vipStyles.subDesc}>{translate('modal.plans.yearly.points')}</div><ul className={vipStyles.featureList}><li>{translate('modal.plans.yearly.description')}</li>@@ -370,18 +412,22 @@ const VipContentModal = memo(({ open, onClose }: VipContentModalProps) => {</>)}-{activeTab === 'month' && (<>{/* 左侧免费卡片 */}<div className={vipStyles.freeCard}><div className={vipStyles.freeTitle}>{translate('modal.free.title')}</div>- <div className={vipStyles.freePrice}> $ <span style={{ fontSize: 44,fontWeight: 800, color: '#333' }}>{translate('modal.free.price')}</span><span className={vipStyles.unit}>{translate('modal.free.period')}</span></div>+ <div className={vipStyles.freePrice}>+ {' '}+ $+ <span style={{ fontSize: 44, fontWeight: 800, color: '#333' }}>{translate('modal.free.price')}</span>+ <span className={vipStyles.unit}>{translate('modal.free.period')}</span>+ </div><Button disabled className={vipStyles.freeBtn}>{isVip ? translate('modal.free.freePlan') : translate('modal.free.currentPlan')}</Button><ul className={vipStyles.featureList}>- {/* <li>{translate('modal.free.points')}</li> */}+ {/* <li>{translate('modal.free.points')}</li> */}<li>{translate('modal.free.features.dailyPoints')}</li><li>{translate('modal.free.features.maxPoints')}</li><li>{translate('modal.free.features.videos')}</li>@@ -389,34 +435,45 @@ const VipContentModal = memo(({ open, onClose }: VipContentModalProps) => {</ul></div>- {/* 月度会员 */}- <div className={`${vipStyles.planCard} ${vipStyles.premium}`} >- <div className={vipStyles.planHead}>{translate('modal.plans.monthly.title')} </div>- <div className={vipStyles.planPriceLine}><span className={vipStyles.currency}>$</span><span className={vipStyles.bigNum}>{translate('modal.plans.monthly.price')}</span><span className={vipStyles.unit}>{translate('modal.plans.monthly.period')}</span></div>- {/* <div className={vipStyles.planDesc}>+ {/* 月度会员 */}+ <div className={`${vipStyles.planCard} ${vipStyles.premium}`}>+ <div className={vipStyles.planHead}>+ {translate('modal.plans.monthly.title')}+ {' '}+ </div>+ <div className={vipStyles.planPriceLine}>+ <span className={vipStyles.currency}>$</span>+ <span className={vipStyles.bigNum}>{translate('modal.plans.monthly.price')}</span>+ <span className={vipStyles.unit}>{translate('modal.plans.monthly.period')}</span>+ </div>+ {/* <div className={vipStyles.planDesc}>{translate('modal.plans.monthly.button')}</div> */}- <Button- className={vipStyles.primaryBtn}- onClick={() => handleActivate('month')}- loading={loading}- disabled={isCurrentPlan.month || isCurrentPlan.trial}- >- {isCurrentPlan.month ? translate('currentPlan') :- (- userStore.userInfo?.vipInfo ? translate('modal.plans.goumai') : 'Start 3-day free trial'- )- }- </Button>- <div className={vipStyles.benefitBox}><span className={vipStyles.dot} /> {translate('modal.plans.yearly.features.dailyPoints')}</div>+ <Button+ className={vipStyles.primaryBtn}+ onClick={() => handleActivate('month')}+ loading={loading}+ disabled={isCurrentPlan.month || isCurrentPlan.trial}+ >+ {isCurrentPlan.month+ ? translate('currentPlan')+ : (+ userStore.userInfo?.vipInfo ? translate('modal.plans.goumai') : 'Start 3-day free trial'+ )}+ </Button>+ <div className={vipStyles.benefitBox}>+ <span className={vipStyles.dot} />+ {' '}+ {translate('modal.plans.yearly.features.dailyPoints')}+ </div>{/* <div className={vipStyles.subDesc}>{translate('modal.plans.monthly.points')}</div> */}<ul className={vipStyles.featureList}>{/* <li>{translate('modal.plans.monthly.description')}</li> */}<li>{translate('modal.plans.yearly.features.contentReview')}</li><li>{translate('modal.plans.yearly.features.dailyPoints')}</li><li>{translate('modal.plans.yearly.features.multiModel')}</li>- <li>{translate('modal.plans.yearly.features.textToVideo')}</li>- {/*<li>{translate('modal.plans.yearly.features.aiGeneration')}</li>+ <li>{translate('modal.plans.yearly.features.textToVideo')}</li>+ {/* <li>{translate('modal.plans.yearly.features.aiGeneration')}</li><li>{translate('modal.plans.yearly.features.noWatermark')}</li> */}</ul></div>@@ -428,12 +485,15 @@ const VipContentModal = memo(({ open, onClose }: VipContentModalProps) => {{/* 左侧免费卡片 */}<div className={vipStyles.freeCard}><div className={vipStyles.freeTitle}>{translate('modal.free.title')}</div>- <div className={vipStyles.freePrice}><span>{translate('modal.free.price')}</span><span className={vipStyles.unit}>{translate('modal.free.period')}</span></div>+ <div className={vipStyles.freePrice}>+ <span>{translate('modal.free.price')}</span>+ <span className={vipStyles.unit}>{translate('modal.free.period')}</span>+ </div><Button disabled className={vipStyles.freeBtn}>{isVip ? translate('modal.free.freePlan') : translate('modal.free.currentPlan')}</Button><ul className={vipStyles.featureList}>- <li>{translate('modal.free.points')}</li>+ <li>{translate('modal.free.points')}</li><li>{translate('modal.free.features.dailyPoints')}</li><li>{translate('modal.free.features.maxPoints')}</li><li>{translate('modal.free.features.videos')}</li>@@ -441,18 +501,29 @@ const VipContentModal = memo(({ open, onClose }: VipContentModalProps) => {</ul></div>- {/* 一次性月度会员 */}- <div className={`${vipStyles.planCard} ${vipStyles.premium}`} >- <div className={vipStyles.planHead}>{translate('modal.plans.once.title')} </div>- <div className={vipStyles.planPriceLine}><span className={vipStyles.currency}>$</span><span className={vipStyles.bigNum}>{translate('modal.plans.once.price')}</span><span className={vipStyles.unit}>{translate('modal.plans.once.period')}</span></div>- <Button- className={vipStyles.primaryBtn}- onClick={() => handleActivate('once')}- loading={loading}- >- {translate('modal.plans.goumai')}- </Button>- <div className={vipStyles.benefitBox}><span className={vipStyles.dot} /> {translate('modal.plans.yearly.features.dailyPoints')}</div>+ {/* 一次性月度会员 */}+ <div className={`${vipStyles.planCard} ${vipStyles.premium}`}>+ <div className={vipStyles.planHead}>+ {translate('modal.plans.once.title')}+ {' '}+ </div>+ <div className={vipStyles.planPriceLine}>+ <span className={vipStyles.currency}>$</span>+ <span className={vipStyles.bigNum}>{translate('modal.plans.once.price')}</span>+ <span className={vipStyles.unit}>{translate('modal.plans.once.period')}</span>+ </div>+ <Button+ className={vipStyles.primaryBtn}+ onClick={() => handleActivate('once')}+ loading={loading}+ >+ {translate('modal.plans.goumai')}+ </Button>+ <div className={vipStyles.benefitBox}>+ <span className={vipStyles.dot} />+ {' '}+ {translate('modal.plans.yearly.features.dailyPoints')}+ </div><div className={vipStyles.subDesc}>{translate('modal.plans.once.points')}</div><ul className={vipStyles.featureList}><li>{translate('modal.plans.once.description')}</li>@@ -477,9 +548,7 @@ const VipContentModal = memo(({ open, onClose }: VipContentModalProps) => {{/* 订阅管理弹窗 */}<SubscriptionManagementModal open={subscriptionModalVisible} onClose={() => setSubscriptionModalVisible(false)} /></Modal>- );-});--export default VipContentModal;-+ )+})+export default VipContentModaldiff --git a/project/web/src/components/modals/outsideCloseModal.module.css b/project/web/src/components/modals/outsideCloseModal.module.cssindex a9455087..68a7da14 100644--- a/project/web/src/components/modals/outsideCloseModal.module.css+++ b/project/web/src/components/modals/outsideCloseModal.module.css@@ -19,5 +19,3 @@.outsideCloseModal :global(.ant-modal-content) {border-radius: 14px;}--diff --git a/project/web/src/components/modals/subscriptionManagementModal.module.css b/project/web/src/components/modals/subscriptionManagementModal.module.cssindex 3c986eab..5d8e7219 100644--- a/project/web/src/components/modals/subscriptionManagementModal.module.css+++ b/project/web/src/components/modals/subscriptionManagementModal.module.css@@ -249,14 +249,14 @@}/* 表格样式优化 */-.ant-table-thead>tr>th {+.ant-table-thead > tr > th {background: #f8f9fa;font-weight: 600;color: #374151;border-bottom: 2px solid #e5e7eb;}-.ant-table-tbody>tr:hover>td {+.ant-table-tbody > tr:hover > td {background: #f8f9fa;}@@ -442,4 +442,4 @@flex-direction: column;gap: 12px;}-}\ No newline at end of file+}diff --git a/project/web/src/components/modals/vipContentModal.module.css b/project/web/src/components/modals/vipContentModal.module.cssindex 1839ee2f..d409e9d8 100644--- a/project/web/src/components/modals/vipContentModal.module.css+++ b/project/web/src/components/modals/vipContentModal.module.css@@ -77,10 +77,10 @@padding: 8px 16px;cursor: pointer;border: 1px solid #e5e7eb;- box-shadow: 0 1px 2px rgba(0,0,0,0.04);+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);}-.outsideCloseModal{+.outsideCloseModal {max-width: 1000px;}@@ -104,15 +104,40 @@border-radius: 12px;padding: 24px;border: 1px solid #eef2f7;- box-shadow: 0 1px 2px rgba(0,0,0,0.04);+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);+}+.freeTitle {+ font-weight: 700;+ margin-bottom: 12px;+ color: #111827;+}+.freePrice {+ font-size: 14px;+ margin: 12px 0;+ color: #111827;+ height: 69px;+ line-height: 69px;+}+.freePrice span {+ font-size: 18px;+}+.unit {+ margin-left: 6px;+ font-size: 14px;+ color: #6b7280;+}+.freeForever {+ color: #6b7280;+ margin-bottom: 16px;+}+.freeBtn {+ width: 100%;+ margin-bottom: 16px;+}+.freeItem {+ font-size: 12px;+ color: #6b7280;}-.freeTitle { font-weight: 700; margin-bottom: 12px; color:#111827; }-.freePrice { font-size: 14px; margin: 12px 0; color:#111827; height: 69px; line-height: 69px; }-.freePrice span { font-size: 18px; }-.unit { margin-left: 6px; font-size: 14px; color: #6b7280; }-.freeForever { color: #6b7280; margin-bottom: 16px; }-.freeBtn { width: 100%; margin-bottom: 16px; }-.freeItem { font-size: 12px; color: #6b7280; }.planCard {background: #ffffff;@@ -121,26 +146,90 @@padding: 24px;position: relative;border: 1px solid #eef2f7;- box-shadow: 0 1px 2px rgba(0,0,0,0.04);+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);}-.premium { box-shadow: 0 0 0 1px rgba(166,106,228,0.4), 0 0 30px rgba(166,106,228,0.25) inset; min-height: 530px; }--.planHead { font-weight: 700; margin-bottom: 12px; display: flex; align-items: center; gap: 8px; color:#111827; }-.planPriceLine { display: flex; align-items: baseline; gap: 4px; margin: 6px 0 10px; }-.currency { font-size: 18px; }-.bigNum { font-size: 44px; font-weight: 800; color: #111827; }-.planDesc { font-size: 12px; color: #6b7280; margin-bottom: 12px; line-height: 1.6; }-+.premium {+ box-shadow:+ 0 0 0 1px rgba(166, 106, 228, 0.4),+ 0 0 30px rgba(166, 106, 228, 0.25) inset;+ min-height: 530px;+}+.planHead {+ font-weight: 700;+ margin-bottom: 12px;+ display: flex;+ align-items: center;+ gap: 8px;+ color: #111827;+}+.planPriceLine {+ display: flex;+ align-items: baseline;+ gap: 4px;+ margin: 6px 0 10px;+}+.currency {+ font-size: 18px;+}+.bigNum {+ font-size: 44px;+ font-weight: 800;+ color: #111827;+}+.planDesc {+ font-size: 12px;+ color: #6b7280;+ margin-bottom: 12px;+ line-height: 1.6;+}-.primaryBtn { width: 100%; background: linear-gradient(92deg,#66e9ff,#b5e9fd 34.5%,#a396ff 66.5%,#a66ae4) !important; border-color: #a66ae4; color: #ffffff; font-weight: 600 !important; margin-bottom: 16px; }-.primaryBtn:hover { background: #9556d1; border-color: #9556d1; }+.primaryBtn {+ width: 100%;+ background: linear-gradient(92deg, #66e9ff, #b5e9fd 34.5%, #a396ff 66.5%, #a66ae4) !important;+ border-color: #a66ae4;+ color: #ffffff;+ font-weight: 600 !important;+ margin-bottom: 16px;+}+.primaryBtn:hover {+ background: #9556d1;+ border-color: #9556d1;+}-.benefitBox { background: #f8f4ff; border-radius: 10px; padding: 10px 12px; display: flex; align-items: center; gap: 8px; color: #7c3aed; margin-bottom: 8px; }-.dot { width: 8px; height: 8px; background: #a66ae4; border-radius: 50%; display: inline-block; }-.subDesc { font-size: 12px; color: #6b7280; margin-bottom: 12px; }-.featureList { list-style: none; padding: 0; margin: 0; padding-left: 3px; display: grid; gap: 10px; color: #374151; font-size: 13px; }+.benefitBox {+ background: #f8f4ff;+ border-radius: 10px;+ padding: 10px 12px;+ display: flex;+ align-items: center;+ gap: 8px;+ color: #7c3aed;+ margin-bottom: 8px;+}+.dot {+ width: 8px;+ height: 8px;+ background: #a66ae4;+ border-radius: 50%;+ display: inline-block;+}+.subDesc {+ font-size: 12px;+ color: #6b7280;+ margin-bottom: 12px;+}+.featureList {+ list-style: none;+ padding: 0;+ margin: 0;+ padding-left: 3px;+ display: grid;+ gap: 10px;+ color: #374151;+ font-size: 13px;+}/* 会员信息区域样式 */.vipInfoSection {@@ -246,7 +335,8 @@gap: 88px;}-.planType, .expireTime {+.planType,+.expireTime {font-size: 14px;color: #374151;display: flex;@@ -254,7 +344,8 @@gap: 8px;}-.planValue, .expireValue {+.planValue,+.expireValue {color: #111827;}@@ -297,5 +388,3 @@background: #059669;border-color: #059669;}--diff --git a/project/web/src/components/notification/NotificationPanel.module.scss b/project/web/src/components/notification/NotificationPanel.module.scssindex bb8bd437..12ed0eee 100644--- a/project/web/src/components/notification/NotificationPanel.module.scss+++ b/project/web/src/components/notification/NotificationPanel.module.scss@@ -17,8 +17,6 @@&.unread {background: linear-gradient(135deg, #f6ffed 0%, #e6f7ff 100%);position: relative;--}}@@ -155,4 +153,4 @@padding-top: 16px;border-top: 1px solid #e9ecef;text-align: center;-}\ No newline at end of file+}diff --git a/project/web/src/components/notification/NotificationPanel.tsx b/project/web/src/components/notification/NotificationPanel.tsxindex b730dec4..1276d785 100644--- a/project/web/src/components/notification/NotificationPanel.tsx+++ b/project/web/src/components/notification/NotificationPanel.tsx@@ -1,245 +1,264 @@-"use client";--import React, { useState, useEffect } from "react";-import { Badge, Button, List, Modal, message, Spin, Empty, Popconfirm, Tooltip, Tag, Steps } from "antd";-import { CheckOutlined, DeleteOutlined, EyeOutlined, ClockCircleOutlined } from "@ant-design/icons";-import { useTransClient } from "@/app/i18n/client";-import { useUserStore } from "@/store/user";-import {- getNotificationList,- getNotificationDetail,- markNotificationAsRead,- markAllNotificationsAsRead,- getUnreadCount,+'use client'++import type { NotificationItem, TaskItem } from '@/api/notification'+import type { SocialAccount } from '@/api/types/account.type'+// 平台配置(图标等)+import type { PlatType } from '@/app/config/platConfig'+import { CheckOutlined, ClockCircleOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons'+import { Badge, Button, Empty, List, message, Modal, Popconfirm, Spin, Steps, Tag, Tooltip } from 'antd'+import { useParams, useRouter } from 'next/navigation'+import React, { useEffect, useState } from 'react'+import { getAccountListApi } from '@/api/account'+import {+ acceptTask,deleteNotifications,+ getNotificationDetail,+ getNotificationList,getTaskDetail,- acceptTask,+ getUnreadCount,+ markAllNotificationsAsRead,+ markNotificationAsRead,+submitTask,- type NotificationItem,- type TaskItem-} from "@/api/notification";-import { getAccountListApi } from "@/api/account";-import { SocialAccount } from "@/api/types/account.type";-import { apiCreatePublish } from "@/api/plat/publish";-import { getOssUrl } from "@/utils/oss";-import { PubType } from "@/app/config/publishConfig";-import { getAppDownloadConfig, getTasksRequiringApp } from "@/app/config/appDownloadConfig";-import DownloadAppModal from "@/components/common/DownloadAppModal";-import styles from "./NotificationPanel.module.scss";-import { useParams, useRouter } from "next/navigation";-import { getDays, getUtcDays } from "@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils";-// 平台配置(图标等)-import { AccountPlatInfoMap, PlatType } from "@/app/config/platConfig";+} from '@/api/notification'+import { apiCreatePublish } from '@/api/plat/publish'+import { getDays, getUtcDays } from '@/app/[lng]/accounts/components/CalendarTiming/calendarTiming.utils'+import { getAppDownloadConfig, getTasksRequiringApp } from '@/app/config/appDownloadConfig'+import { AccountPlatInfoMap } from '@/app/config/platConfig'+import { PubType } from '@/app/config/publishConfig'+import { useTransClient } from '@/app/i18n/client'+import DownloadAppModal from '@/components/common/DownloadAppModal'+import { useUserStore } from '@/store/user'+import { getOssUrl } from '@/utils/oss'++import styles from './NotificationPanel.module.scss'interface NotificationPanelProps {- visible: boolean;- onClose: () => void;+ visible: boolean+ onClose: () => void}const NotificationPanel: React.FC<NotificationPanelProps> = ({ visible, onClose }) => {- const { t } = useTransClient("notification" as any);- const token = useUserStore((state) => state.token);- const router = useRouter();- const { lng } = useParams();- const [notifications, setNotifications] = useState<NotificationItem[]>([]);- const [loading, setLoading] = useState(false);- const [unreadCount, setUnreadCount] = useState(0);+ const { t } = useTransClient('notification' as any)+ const token = useUserStore(state => state.token)+ const router = useRouter()+ const { lng } = useParams()+ const [notifications, setNotifications] = useState<NotificationItem[]>([])+ const [loading, setLoading] = useState(false)+ const [unreadCount, setUnreadCount] = useState(0)const [notificationPagination, setNotificationPagination] = useState({current: 1,pageSize: 10,- total: 0- });- const [selectedNotification, setSelectedNotification] = useState<NotificationItem | null>(null);- const [selectedTask, setSelectedTask] = useState<TaskItem | null>(null);- const [detailModalVisible, setDetailModalVisible] = useState(false);- const [taskLoading, setTaskLoading] = useState(false);- const [accountList, setAccountList] = useState<SocialAccount[]>([]);-+ total: 0,+ })+ const [selectedNotification, setSelectedNotification] = useState<NotificationItem | null>(null)+ const [selectedTask, setSelectedTask] = useState<TaskItem | null>(null)+ const [detailModalVisible, setDetailModalVisible] = useState(false)+ const [taskLoading, setTaskLoading] = useState(false)+ const [accountList, setAccountList] = useState<SocialAccount[]>([])+// 下载App弹窗状态- const [downloadAppVisible, setDownloadAppVisible] = useState(false);+ const [downloadAppVisible, setDownloadAppVisible] = useState(false)const [downloadAppConfig, setDownloadAppConfig] = useState({- platform: "",- appName: "",- downloadUrl: "",- qrCodeUrl: "" as string | undefined- });+ platform: '',+ appName: '',+ downloadUrl: '',+ qrCodeUrl: '' as string | undefined,+ })// 媒体预览弹窗状态- const [mediaPreviewVisible, setMediaPreviewVisible] = useState(false);+ const [mediaPreviewVisible, setMediaPreviewVisible] = useState(false)const [previewMedia, setPreviewMedia] = useState<{- type: 'video' | 'image';- url: string;- title?: string;- } | null>(null);- const [videoRef, setVideoRef] = useState<HTMLVideoElement | null>(null);+ type: 'video' | 'image'+ url: string+ title?: string+ } | null>(null)+ const [videoRef, setVideoRef] = useState<HTMLVideoElement | null>(null)// 任务进度弹窗状态- const [taskProgressVisible, setTaskProgressVisible] = useState(false);+ const [taskProgressVisible, setTaskProgressVisible] = useState(false)const [taskProgress, setTaskProgress] = useState({currentStep: 0,steps: [{ title: t('acceptingTask' as any), status: 'processing' },{ title: t('publishingTask' as any), status: 'wait' },{ title: t('submittingTask' as any), status: 'wait' },- { title: t('taskCompleted' as any), status: 'wait' }- ]- });+ { title: t('taskCompleted' as any), status: 'wait' },+ ],+ })// 账号选择弹窗状态- const [accountSelectVisible, setAccountSelectVisible] = useState(false);- const [availableAccounts, setAvailableAccounts] = useState<SocialAccount[]>([]);- const [selectedAccount, setSelectedAccount] = useState<SocialAccount | null>(null);- const [requiredAccountTypes, setRequiredAccountTypes] = useState<string[]>([]);+ const [accountSelectVisible, setAccountSelectVisible] = useState(false)+ const [availableAccounts, setAvailableAccounts] = useState<SocialAccount[]>([])+ const [selectedAccount, setSelectedAccount] = useState<SocialAccount | null>(null)+ const [requiredAccountTypes, setRequiredAccountTypes] = useState<string[]>([])// 获取通知列表const fetchNotifications = async (page: number = 1, pageSize: number = 20) => {// 如果没有登录信息,不发送请求if (!token) {- setNotifications([]);- return;+ setNotifications([])+ return}try {- setLoading(true);- const response = await getNotificationList({ page, pageSize });+ setLoading(true)+ const response = await getNotificationList({ page, pageSize })if (response && response.data) {- setNotifications(response.data.list || []);+ setNotifications(response.data.list || [])setNotificationPagination(prev => ({...prev,current: page,- total: response.data.total || 0- }));+ total: response.data.total || 0,+ }))}- } catch (error) {- message.error(t('getNotificationListFailed'));- } finally {- setLoading(false);}- };+ catch (error) {+ message.error(t('getNotificationListFailed'))+ }+ finally {+ setLoading(false)+ }+ }// 获取未读数量const fetchUnreadCount = async () => {// 如果没有登录信息,不发送请求if (!token) {- setUnreadCount(0);- return;+ setUnreadCount(0)+ return}try {- const response = await getUnreadCount();+ const response = await getUnreadCount()if (response && response.data) {- setUnreadCount(response.data.count || 0);+ setUnreadCount(response.data.count || 0)}- } catch (error) {- console.error("获取未读数量失败:", error);}- };+ catch (error) {+ console.error('获取未读数量失败:', error)+ }+ }// 获取账号列表const fetchAccountList = async () => {if (!token) {- setAccountList([]);- return;+ setAccountList([])+ return}try {- const response = await getAccountListApi();+ const response = await getAccountListApi()if (response && response.data) {- setAccountList(response.data || []);+ setAccountList(response.data || [])}- } catch (error) {- console.error("获取账号列表失败:", error);}- };+ catch (error) {+ console.error('获取账号列表失败:', error)+ }+ }// 标记单个通知为已读const handleMarkAsRead = async (id: string) => {try {- await markNotificationAsRead([id]);- message.success(t('markSuccess'));- fetchNotifications();- fetchUnreadCount();- } catch (error) {- message.error(t('markFailed'));+ await markNotificationAsRead([id])+ message.success(t('markSuccess'))+ fetchNotifications()+ fetchUnreadCount()+ }+ catch (error) {+ message.error(t('markFailed'))}- };+ }// 全部标记为已读const handleMarkAllAsRead = async () => {try {- await markAllNotificationsAsRead();- message.success(t('markAllSuccess'));- fetchNotifications();- fetchUnreadCount();- } catch (error) {- message.error(t('markFailed'));+ await markAllNotificationsAsRead()+ message.success(t('markAllSuccess'))+ fetchNotifications()+ fetchUnreadCount()+ }+ catch (error) {+ message.error(t('markFailed'))+ }+ }++ // 获取任务详情+ const fetchTaskDetail = async (opportunityId: string) => {+ try {+ setTaskLoading(true)+ const response: any = await getTaskDetail(opportunityId)+ if (response && response.data && response.code === 0) {+ setSelectedTask(response.data)+ }+ else {+ console.error(t('getTaskDetailFailed'))+ }+ }+ catch (error) {+ console.error(t('getTaskDetailFailed'), error)+ }+ finally {+ setTaskLoading(false)}- };+ }// 查看通知详情const handleViewDetail = async (notification: NotificationItem) => {try {// 调用API获取通知详情- const response:any = await getNotificationDetail(notification.id);- if (response && response.data && response.code == 0) {- setSelectedNotification(response.data);- setDetailModalVisible(true);-+ const response: any = await getNotificationDetail(notification.id)+ if (response && response.data && response.code === 0) {+ setSelectedNotification(response.data)+ setDetailModalVisible(true)+// 如果是任务提醒类型且有relatedId,获取任务详情if (notification.type === 'task_reminder' && notification.relatedId) {- await fetchTaskDetail(notification.relatedId);+ await fetchTaskDetail(notification.relatedId)}-+// 如果是未读状态,标记为已读if (notification.status === 'unread') {- handleMarkAsRead(notification.id);+ handleMarkAsRead(notification.id)}- } else {- message.error(t('getNotificationDetailFailed'));}- } catch (error) {- message.error(t('getNotificationDetailFailed'));- console.error("获取通知详情失败:", error);- }- };-- // 获取任务详情- const fetchTaskDetail = async (opportunityId: string) => {- try {- setTaskLoading(true);- const response: any = await getTaskDetail(opportunityId);- if (response && response.data && response.code === 0) {- setSelectedTask(response.data);- } else {- console.error(t('getTaskDetailFailed'));+ else {+ message.error(t('getNotificationDetailFailed'))}- } catch (error) {- console.error(t('getTaskDetailFailed'), error);- } finally {- setTaskLoading(false);}- };+ catch (error) {+ message.error(t('getNotificationDetailFailed'))+ console.error('获取通知详情失败:', error)+ }+ }++ // 根据accountId获取账号信息+ const getAccountById = (accountId: string): SocialAccount | null => {+ return accountList.find(account => account.id === accountId) || null+ }// 接受任务const handleAcceptTask = async (account?: SocialAccount) => {- if (!selectedTask) return;+ if (!selectedTask)+ return// 显示进度弹窗- setTaskProgressVisible(true);+ setTaskProgressVisible(true)setTaskProgress({currentStep: 0,steps: [{ title: '正在接受任务...', status: 'processing' },{ title: '正在发布任务...', status: 'wait' },{ title: '正在提交任务...', status: 'wait' },- { title: '任务完成', status: 'wait' }- ]- });-+ { title: '任务完成', status: 'wait' },+ ],+ })+try {// 第一步:接受任务- const response: any = await acceptTask(selectedTask.id, selectedTask.opportunityId, account?.id);+ const response: any = await acceptTask(selectedTask.id, selectedTask.opportunityId, account?.id)if (response && response.code === 0) {// 更新进度:第一步完成,开始第二步setTaskProgress(prev => ({@@ -248,13 +267,13 @@ const NotificationPanel: React.FC<NotificationPanelProps> = ({ visible, onClosesteps: [{ title: t('acceptingTask' as any), status: 'finish' },{ title: t('publishingTask' as any), status: 'processing' },- { title: t('taskCompleted' as any), status: 'wait' }- ]- }));+ { title: t('taskCompleted' as any), status: 'wait' },+ ],+ }))// 第二步:发布任务// 优先使用传入的账号,其次使用任务指定的账号- const publishAccount = account || getAccountById(selectedTask.accountId);+ const publishAccount = account || getAccountById(selectedTask.accountId)if (publishAccount) {// 处理素材链接,确保使用完整链接const processedMaterials = selectedTask.materials?.map((material: any) => ({@@ -263,9 +282,9 @@ const NotificationPanel: React.FC<NotificationPanelProps> = ({ visible, onClosemediaList: material.mediaList?.map((media: any) => ({...media,url: getOssUrl(media.url),- coverUrl: media.coverUrl ? getOssUrl(media.coverUrl) : undefined- }))- }));+ coverUrl: media.coverUrl ? getOssUrl(media.coverUrl) : undefined,+ })),+ }))const publishData = {flowId: publishAccount.uid, // 使用账号的uid作为flowId@@ -275,21 +294,22 @@ const NotificationPanel: React.FC<NotificationPanelProps> = ({ visible, onClosedesc: selectedTask.description,type: selectedTask.type as any, // 转换为PubType// 处理素材数据- videoUrl: processedMaterials?.[0]?.mediaList?.[0]?.type === 'video' ?- getOssUrl(processedMaterials[0].mediaList[0].url) : undefined,+ videoUrl: processedMaterials?.[0]?.mediaList?.[0]?.type === 'video'+ ? getOssUrl(processedMaterials[0].mediaList[0].url)+ : undefined,coverUrl: processedMaterials?.[0]?.coverUrl,- imgUrlList: processedMaterials?.flatMap((material: any) =>+ imgUrlList: processedMaterials?.flatMap((material: any) =>material.mediaList?.filter((media: any) => media.type !== 'video')- .map((media: any) => getOssUrl(media.url)) || []+ .map((media: any) => getOssUrl(media.url)) || [],),option: {},topics: [],- publishTime: getUtcDays(getDays().add(6, "minute")).format(),+ publishTime: getUtcDays(getDays().add(6, 'minute')).format(),userTaskId: response.data.id,- taskMaterialId: selectedTask.materialIds[0]- };+ taskMaterialId: selectedTask.materialIds[0],+ }- const publishResponse: any = await apiCreatePublish(publishData);+ const publishResponse: any = await apiCreatePublish(publishData)if (publishResponse && publishResponse.code === 0) {// 更新进度:第二步完成,开始第三步setTaskProgress(prev => ({@@ -299,15 +319,15 @@ const NotificationPanel: React.FC<NotificationPanelProps> = ({ visible, onClose{ title: t('acceptingTask' as any), status: 'finish' },{ title: t('publishingTask' as any), status: 'finish' },{ title: t('submittingTask' as any), status: 'processing' },- { title: t('taskCompleted' as any), status: 'wait' }- ]- }));+ { title: t('taskCompleted' as any), status: 'wait' },+ ],+ }))// 第三步:提交任务// 从发布响应中获取userTaskId,如果没有则使用任务ID- const userTaskId = response.data.id;- const submitResponse: any = await submitTask(userTaskId, selectedTask.materialIds[0]);-+ const userTaskId = response.data.id+ const submitResponse: any = await submitTask(userTaskId, selectedTask.materialIds[0])+if (submitResponse && submitResponse.code === 0) {// 更新进度:第三步完成,开始第四步setTaskProgress(prev => ({@@ -317,254 +337,261 @@ const NotificationPanel: React.FC<NotificationPanelProps> = ({ visible, onClose{ title: t('acceptingTask' as any), status: 'finish' },{ title: t('publishingTask' as any), status: 'finish' },{ title: t('submittingTask' as any), status: 'finish' },- { title: t('taskCompleted' as any), status: 'finish' }- ]- }));+ { title: t('taskCompleted' as any), status: 'finish' },+ ],+ }))// 延迟1秒后关闭进度窗口并跳转setTimeout(() => {- setTaskProgressVisible(false);- setDetailModalVisible(false);- setSelectedTask(null);- router.push(`/${lng}/tasks`);- }, 1000);- } else {- throw new Error('提交任务失败');+ setTaskProgressVisible(false)+ setDetailModalVisible(false)+ setSelectedTask(null)+ router.push(`/${lng}/tasks`)+ }, 1000)}- } else {- throw new Error('发布任务失败');+ else {+ throw new Error('提交任务失败')+ }+ }+ else {+ throw new Error('发布任务失败')}- } else {- throw new Error('找不到发布账号信息');}- } else {- throw new Error('接受任务失败');+ else {+ throw new Error('找不到发布账号信息')+ }}- } catch (error) {- console.error("任务处理失败:", error);- message.error(t('taskProcessFailed'));- setTaskProgressVisible(false);+ else {+ throw new Error('接受任务失败')+ }+ }+ catch (error) {+ console.error('任务处理失败:', error)+ message.error(t('taskProcessFailed'))+ setTaskProgressVisible(false)}- };+ }++ // 获取符合条件的账号列表+ const getAvailableAccounts = (accountTypes: string[]): SocialAccount[] => {+ if (!accountTypes || accountTypes.length === 0) {+ return accountList // 如果没有类型限制,返回所有账号+ }+ return accountList.filter(account => accountTypes.includes(account.type))+ }// 检查任务类型并显示相应的操作提示const handleTaskAction = (task: TaskItem) => {// 首先检查任务支持的所有平台是否都需要App操作- const taskPlatforms = task.accountTypes || [];- const appRequiredPlatforms = getTasksRequiringApp(taskPlatforms);-+ const taskPlatforms = task.accountTypes || []+ const appRequiredPlatforms = getTasksRequiringApp(taskPlatforms)+// 如果所有平台都需要App操作,直接显示下载App提示if (appRequiredPlatforms.length > 0 && appRequiredPlatforms.length === taskPlatforms.length) {- const firstPlatform = appRequiredPlatforms[0];- const config = getAppDownloadConfig(firstPlatform);-+ const firstPlatform = appRequiredPlatforms[0]+ const config = getAppDownloadConfig(firstPlatform)+if (config) {setDownloadAppConfig({platform: config.platform,appName: config.appName,downloadUrl: config.downloadUrl,- qrCodeUrl: config.qrCodeUrl- });- setDownloadAppVisible(true);- return;+ qrCodeUrl: config.qrCodeUrl,+ })+ setDownloadAppVisible(true)+ return}}// 如果任务指定了账号,使用指定账号的逻辑if (task.accountId) {- const publishAccount = getAccountById(task.accountId);+ const publishAccount = getAccountById(task.accountId)if (publishAccount) {// 检查发布账号的平台是否需要App操作- const appRequiredPlatforms = getTasksRequiringApp([publishAccount.type]);-+ const appRequiredPlatforms = getTasksRequiringApp([publishAccount.type])+if (appRequiredPlatforms.length > 0) {// 有需要App操作的平台,显示第一个平台的下载提示- const firstPlatform = appRequiredPlatforms[0];- const config = getAppDownloadConfig(firstPlatform);-+ const firstPlatform = appRequiredPlatforms[0]+ const config = getAppDownloadConfig(firstPlatform)+if (config) {setDownloadAppConfig({platform: config.platform,appName: config.appName,downloadUrl: config.downloadUrl,- qrCodeUrl: config.qrCodeUrl- });- setDownloadAppVisible(true);- return;+ qrCodeUrl: config.qrCodeUrl,+ })+ setDownloadAppVisible(true)+ return}}-+// 直接使用指定账号接受任务- handleAcceptTask(publishAccount);- return;+ handleAcceptTask(publishAccount)+ return}}// 如果没有指定账号,需要用户选择账号- const availableAccounts = getAvailableAccounts(task.accountTypes || []);-+ const availableAccounts = getAvailableAccounts(task.accountTypes || [])+if (availableAccounts.length === 0) {// 没有符合条件的账号,跳转到账户界面并弹出授权界面- setRequiredAccountTypes(task.accountTypes || []);- setDetailModalVisible(false); // 关闭任务详情弹窗- message.info(t('accountSelect.redirectingToAccounts' as any));-+ setRequiredAccountTypes(task.accountTypes || [])+ setDetailModalVisible(false) // 关闭任务详情弹窗+ message.info(t('accountSelect.redirectingToAccounts' as any))+// 构建跳转URL,包含需要的平台类型参数- const accountTypes = task.accountTypes || [];- const platformParam = accountTypes.length > 0 ? accountTypes[0] : undefined;- const accountsUrl = platformParam+ const accountTypes = task.accountTypes || []+ const platformParam = accountTypes.length > 0 ? accountTypes[0] : undefined+ const accountsUrl = platformParam? `/${lng}/accounts?platform=${platformParam}`- : `/${lng}/accounts`;-- router.push(accountsUrl); // 跳转到账户界面并自动打开添加账号弹窗- return;+ : `/${lng}/accounts`++ router.push(accountsUrl) // 跳转到账户界面并自动打开添加账号弹窗+ return}if (availableAccounts.length === 1) {// 只有一个符合条件的账号,直接使用- const account = availableAccounts[0];-+ const account = availableAccounts[0]+// 检查是否需要App操作- const appRequiredPlatforms = getTasksRequiringApp([account.type]);+ const appRequiredPlatforms = getTasksRequiringApp([account.type])if (appRequiredPlatforms.length > 0) {- const firstPlatform = appRequiredPlatforms[0];- const config = getAppDownloadConfig(firstPlatform);-+ const firstPlatform = appRequiredPlatforms[0]+ const config = getAppDownloadConfig(firstPlatform)+if (config) {setDownloadAppConfig({platform: config.platform,appName: config.appName,downloadUrl: config.downloadUrl,- qrCodeUrl: config.qrCodeUrl- });- setDownloadAppVisible(true);- return;+ qrCodeUrl: config.qrCodeUrl,+ })+ setDownloadAppVisible(true)+ return}}-+// 直接使用这个账号接受任务- handleAcceptTask(account);- return;+ handleAcceptTask(account)+ return}-+// 多个符合条件的账号,显示选择弹窗- setAvailableAccounts(availableAccounts);- setAccountSelectVisible(true);- };+ setAvailableAccounts(availableAccounts)+ setAccountSelectVisible(true)+ }// 格式化时间const formatTime = (timeString: string) => {- const date = new Date(timeString);- const now = new Date();- const diff = now.getTime() - date.getTime();- const minutes = Math.floor(diff / (1000 * 60));- const hours = Math.floor(diff / (1000 * 60 * 60));- const days = Math.floor(diff / (1000 * 60 * 60 * 24));-- if (minutes < 1) return t('time.justNow' as any);- if (minutes < 60) return t('time.minutesAgo' as any, { minutes });- if (hours < 24) return t('time.hoursAgo' as any, { hours });- if (days < 7) return t('time.daysAgo' as any, { days });- return date.toLocaleDateString();- };+ const date = new Date(timeString)+ const now = new Date()+ const diff = now.getTime() - date.getTime()+ const minutes = Math.floor(diff / (1000 * 60))+ const hours = Math.floor(diff / (1000 * 60 * 60))+ const days = Math.floor(diff / (1000 * 60 * 60 * 24))++ if (minutes < 1)+ return t('time.justNow' as any)+ if (minutes < 60)+ return t('time.minutesAgo' as any, { minutes })+ if (hours < 24)+ return t('time.hoursAgo' as any, { hours })+ if (days < 7)+ return t('time.daysAgo' as any, { days })+ return date.toLocaleDateString()+ }// 获取通知类型文本const getNotificationTypeText = (type: string) => {const typeMap: Record<string, string> = {system: t('notificationTypes.system' as any),- user: t('notificationTypes.user' as any),+ user: t('notificationTypes.user' as any),material: t('notificationTypes.material' as any),task_reminder: t('notificationTypes.task_reminder' as any),- other: t('notificationTypes.other' as any)- };- return typeMap[type] || type;- };+ other: t('notificationTypes.other' as any),+ }+ return typeMap[type] || type+ }// 获取通知类型颜色const getNotificationTypeColor = (type: string) => {const colorMap: Record<string, string> = {- system: "blue",- user: "green",- material: "orange",- task_reminder: "red",- other: "default"- };- return colorMap[type] || "default";- };+ system: 'blue',+ user: 'green',+ material: 'orange',+ task_reminder: 'red',+ other: 'default',+ }+ return colorMap[type] || 'default'+ }// 删除通知const handleDeleteNotification = async (id: string) => {try {- await deleteNotifications([id]);- message.success(t('deleteSuccess'));- fetchNotifications();- fetchUnreadCount();- } catch (error) {- message.error(t('deleteFailed'));+ await deleteNotifications([id])+ message.success(t('deleteSuccess'))+ fetchNotifications()+ fetchUnreadCount()}- };+ catch (error) {+ message.error(t('deleteFailed'))+ }+ }// 获取平台显示名称const getPlatformName = (type: string) => {- const { lng } = useParams();-+ const { lng } = useParams()+if (lng === 'en') {- return type;+ return type}-+// 使用国际化显示名称const platformNames: Record<string, string> = {- 'tiktok': t('platforms.tiktok' as any),- 'youtube': t('platforms.youtube' as any),- 'twitter': t('platforms.twitter' as any),- 'bilibili': t('platforms.bilibili' as any),- 'KWAI': t('platforms.KWAI' as any),- 'douyin': t('platforms.douyin' as any),- 'xhs': t('platforms.xhs' as any),- 'wxSph': t('platforms.wxSph' as any),- 'wxGzh': t('platforms.wxGzh' as any),- 'facebook': t('platforms.facebook' as any),- 'instagram': t('platforms.instagram' as any),- 'threads': t('platforms.threads' as any),- 'pinterest': t('platforms.pinterest' as any),- };- return platformNames[type] || type;- };+ tiktok: t('platforms.tiktok' as any),+ youtube: t('platforms.youtube' as any),+ twitter: t('platforms.twitter' as any),+ bilibili: t('platforms.bilibili' as any),+ KWAI: t('platforms.KWAI' as any),+ douyin: t('platforms.douyin' as any),+ xhs: t('platforms.xhs' as any),+ wxSph: t('platforms.wxSph' as any),+ wxGzh: t('platforms.wxGzh' as any),+ facebook: t('platforms.facebook' as any),+ instagram: t('platforms.instagram' as any),+ threads: t('platforms.threads' as any),+ pinterest: t('platforms.pinterest' as any),+ }+ return platformNames[type] || type+ }// 获取任务类型显示名称const getTaskTypeName = (type: string) => {const taskTypeNames: Record<string, string> = {- 'video': t('taskTypes.video' as any),- 'article': t('taskTypes.article' as any),- 'article2': t('taskTypes.article2' as any),- };- return taskTypeNames[type] || type;- };+ video: t('taskTypes.video' as any),+ article: t('taskTypes.article' as any),+ article2: t('taskTypes.article2' as any),+ }+ return taskTypeNames[type] || type+ }/*** 从平台配置中获取平台图标* 兼容字符串路径与含有src字段的对象*/const getPlatformIcon = (type: string) => {- const info = AccountPlatInfoMap.get(type as PlatType);- const icon: any = info?.icon;- if (!icon) return null;- if (typeof icon === 'string') return icon;- return icon?.src || icon?.default || null;- };-- // 根据accountId获取账号信息- const getAccountById = (accountId: string): SocialAccount | null => {- return accountList.find(account => account.id === accountId) || null;- };-- // 获取符合条件的账号列表- const getAvailableAccounts = (accountTypes: string[]): SocialAccount[] => {- if (!accountTypes || accountTypes.length === 0) {- return accountList; // 如果没有类型限制,返回所有账号- }- return accountList.filter(account => accountTypes.includes(account.type));- };+ const info = AccountPlatInfoMap.get(type as PlatType)+ const icon: any = info?.icon+ if (!icon)+ return null+ if (typeof icon === 'string')+ return icon+ return icon?.src || icon?.default || null+ }// 处理媒体点击const handleMediaClick = (media: any, materialTitle?: string, materialCoverUrl?: string) => {@@ -572,140 +599,141 @@ const NotificationPanel: React.FC<NotificationPanelProps> = ({ visible, onClosesetPreviewMedia({type: 'video',url: getOssUrl(media.url),- title: materialTitle- });- } else {+ title: materialTitle,+ })+ }+ else {setPreviewMedia({type: 'image',url: getOssUrl(media.url),- title: materialTitle- });+ title: materialTitle,+ })}- setMediaPreviewVisible(true);- };+ setMediaPreviewVisible(true)+ }// 处理视频封面点击const handleVideoCoverClick = (media: any, materialTitle?: string) => {setPreviewMedia({type: 'video',url: getOssUrl(media.url),- title: materialTitle- });- setMediaPreviewVisible(true);- };+ title: materialTitle,+ })+ setMediaPreviewVisible(true)+ }// 关闭媒体预览const handleCloseMediaPreview = () => {// 停止视频播放if (videoRef) {- videoRef.pause();- videoRef.currentTime = 0;+ videoRef.pause()+ videoRef.currentTime = 0}- setMediaPreviewVisible(false);- setPreviewMedia(null);- setVideoRef(null);- };+ setMediaPreviewVisible(false)+ setPreviewMedia(null)+ setVideoRef(null)+ }// 处理通知分页变化const handleNotificationPageChange = (page: number, pageSize?: number) => {- fetchNotifications(page, pageSize || notificationPagination.pageSize);- };+ fetchNotifications(page, pageSize || notificationPagination.pageSize)+ }// 处理账号选择const handleAccountSelect = (account: SocialAccount) => {- setSelectedAccount(account);- setAccountSelectVisible(false);-+ setSelectedAccount(account)+ setAccountSelectVisible(false)+// 检查是否需要App操作- const appRequiredPlatforms = getTasksRequiringApp([account.type]);+ const appRequiredPlatforms = getTasksRequiringApp([account.type])if (appRequiredPlatforms.length > 0) {- const firstPlatform = appRequiredPlatforms[0];- const config = getAppDownloadConfig(firstPlatform);-+ const firstPlatform = appRequiredPlatforms[0]+ const config = getAppDownloadConfig(firstPlatform)+if (config) {setDownloadAppConfig({platform: config.platform,appName: config.appName,downloadUrl: config.downloadUrl,- qrCodeUrl: config.qrCodeUrl- });- setDownloadAppVisible(true);- return;+ qrCodeUrl: config.qrCodeUrl,+ })+ setDownloadAppVisible(true)+ return}}-+// 使用选择的账号接受任务- handleAcceptTask(account);- };+ handleAcceptTask(account)+ }// 检查是否有新添加的符合条件账号const checkForNewAccounts = () => {if (requiredAccountTypes.length > 0 && selectedTask) {- const newAvailableAccounts = getAvailableAccounts(requiredAccountTypes);-+ const newAvailableAccounts = getAvailableAccounts(requiredAccountTypes)+if (newAvailableAccounts.length > 0) {// 有新账号了,清除需求状态- setRequiredAccountTypes([]);-+ setRequiredAccountTypes([])+if (newAvailableAccounts.length === 1) {// 只有一个新账号,直接使用- const account = newAvailableAccounts[0];-+ const account = newAvailableAccounts[0]+// 检查是否需要App操作- const appRequiredPlatforms = getTasksRequiringApp([account.type]);+ const appRequiredPlatforms = getTasksRequiringApp([account.type])if (appRequiredPlatforms.length > 0) {- const firstPlatform = appRequiredPlatforms[0];- const config = getAppDownloadConfig(firstPlatform);-+ const firstPlatform = appRequiredPlatforms[0]+ const config = getAppDownloadConfig(firstPlatform)+if (config) {setDownloadAppConfig({platform: config.platform,appName: config.appName,downloadUrl: config.downloadUrl,- qrCodeUrl: config.qrCodeUrl- });- setDownloadAppVisible(true);- return;+ qrCodeUrl: config.qrCodeUrl,+ })+ setDownloadAppVisible(true)+ return}}-+// 直接使用这个账号接受任务- handleAcceptTask(account);- } else {+ handleAcceptTask(account)+ }+ else {// 多个新账号,显示选择弹窗- setAvailableAccounts(newAvailableAccounts);- setAccountSelectVisible(true);+ setAvailableAccounts(newAvailableAccounts)+ setAccountSelectVisible(true)}}}- };+ }useEffect(() => {if (visible) {- fetchNotifications();- fetchUnreadCount();- fetchAccountList();+ fetchNotifications()+ fetchUnreadCount()+ fetchAccountList()}- }, [visible, token]);+ }, [visible, token])// 监听账号列表变化,检查是否有新添加的符合条件账号useEffect(() => {if (accountList.length > 0) {- checkForNewAccounts();+ checkForNewAccounts()}- }, [accountList, requiredAccountTypes, selectedTask]);-+ }, [accountList, requiredAccountTypes, selectedTask])return (<><Modal- title={+ title={(<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><Badge count={unreadCount} size="small"><span style={{ fontSize: '16px', fontWeight: '600' }}>{t('title')}</span></Badge></div>- }+ )}open={visible}onCancel={onClose}footer={[@@ -714,432 +742,488 @@ const NotificationPanel: React.FC<NotificationPanelProps> = ({ visible, onClose</Button>,<Button key="close" onClick={onClose}>{t('cancel')}- </Button>+ </Button>,]}width={700}destroyOnHiddenstyles={{header: {borderBottom: '1px solid #f0f0f0',- paddingBottom: '16px'+ paddingBottom: '16px',},body: {- padding: '6px'- }+ padding: '6px',+ },}}><Spin spinning={loading}>- {notifications.length > 0 ? (- <List- dataSource={notifications}- pagination={{- current: notificationPagination.current,- pageSize: notificationPagination.pageSize,- total: notificationPagination.total,- onChange: handleNotificationPageChange,- showSizeChanger: true,- showQuickJumper: true,- showTotal: (total, range) => t('pageInfo' as any, { start: range[0], end: range[1], total }),- pageSizeOptions: ['10', '20', '50', '100']- }}- renderItem={(item) => (- <List.Item- className={`${styles.notificationItem} ${item.status === 'unread' ? styles.unread : ""}`}- actions={[- item.status === 'unread' && (- <Button- key="mark"- type="text"- size="small"- icon={<CheckOutlined />}- onClick={(e) => {- e.stopPropagation();- handleMarkAsRead(item.id);- }}- >- {t('markAsRead')}- </Button>- ),- <Popconfirm- key="delete"- title={t('confirmDelete')}- onConfirm={() => handleDeleteNotification(item.id)}- okText={t('confirm')}- cancelText={t('cancel')}+ {notifications.length > 0+ ? (+ <List+ dataSource={notifications}+ pagination={{+ current: notificationPagination.current,+ pageSize: notificationPagination.pageSize,+ total: notificationPagination.total,+ onChange: handleNotificationPageChange,+ showSizeChanger: true,+ showQuickJumper: true,+ showTotal: (total, range) => t('pageInfo' as any, { start: range[0], end: range[1], total }),+ pageSizeOptions: ['10', '20', '50', '100'],+ }}+ renderItem={item => (+ <List.Item+ className={`${styles.notificationItem} ${item.status === 'unread' ? styles.unread : ''}`}+ actions={[+ item.status === 'unread' && (+ <Button+ key="mark"+ type="text"+ size="small"+ icon={<CheckOutlined />}+ onClick={(e) => {+ e.stopPropagation()+ handleMarkAsRead(item.id)+ }}+ >+ {t('markAsRead')}+ </Button>+ ),+ <Popconfirm+ key="delete"+ title={t('confirmDelete')}+ onConfirm={() => handleDeleteNotification(item.id)}+ okText={t('confirm')}+ cancelText={t('cancel')}+ >+ <Button+ type="text"+ size="small"+ danger+ icon={<DeleteOutlined />}+ onClick={e => e.stopPropagation()}+ >+ {t('delete')}+ </Button>+ </Popconfirm>,+ ]}>- <Button- type="text"- size="small"- danger- icon={<DeleteOutlined />}- onClick={(e) => e.stopPropagation()}+ <div+ className={styles.notificationClickableArea}+ onClick={() => handleViewDetail(item)}+ style={{+ cursor: 'pointer',+ width: '100%',+ padding: '8px 0',+ }}>- {t('delete')}- </Button>- </Popconfirm>- ]}- >- <div- className={styles.notificationClickableArea}- onClick={() => handleViewDetail(item)}- style={{- cursor: 'pointer',- width: '100%',- padding: '8px 0'- }}- >- <List.Item.Meta- title={- <div className={styles.notificationTitle}>- <span>{item.title}</span>- {item.status === 'unread' && <Badge status="processing" />}- </div>- }- description={- <div className={styles.notificationContent}>- <div className={styles.notificationMeta}>- <Tag color={getNotificationTypeColor(item.type)}>- {getNotificationTypeText(item.type)}- </Tag>- <span className={styles.time}>- <ClockCircleOutlined style={{ marginRight: 4 }} />- {formatTime(item.createdAt)}- </span>- </div>- <div className={styles.content}>- {item.content.length > 100- ? `${item.content.substring(0, 100)}...`- : item.content- }- </div>- </div>- }- />- </div>- </List.Item>+ <List.Item.Meta+ title={(+ <div className={styles.notificationTitle}>+ <span>{item.title}</span>+ {item.status === 'unread' && <Badge status="processing" />}+ </div>+ )}+ description={(+ <div className={styles.notificationContent}>+ <div className={styles.notificationMeta}>+ <Tag color={getNotificationTypeColor(item.type)}>+ {getNotificationTypeText(item.type)}+ </Tag>+ <span className={styles.time}>+ <ClockCircleOutlined style={{ marginRight: 4 }} />+ {formatTime(item.createdAt)}+ </span>+ </div>+ <div className={styles.content}>+ {item.content.length > 100+ ? `${item.content.substring(0, 100)}...`+ : item.content}+ </div>+ </div>+ )}+ />+ </div>+ </List.Item>+ )}+ />+ )+ : (+ <Empty description={t('noNotifications')} />)}- />- ) : (- <Empty description={t('noNotifications')} />- )}</Spin></Modal>{/* 通知详情弹窗 */}<Modal- title={+ title={(<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><span style={{ fontSize: '16px', fontWeight: '600' }}>{t('detailTitle')}</span></div>- }+ )}zIndex={2000}- open={detailModalVisible}- onCancel={() => {- setDetailModalVisible(false);- setSelectedTask(null);- }}- footer={[- <Button key="close" onClick={() => {- setDetailModalVisible(false);- setSelectedTask(null);- }} type="primary">- {t('close')}- </Button>- ]}+ open={detailModalVisible}+ onCancel={() => {+ setDetailModalVisible(false)+ setSelectedTask(null)+ }}+ footer={[+ <Button+ key="close"+ onClick={() => {+ setDetailModalVisible(false)+ setSelectedTask(null)+ }}+ type="primary"+ >+ {t('close')}+ </Button>,+ ]}width={800}styles={{header: {borderBottom: '1px solid #f0f0f0',- paddingBottom: '16px'+ paddingBottom: '16px',},body: {- padding: '24px'- }+ padding: '24px',+ },}}>- {selectedNotification && (- <div className={styles.notificationDetail}>- <h3>{selectedNotification.title}</h3>- <div className={styles.meta}>- <span>- <Tag color={getNotificationTypeColor(selectedNotification.type)}>- {getNotificationTypeText(selectedNotification.type)}- </Tag>- </span>- <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>- <span>- <ClockCircleOutlined style={{ marginRight: 4 }} />- {t('createTime')}: {formatTime(selectedNotification.createdAt)}- </span>- {selectedNotification.readAt && (- <span style={{ color: '#52c41a' }}>- {t('readTime')}: {formatTime(selectedNotification.readAt)}- </span>- )}- </div>- </div>- {/* <div className={styles.content}>+ {selectedNotification && (+ <div className={styles.notificationDetail}>+ <h3>{selectedNotification.title}</h3>+ <div className={styles.meta}>+ <span>+ <Tag color={getNotificationTypeColor(selectedNotification.type)}>+ {getNotificationTypeText(selectedNotification.type)}+ </Tag>+ </span>+ <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>+ <span>+ <ClockCircleOutlined style={{ marginRight: 4 }} />+ {t('createTime')}+ :+ {formatTime(selectedNotification.createdAt)}+ </span>+ {selectedNotification.readAt && (+ <span style={{ color: '#52c41a' }}>+ {t('readTime')}+ :+ {formatTime(selectedNotification.readAt)}+ </span>+ )}+ </div>+ </div>+ {/* <div className={styles.content}>{selectedNotification.content}</div> */}-- {/* 任务详情部分 */}- {selectedNotification.type === 'task_reminder' && (- <div className={styles.taskDetail}>- <h4 style={{ marginBottom: '16px', color: '#1890ff' }}>{t('taskDetail')}</h4>- <Spin spinning={taskLoading}>- {selectedTask ? (- <div className={styles.taskInfo}>- <div className={styles.taskHeader}>- <h5>{selectedTask.title}</h5>- <Tag color={selectedTask.status === 'active' ? 'green' : 'red'}>- {selectedTask.status === 'active' ? t('taskStatus.active' as any) : t('taskStatus.inactive' as any)}- </Tag>- </div>- <div className={styles.taskContent}>- <p><strong>{t('taskInfo.description' as any)}:</strong>- <div dangerouslySetInnerHTML={{ __html: selectedTask.description }} />- </p>- {/* 发布账号信息 */}- {selectedTask.accountId && (() => {- const publishAccount = getAccountById(selectedTask.accountId);- return publishAccount ? (- <p><strong>{t('taskInfo.publisherAccount' as any)}:</strong>- <div style={{ display: 'flex', alignItems: 'center', marginLeft: '4px', gap: '8px' }}>- <img- src={publishAccount.avatar ? getOssUrl(publishAccount.avatar) : '/default-avatar.png'}- alt="账号头像"- style={{- width: '24px',- height: '24px',- borderRadius: '50%',- objectFit: 'cover'- }}- onError={(e) => {- e.currentTarget.src = '/default-avatar.png';- }}- />- <Tag color="green">- {getPlatformName(publishAccount.type)} - {publishAccount.nickname}- </Tag>- </div>- </p>- ) : (- <p><strong>{t('taskInfo.publisherAccount' as any)}:</strong>- <Tag color="red" style={{ marginLeft: '4px' }}>- {t('accountInfoFailed')}- </Tag>- </p>- );- })()}++ {/* 任务详情部分 */}+ {selectedNotification.type === 'task_reminder' && (+ <div className={styles.taskDetail}>+ <h4 style={{ marginBottom: '16px', color: '#1890ff' }}>{t('taskDetail')}</h4>+ <Spin spinning={taskLoading}>+ {selectedTask+ ? (+ <div className={styles.taskInfo}>+ <div className={styles.taskHeader}>+ <h5>{selectedTask.title}</h5>+ <Tag color={selectedTask.status === 'active' ? 'green' : 'red'}>+ {selectedTask.status === 'active' ? t('taskStatus.active' as any) : t('taskStatus.inactive' as any)}+ </Tag>+ </div>+ <div className={styles.taskContent}>+ <p>+ <strong>+ {t('taskInfo.description' as any)}+ :+ </strong>+ <div dangerouslySetInnerHTML={{ __html: selectedTask.description }} />+ </p>+ {/* 发布账号信息 */}+ {selectedTask.accountId && (() => {+ const publishAccount = getAccountById(selectedTask.accountId)+ return publishAccount+ ? (+ <p>+ <strong>+ {t('taskInfo.publisherAccount' as any)}+ :+ </strong>+ <div style={{ display: 'flex', alignItems: 'center', marginLeft: '4px', gap: '8px' }}>+ <img+ src={publishAccount.avatar ? getOssUrl(publishAccount.avatar) : '/default-avatar.png'}+ alt="账号头像"+ style={{+ width: '24px',+ height: '24px',+ borderRadius: '50%',+ objectFit: 'cover',+ }}+ onError={(e) => {+ e.currentTarget.src = '/default-avatar.png'+ }}+ />+ <Tag color="green">+ {getPlatformName(publishAccount.type)}+ {' '}+ -+ {publishAccount.nickname}+ </Tag>+ </div>+ </p>+ )+ : (+ <p>+ <strong>+ {t('taskInfo.publisherAccount' as any)}+ :+ </strong>+ <Tag color="red" style={{ marginLeft: '4px' }}>+ {t('accountInfoFailed')}+ </Tag>+ </p>+ )+ })()}{/* 任务平台类型显示 */}{selectedTask.accountTypes && selectedTask.accountTypes.length > 0 && (- <p style={{ display: 'flex', alignItems: 'center', gap: '8px', margin: 0, marginBottom: '6px' }}>- <strong>{t('taskInfo.platformTypes' as any)}:</strong>- {selectedTask.accountTypes.map(type => {- const platformIcon = getPlatformIcon(type);- return platformIcon ? (- <img- key={type}- src={platformIcon}- alt={`${type} icon`}- style={{- width: '20px',- height: '20px',- objectFit: 'contain'- }}- />- ) : null;- })}- </p>- )}-- <p><strong>{t('taskInfo.reward' as any)}:</strong>¥{selectedTask.reward/100}</p>- {/* <p><strong>招募人数:</strong>{selectedTask.currentRecruits}/{selectedTask.maxRecruits}</p> */}-- <p><strong>{t('taskInfo.taskType' as any)}:</strong>- <Tag color="blue" style={{ marginLeft: '4px' }}>- {getTaskTypeName(selectedTask.type)}- </Tag>- </p>---- {/* 任务素材展示 */}- {selectedTask.materials && selectedTask.materials.length > 0 && (- <div style={{ marginTop: '16px' }}>- <p><strong>{t('taskInfo.taskType' as any)}:</strong></p>- <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>- {selectedTask.materials.map((material: any, index: number) => (- <div key={index} style={{- border: '1px solid #e8e8e8',- borderRadius: '8px',- padding: '8px',- maxWidth: '200px'- }}>- {/* <div style={{ fontSize: '12px', fontWeight: '500', marginBottom: '4px' }}>+ <p style={{ display: 'flex', alignItems: 'center', gap: '8px', margin: 0, marginBottom: '6px' }}>+ <strong>+ {t('taskInfo.platformTypes' as any)}+ :+ </strong>+ {selectedTask.accountTypes.map((type) => {+ const platformIcon = getPlatformIcon(type)+ return platformIcon+ ? (+ <img+ key={type}+ src={platformIcon}+ alt={`${type} icon`}+ style={{+ width: '20px',+ height: '20px',+ objectFit: 'contain',+ }}+ />+ )+ : null+ })}+ </p>+ )}++ <p>+ <strong>+ {t('taskInfo.reward' as any)}+ :+ </strong>+ ¥+ {selectedTask.reward / 100}+ </p>+ {/* <p><strong>招募人数:</strong>{selectedTask.currentRecruits}/{selectedTask.maxRecruits}</p> */}++ <p>+ <strong>+ {t('taskInfo.taskType' as any)}+ :+ </strong>+ <Tag color="blue" style={{ marginLeft: '4px' }}>+ {getTaskTypeName(selectedTask.type)}+ </Tag>+ </p>++ {/* 任务素材展示 */}+ {selectedTask.materials && selectedTask.materials.length > 0 && (+ <div style={{ marginTop: '16px' }}>+ <p>+ <strong>+ {t('taskInfo.taskType' as any)}+ :+ </strong>+ </p>+ <div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>+ {selectedTask.materials.map((material: any, index: number) => (+ <div+ key={index}+ style={{+ border: '1px solid #e8e8e8',+ borderRadius: '8px',+ padding: '8px',+ maxWidth: '200px',+ }}+ >+ {/* <div style={{ fontSize: '12px', fontWeight: '500', marginBottom: '4px' }}>{material.title}</div> */}- { (material.coverUrl && material.type !== "video") && (- <img- src={getOssUrl(material.coverUrl)}- alt="cover"- style={{- width: '100%',- height: '100px',- objectFit: 'cover',- borderRadius: '4px',- marginBottom: '4px'- }}- />- )}- {/* <div style={{ fontSize: '11px', color: '#666', lineHeight: '1.3' }}>+ { (material.coverUrl && material.type !== 'video') && (+ <img+ src={getOssUrl(material.coverUrl)}+ alt="cover"+ style={{+ width: '100%',+ height: '100px',+ objectFit: 'cover',+ borderRadius: '4px',+ marginBottom: '4px',+ }}+ />+ )}+ {/* <div style={{ fontSize: '11px', color: '#666', lineHeight: '1.3' }}>{material.desc?.substring(0, 50)}{material.desc?.length > 50 ? '...' : ''}</div> */}- {material.mediaList && material.mediaList.length > 0 && (- <div style={{- display: 'flex',- gap: '4px',- marginTop: '4px',- flexWrap: 'wrap'- }}>- {material.mediaList.slice(0, 3).map((media: any, mediaIndex: number) => (- <div key={mediaIndex} style={{ position: 'relative', cursor: 'pointer' }}>- {media.type === 'video' ? (- <div- style={{- width: '180px',- height: '180px',- borderRadius: '2px',- position: 'relative',- overflow: 'hidden'- }}- onClick={() => handleVideoCoverClick(media, material.title)}- >- {/* 视频封面图片 - 使用material.coverUrl */}- <img- src={material.coverUrl ? getOssUrl(material.coverUrl) : getOssUrl(media.url)}- alt="video cover"- style={{- width: '100%',- height: '100%',- objectFit: 'cover'- }}- />- {/* 播放按钮 */}- <div style={{- position: 'absolute',- top: '50%',- left: '50%',- transform: 'translate(-50%, -50%)',- color: 'white',- fontSize: '11px',- background: 'rgba(0,0,0,0.6)',- borderRadius: '50%',- width: '26px',- height: '26px',- display: 'flex',- alignItems: 'center',- justifyContent: 'center'- }}>- ▶- </div>- </div>- ) : (- <img- src={getOssUrl(media.url)}- alt="media"- style={{- width: '40px',- height: '40px',- objectFit: 'cover',- borderRadius: '2px'- }}- onClick={() => handleMediaClick(media, material.title)}- />- )}- </div>- ))}- {material.mediaList.length > 3 && (- <div style={{- width: '40px',- height: '40px',- background: '#f0f0f0',- borderRadius: '2px',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- fontSize: '10px',- color: '#666'- }}>- +{material.mediaList.length - 3}- </div>- )}- </div>- )}- </div>- ))}- </div>- </div>- )}- </div>- {selectedTask.status === 'active' && selectedTask.currentRecruits < selectedTask.maxRecruits && (- <div className={styles.taskActions}>- {/* 需要App操作的平台提示 - 只根据发布账号类型判断 */}- {(() => {- // 只根据发布账号类型判断是否需要App操作- if (selectedTask.accountId) {- const publishAccount = getAccountById(selectedTask.accountId);- if (publishAccount) {- const appRequiredPlatforms = getTasksRequiringApp([publishAccount.type]);- if (appRequiredPlatforms.length > 0) {- const platformNames = appRequiredPlatforms.map(p => getAppDownloadConfig(p)?.platform).filter(Boolean);- return (- <div style={{- marginBottom: '12px',- padding: '12px',- backgroundColor: '#fff7e6',- border: '1px solid #ffd591',- borderRadius: '6px',- color: '#d46b08'- }}>- <strong>{t('appRequiredNotice')}</strong>- {t('appRequiredMessage' as any, { platform: getPlatformName(publishAccount.type) })}- </div>- );- }- }- }- return null;- })()}-- {-- selectedTask.opportunityStatus == 'pending' && (- <Button- type="primary"- onClick={() => handleTaskAction(selectedTask)}- style={{ marginTop: '12px' }}- >- {t('acceptTask')}- </Button>- )- }- </div>- )}- </div>- ) : !taskLoading && (- <div style={{ textAlign: 'center', color: '#999' }}>- {t('noTaskDetails')}- </div>- )}- </Spin>- </div>- )}- </div>- )}+ {material.mediaList && material.mediaList.length > 0 && (+ <div style={{+ display: 'flex',+ gap: '4px',+ marginTop: '4px',+ flexWrap: 'wrap',+ }}+ >+ {material.mediaList.slice(0, 3).map((media: any, mediaIndex: number) => (+ <div key={mediaIndex} style={{ position: 'relative', cursor: 'pointer' }}>+ {media.type === 'video'+ ? (+ <div+ style={{+ width: '180px',+ height: '180px',+ borderRadius: '2px',+ position: 'relative',+ overflow: 'hidden',+ }}+ onClick={() => handleVideoCoverClick(media, material.title)}+ >+ {/* 视频封面图片 - 使用material.coverUrl */}+ <img+ src={material.coverUrl ? getOssUrl(material.coverUrl) : getOssUrl(media.url)}+ alt="video cover"+ style={{+ width: '100%',+ height: '100%',+ objectFit: 'cover',+ }}+ />+ {/* 播放按钮 */}+ <div style={{+ position: 'absolute',+ top: '50%',+ left: '50%',+ transform: 'translate(-50%, -50%)',+ color: 'white',+ fontSize: '11px',+ background: 'rgba(0,0,0,0.6)',+ borderRadius: '50%',+ width: '26px',+ height: '26px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ }}+ >+ ▶+ </div>+ </div>+ )+ : (+ <img+ src={getOssUrl(media.url)}+ alt="media"+ style={{+ width: '40px',+ height: '40px',+ objectFit: 'cover',+ borderRadius: '2px',+ }}+ onClick={() => handleMediaClick(media, material.title)}+ />+ )}+ </div>+ ))}+ {material.mediaList.length > 3 && (+ <div style={{+ width: '40px',+ height: '40px',+ background: '#f0f0f0',+ borderRadius: '2px',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: '10px',+ color: '#666',+ }}+ >+ ++ {material.mediaList.length - 3}+ </div>+ )}+ </div>+ )}+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ {selectedTask.status === 'active' && selectedTask.currentRecruits < selectedTask.maxRecruits && (+ <div className={styles.taskActions}>+ {/* 需要App操作的平台提示 - 只根据发布账号类型判断 */}+ {(() => {+ // 只根据发布账号类型判断是否需要App操作+ if (selectedTask.accountId) {+ const publishAccount = getAccountById(selectedTask.accountId)+ if (publishAccount) {+ const appRequiredPlatforms = getTasksRequiringApp([publishAccount.type])+ if (appRequiredPlatforms.length > 0) {+ const platformNames = appRequiredPlatforms.map(p => getAppDownloadConfig(p)?.platform).filter(Boolean)+ return (+ <div style={{+ marginBottom: '12px',+ padding: '12px',+ backgroundColor: '#fff7e6',+ border: '1px solid #ffd591',+ borderRadius: '6px',+ color: '#d46b08',+ }}+ >+ <strong>{t('appRequiredNotice')}</strong>+ {t('appRequiredMessage' as any, { platform: getPlatformName(publishAccount.type) })}+ </div>+ )+ }+ }+ }+ return null+ })()}++ {+ selectedTask.opportunityStatus === 'pending' && (+ <Button+ type="primary"+ onClick={() => handleTaskAction(selectedTask)}+ style={{ marginTop: '12px' }}+ >+ {t('acceptTask')}+ </Button>+ )+ }+ </div>+ )}+ </div>+ )+ : !taskLoading && (+ <div style={{ textAlign: 'center', color: '#999' }}>+ {t('noTaskDetails')}+ </div>+ )}+ </Spin>+ </div>+ )}+ </div>+ )}</Modal>-+{/* 下载App提示弹窗 */}<DownloadAppModalvisible={downloadAppVisible}@@ -1160,7 +1244,7 @@ const NotificationPanel: React.FC<NotificationPanelProps> = ({ visible, onClosefooter={[<Button key="close" onClick={handleCloseMediaPreview}>{t('close')}- </Button>+ </Button>,]}width={previewMedia?.type === 'video' ? 800 : 600}zIndex={3000}@@ -1168,42 +1252,44 @@ const NotificationPanel: React.FC<NotificationPanelProps> = ({ visible, onClosestyles={{body: {padding: '24px',- textAlign: 'center'- }+ textAlign: 'center',+ },}}>{previewMedia && (<div>- {previewMedia.type === 'video' ? (- <video- ref={setVideoRef}- src={previewMedia.url}- controls- style={{- width: '100%',- maxHeight: '500px',- borderRadius: '8px'- }}- autoPlay- onEnded={() => {- // 视频播放结束时重置到开始- if (videoRef) {- videoRef.currentTime = 0;- }- }}- />- ) : (- <img- src={previewMedia.url}- alt="preview"- style={{- width: '100%',- maxHeight: '500px',- objectFit: 'contain',- borderRadius: '8px'- }}- />- )}+ {previewMedia.type === 'video'+ ? (+ <video+ ref={setVideoRef}+ src={previewMedia.url}+ controls+ style={{+ width: '100%',+ maxHeight: '500px',+ borderRadius: '8px',+ }}+ autoPlay+ onEnded={() => {+ // 视频播放结束时重置到开始+ if (videoRef) {+ videoRef.currentTime = 0+ }+ }}+ />+ )+ : (+ <img+ src={previewMedia.url}+ alt="preview"+ style={{+ width: '100%',+ maxHeight: '500px',+ objectFit: 'contain',+ borderRadius: '8px',+ }}+ />+ )}</div>)}</Modal>@@ -1219,8 +1305,8 @@ const NotificationPanel: React.FC<NotificationPanelProps> = ({ visible, onClosezIndex={3000}styles={{body: {- padding: '24px'- }+ padding: '24px',+ },}}><Steps@@ -1229,10 +1315,13 @@ const NotificationPanel: React.FC<NotificationPanelProps> = ({ visible, onCloseitems={taskProgress.steps.map((step, index) => ({title: step.title,status: step.status as 'wait' | 'process' | 'finish' | 'error',- description: index === 0 ? t('acceptingTask' as any) :- index === 1 ? t('publishingTask' as any) :- index === 2 ? t('submittingTask' as any) :- t('taskCompleted' as any)+ description: index === 0+ ? t('acceptingTask' as any)+ : index === 1+ ? t('publishingTask' as any)+ : index === 2+ ? t('submittingTask' as any)+ : t('taskCompleted' as any),}))}/></Modal>@@ -1248,11 +1337,11 @@ const NotificationPanel: React.FC<NotificationPanelProps> = ({ visible, onClosestyles={{header: {borderBottom: '1px solid #f0f0f0',- paddingBottom: '16px'+ paddingBottom: '16px',},body: {- padding: '24px'- }+ padding: '24px',+ },}}><div style={{ marginBottom: '16px' }}>@@ -1262,28 +1351,28 @@ const NotificationPanel: React.FC<NotificationPanelProps> = ({ visible, onClose</div><ListdataSource={availableAccounts}- renderItem={(account) => (+ renderItem={account => (<List.Item- style={{+ style={{cursor: 'pointer',padding: '16px',border: '1px solid #f0f0f0',borderRadius: '8px',marginBottom: '8px',- transition: 'all 0.3s ease'+ transition: 'all 0.3s ease',}}onClick={() => handleAccountSelect(account)}onMouseEnter={(e) => {- e.currentTarget.style.borderColor = '#1890ff';- e.currentTarget.style.backgroundColor = '#f6ffed';+ e.currentTarget.style.borderColor = '#1890ff'+ e.currentTarget.style.backgroundColor = '#f6ffed'}}onMouseLeave={(e) => {- e.currentTarget.style.borderColor = '#f0f0f0';- e.currentTarget.style.backgroundColor = 'transparent';+ e.currentTarget.style.borderColor = '#f0f0f0'+ e.currentTarget.style.backgroundColor = 'transparent'}}><List.Item.Meta- avatar={+ avatar={(<imgsrc={account.avatar ? getOssUrl(account.avatar) : '/default-avatar.png'}alt="账号头像"@@ -1291,32 +1380,44 @@ const NotificationPanel: React.FC<NotificationPanelProps> = ({ visible, onClosewidth: '48px',height: '48px',borderRadius: '50%',- objectFit: 'cover'+ objectFit: 'cover',}}onError={(e) => {- e.currentTarget.src = '/default-avatar.png';+ e.currentTarget.src = '/default-avatar.png'}}/>- }- title={+ )}+ title={(<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}><span style={{ fontWeight: '600' }}>{account.nickname}</span><Tag color="blue">{getPlatformName(account.type)}</Tag></div>- }- description={+ )}+ description={(<div style={{ color: '#666' }}>- <div>{t('accountSelect.accountId' as any)}: {account.account}</div>- {account.nickname && <div>{t('accountSelect.description' as any)}: {account.nickname}</div>}+ <div>+ {t('accountSelect.accountId' as any)}+ :+ {' '}+ {account.account}+ </div>+ {account.nickname && (+ <div>+ {t('accountSelect.description' as any)}+ :+ {' '}+ {account.nickname}+ </div>+ )}</div>- }+ )}/></List.Item>)}/></Modal></>- );-};+ )+}-export default NotificationPanel;\ No newline at end of file+export default NotificationPaneldiff --git a/project/web/src/constant.ts b/project/web/src/constant.tsindex d9ed2a59..14fa78b8 100644--- a/project/web/src/constant.ts+++ b/project/web/src/constant.ts@@ -1,12 +1,12 @@// api url-export const APP_HOT_URL = "https://att-contents.yikart.cn/api";+export const APP_HOT_URL = 'https://att-contents.yikart.cn/api'// 代理地址export const ProxyUrls = [- "/api/",+ '/api/',process.env.NEXT_PUBLIC_BILI_OSS_PROXY,process.env.NEXT_PUBLIC_OSS_URL_PROXY,-];+]// OSS URL-export const OSS_URL = process.env.NEXT_PUBLIC_OSS_URL!;+export const OSS_URL = process.env.NEXT_PUBLIC_OSS_URL!diff --git a/project/web/src/hooks/useNotification.ts b/project/web/src/hooks/useNotification.tsindex df2fa09a..b31b53e0 100644--- a/project/web/src/hooks/useNotification.ts+++ b/project/web/src/hooks/useNotification.ts@@ -1,50 +1,51 @@-import { useState, useEffect, useCallback } from "react";-import { getUnreadCount } from "@/api/notification";-import { useUserStore } from "@/store/user";+import { useCallback, useEffect, useState } from 'react'+import { getUnreadCount } from '@/api/notification'+import { useUserStore } from '@/store/user'-export const useNotification = () => {- const [unreadCount, setUnreadCount] = useState(0);- const [loading, setLoading] = useState(false);- const token = useUserStore((state) => state.token);+export function useNotification() {+ const [unreadCount, setUnreadCount] = useState(0)+ const [loading, setLoading] = useState(false)+ const token = useUserStore(state => state.token)const fetchUnreadCount = useCallback(async () => {// 如果没有登录信息,不发送请求if (!token) {- setUnreadCount(0);- return;+ setUnreadCount(0)+ return}try {- setLoading(true);- const response = await getUnreadCount();+ setLoading(true)+ const response = await getUnreadCount()if (response && response.data) {- setUnreadCount(response.data.count || 0);+ setUnreadCount(response.data.count || 0)}- } catch (error) {- console.error("获取未读数量失败:", error);- } finally {- setLoading(false);}- }, [token]);-+ catch (error) {+ console.error('获取未读数量失败:', error)+ }+ finally {+ setLoading(false)+ }+ }, [token])useEffect(() => {// 初始获取- fetchUnreadCount();+ fetchUnreadCount()// 每10秒获取一次未读数量const interval = setInterval(() => {- fetchUnreadCount();- }, 60000);+ fetchUnreadCount()+ }, 60000)return () => {- clearInterval(interval);- };- }, [fetchUnreadCount]);+ clearInterval(interval)+ }+ }, [fetchUnreadCount])return {unreadCount,loading,refreshUnreadCount: fetchUnreadCount,- };-};\ No newline at end of file+ }+}diff --git a/project/web/src/hooks/useSystem.ts b/project/web/src/hooks/useSystem.tsindex f28726c9..15e2cecb 100644--- a/project/web/src/hooks/useSystem.ts+++ b/project/web/src/hooks/useSystem.ts@@ -1,14 +1,14 @@-import { useParams } from "next/navigation";-import { fallbackLng, languages } from "@/app/i18n/settings";+import { useParams } from 'next/navigation'+import { fallbackLng, languages } from '@/app/i18n/settings'export function useGetClientLng() {- const params = useParams();- const lng = params?.lng;-+ const params = useParams()+ const lng = params?.lng+// 确保返回的语言在支持的语言列表中if (lng && languages.includes(lng as string)) {- return lng as string;+ return lng as string}-- return fallbackLng;++ return fallbackLng}diff --git a/project/web/src/middleware.ts b/project/web/src/middleware.tsindex d379277c..23a49e6a 100644--- a/project/web/src/middleware.ts+++ b/project/web/src/middleware.ts@@ -1,67 +1,72 @@-import { NextResponse, NextRequest } from "next/server";-import acceptLanguage from "accept-language";-import { fallbackLng, languages, cookieName } from "@/app/i18n/settings";-import { ProxyUrls } from "@/constant";+import type { NextRequest } from 'next/server'+import acceptLanguage from 'accept-language'+import { NextResponse } from 'next/server'+import { cookieName, fallbackLng, languages } from '@/app/i18n/settings'+import { ProxyUrls } from '@/constant'-acceptLanguage.languages(languages);+acceptLanguage.languages(languages)export const config = {// matcher: '/:lng*'matcher: [- "/((?!api|_next/static|_next/image|assets|favicon.ico|sw.js|site.webmanifest).*)",+ '/((?!api|_next/static|_next/image|assets|favicon.ico|sw.js|site.webmanifest).*)',],-};+}export function middleware(req: NextRequest) {- if (ProxyUrls.find((v) => req.nextUrl.pathname.includes(v!))) {- return NextResponse.next();+ if (ProxyUrls.find(v => req.nextUrl.pathname.includes(v!))) {+ return NextResponse.next()}if ([- "/robots.txt",- "/sitemap.xml",- "/sitemap-0.xml",- "/sitemap-1.xml",- "/sitemap-2.xml",- "/sitemap-3.xml",- "/sitemap-4.xml",- "/sitemap",- "/chat",- "/healthz",- ].find((v) => req.nextUrl.pathname.includes(v!))+ '/robots.txt',+ '/sitemap.xml',+ '/sitemap-0.xml',+ '/sitemap-1.xml',+ '/sitemap-2.xml',+ '/sitemap-3.xml',+ '/sitemap-4.xml',+ '/sitemap',+ '/chat',+ '/healthz',+ ].find(v => req.nextUrl.pathname.includes(v!))) {- return NextResponse.next();+ return NextResponse.next()}if (- req.nextUrl.pathname.indexOf("icon") > -1 ||- req.nextUrl.pathname.indexOf("chrome") > -1- )- return NextResponse.next();- let lng: string | undefined | null;+ req.nextUrl.pathname.includes('icon')+ || req.nextUrl.pathname.includes('chrome')+ ) {+ return NextResponse.next()+ }+ let lng: string | undefined | nullif (req.cookies.has(cookieName))- lng = acceptLanguage.get(req.cookies.get(cookieName)?.value);- if (!lng) lng = acceptLanguage.get(req.headers.get("Accept-Language"));- if (!lng) lng = fallbackLng;+ lng = acceptLanguage.get(req.cookies.get(cookieName)?.value)+ if (!lng)+ lng = acceptLanguage.get(req.headers.get('Accept-Language'))+ if (!lng)+ lng = fallbackLng// Redirect if lng in path is not supportedif (- !languages.some((loc) => req.nextUrl.pathname.startsWith(`/${loc}`)) &&- !req.nextUrl.pathname.startsWith("/_next")+ !languages.some(loc => req.nextUrl.pathname.startsWith(`/${loc}`))+ && !req.nextUrl.pathname.startsWith('/_next')) {return NextResponse.redirect(new URL(`/${lng}${req.nextUrl.pathname}${req.nextUrl.search}`, req.url),- );+ )}- if (req.headers.has("referer")) {- const refererUrl = new URL(req.headers.get("referer") || "");- const lngInReferer = languages.find((l) =>+ if (req.headers.has('referer')) {+ const refererUrl = new URL(req.headers.get('referer') || '')+ const lngInReferer = languages.find(l =>refererUrl.pathname.startsWith(`/${l}`),- );- const response = NextResponse.next();- if (lngInReferer) response.cookies.set(cookieName, lngInReferer);- return response;+ )+ const response = NextResponse.next()+ if (lngInReferer)+ response.cookies.set(cookieName, lngInReferer)+ return response}- return NextResponse.next();+ return NextResponse.next()}diff --git a/project/web/src/store/account.ts b/project/web/src/store/account.tsindex 3f1365a9..f67c65ad 100644--- a/project/web/src/store/account.ts+++ b/project/web/src/store/account.ts@@ -1,25 +1,25 @@-import { create } from "zustand";-import { combine } from "zustand/middleware";-import lodash from "lodash";-import { AccountGroupItem, SocialAccount } from "@/api/types/account.type";-import { getAccountGroupApi, getAccountListApi } from "@/api/account";-import { directTrans } from "@/app/i18n/client";-import { useUserStore } from "@/store/user";+import type { AccountGroupItem, SocialAccount } from '@/api/types/account.type'+import lodash from 'lodash'+import { create } from 'zustand'+import { combine } from 'zustand/middleware'+import { getAccountGroupApi, getAccountListApi } from '@/api/account'+import { directTrans } from '@/app/i18n/client'+import { useUserStore } from '@/store/user'export interface AccountGroup extends AccountGroupItem {- children: SocialAccount[];+ children: SocialAccount[]}export interface IAccountStore {- accountList: SocialAccount[];- accountMap: Map<string, SocialAccount>;+ accountList: SocialAccount[]+ accountMap: Map<string, SocialAccount>// key=account,value=账户- accountAccountMap: Map<string, SocialAccount>;- accountGroupList: AccountGroup[];- accountGroupMap: Map<string, AccountGroup>;- accountLoading: boolean;+ accountAccountMap: Map<string, SocialAccount>+ accountGroupList: AccountGroup[]+ accountGroupMap: Map<string, AccountGroup>+ accountLoading: boolean// 当前选择的账户- accountActive?: SocialAccount;+ accountActive?: SocialAccount}const store: IAccountStore = {@@ -32,11 +32,11 @@ const store: IAccountStore = {accountAccountMap: new Map([]),accountLoading: false,accountActive: undefined,-};+}-const getStore = () => {- return lodash.cloneDeep(store);-};+function getStore() {+ return lodash.cloneDeep(store)+}// 视频发布所有组件的共享状态和方法export const useAccountStore = create(@@ -49,59 +49,62 @@ export const useAccountStore = create(clear() {set({...getStore(),- });+ })},// 设置选择账户IDsetAccountActive(accountActive?: SocialAccount) {set({accountActive,- });+ })},setAccountGroupList(accountGroupList: AccountGroup[]) {- set({ accountGroupList });+ set({ accountGroupList })},/*** 异步获取账户列表(含稳健的loading与错误处理),避免阻塞UI*/async getAccountList() {- if (get().accountLoading) return;- set({ accountLoading: true });+ if (get().accountLoading)+ return+ set({ accountLoading: true })try {- const accountMap = new Map<string, SocialAccount>([]);- const accountAccountMap = new Map<string, SocialAccount>([]);+ const accountMap = new Map<string, SocialAccount>([])+ const accountAccountMap = new Map<string, SocialAccount>([])// 防卡死:给请求增加超时兜底(例如 15s),即使后端迟迟不返回也不会一直占用loading- const timeoutMs = 10000;+ const timeoutMs = 10000const timeoutPromise = new Promise<any>((resolve) => {- setTimeout(() => resolve({ code: -1, data: [] }), timeoutMs);- });+ setTimeout(() => resolve({ code: -1, data: [] }), timeoutMs)+ })const result = await Promise.race([getAccountListApi(),timeoutPromise,- ]);+ ])- if (result?.code !== 0) return;+ if (result?.code !== 0)+ return- const accountList: SocialAccount[] = [];+ const accountList: SocialAccount[] = []for (const item of result.data) {- accountMap.set(item.id, item);- accountAccountMap.set(item.account, item);- accountList.push(item);+ accountMap.set(item.id, item)+ accountAccountMap.set(item.account, item)+ accountList.push(item)}set({accountList,accountMap,accountAccountMap,- });+ })// 后续分组数据获取不阻塞调用方- methods.getAccountGroup();- } finally {- set({ accountLoading: false });+ methods.getAccountGroup()+ }+ finally {+ set({ accountLoading: false })}},@@ -110,62 +113,66 @@ export const useAccountStore = create(*/getAccountListInBackground() {// fire-and-forget,内部自行处理loading与错误- void methods.getAccountList();+ void methods.getAccountList()},// 获取用户组的数据并且将用户放到对应组下async getAccountGroup() {- const res = await getAccountGroupApi();- const groupList = res?.data;+ const res = await getAccountGroupApi()+ const groupList = res?.data- if (!groupList) return;- if (groupList.length === 0) return;+ if (!groupList)+ return+ if (groupList.length === 0)+ returngroupList.map((v: any) => {v.name = v.isDefault- ? directTrans("account", "defaultSpace")- : v.name;- });+ ? directTrans('account', 'defaultSpace')+ : v.name+ })- const accountGroupList: AccountGroup[] = [];+ const accountGroupList: AccountGroup[] = []// key=组ID,val=账户ID- const accountGroupMap = new Map<string, AccountGroup>();+ const accountGroupMap = new Map<string, AccountGroup>()- const defaultGroup = groupList.find((v: any) => v.isDefault)!;+ const defaultGroup = groupList.find((v: any) => v.isDefault)!groupList.map((v: any) => {const accountGroupItem = {...v,children: [],- };- accountGroupList.push(accountGroupItem);- accountGroupMap.set(v.id, accountGroupItem);- });+ }+ accountGroupList.push(accountGroupItem)+ accountGroupMap.set(v.id, accountGroupItem)+ })get().accountList.map((v) => {if (accountGroupMap.get(v.groupId!)) {- accountGroupMap.get(v.groupId!)!.children?.push(v);- } else {- accountGroupMap.get(defaultGroup.id)!.children?.push(v);- v.groupId = defaultGroup.id;+ accountGroupMap.get(v.groupId!)!.children?.push(v)+ }+ else {+ accountGroupMap.get(defaultGroup.id)!.children?.push(v)+ v.groupId = defaultGroup.id}- });+ })accountGroupList.sort((a, b) => {- return a.rank - b.rank;- });+ return a.rank - b.rank+ })set({accountGroupList,accountGroupMap,- });+ })},async accountInit() {- if (get().accountList.length > 0) return;+ if (get().accountList.length > 0)+ return// 改为后台异步拉取,避免初始化时阻塞界面- methods.getAccountListInBackground();+ methods.getAccountListInBackground()},- };- return methods;+ }+ return methods},),-);+)diff --git a/project/web/src/store/commont.ts b/project/web/src/store/commont.tsindex ea602776..68af458b 100644--- a/project/web/src/store/commont.ts+++ b/project/web/src/store/commont.ts@@ -1,15 +1,15 @@-import { create } from "zustand";-import { combine } from "zustand/middleware";-import { NotificationInstance } from "antd/es/notification/interface";+import type { NotificationInstance } from 'antd/es/notification/interface'+import { create } from 'zustand'+import { combine } from 'zustand/middleware'export interface ICommontStore {// 全局通知api- notification?: NotificationInstance;+ notification?: NotificationInstance}const store: ICommontStore = {notification: undefined,-};+}// 项目中的通用的、全局的状态和方法export const useCommontStore = create(@@ -22,10 +22,10 @@ export const useCommontStore = create(setNotification(notification: NotificationInstance) {set({notification,- });+ })},- };- return methods;+ }+ return methods},),-);+)diff --git a/project/web/src/store/system.ts b/project/web/src/store/system.tsindex df7521dc..1c499fd4 100644--- a/project/web/src/store/system.ts+++ b/project/web/src/store/system.ts@@ -1,13 +1,13 @@-import { createPersistStore } from "@/utils/createPersistStore";+import { createPersistStore } from '@/utils/createPersistStore'export interface ISystemStore {// 视频发布是否开启填写更多参数- moreParamsOpen: boolean;+ moreParamsOpen: boolean}const state: ISystemStore = {moreParamsOpen: false,-};+}export const useSystemStore = createPersistStore({@@ -18,13 +18,13 @@ export const useSystemStore = createPersistStore(setMoreParamsOpen(moreParamsOpen: boolean) {set({moreParamsOpen,- });+ })},- };+ }- return methods;+ return methods},{- name: "System",+ name: 'System',},-);+)diff --git a/project/web/src/store/user.ts b/project/web/src/store/user.tsindex c1287cdd..74c3144e 100644--- a/project/web/src/store/user.ts+++ b/project/web/src/store/user.ts@@ -1,45 +1,45 @@-import { createPersistStore } from "@/utils/createPersistStore";-import { getUserInfoApi } from "@/api/apiReq";-import i18next from "i18next";+import i18next from 'i18next'+import { getUserInfoApi } from '@/api/apiReq'+import { createPersistStore } from '@/utils/createPersistStore'export interface UserInfo {- createTime: string;- id: string;- name: string;- password: string;- phone?: string;- mail: string;- salt: string;- status: number;- updateTime: string;- _id: string;- avatar?: string;- isVip?: boolean;- score?: number;- income?: number; // 余额字段- popularizeCode?: string;+ createTime: string+ id: string+ name: string+ password: string+ phone?: string+ mail: string+ salt: string+ status: number+ updateTime: string+ _id: string+ avatar?: string+ isVip?: boolean+ score?: number+ income?: number // 余额字段+ popularizeCode?: stringvipInfo?: {- id: string;- expireTime: string;- startTime: string;+ id: string+ expireTime: string+ startTime: stringstatus:- | "none"- | "trialing"- | "monthly_once"- | "yearly_once"- | "active_monthly"- | "active_yearly"- | "active_nonrenewing"- | "expired";- _id: string;- };+ | 'none'+ | 'trialing'+ | 'monthly_once'+ | 'yearly_once'+ | 'active_monthly'+ | 'active_yearly'+ | 'active_nonrenewing'+ | 'expired'+ _id: string+ }}export interface IUserStore {- token?: string;- userInfo?: Partial<UserInfo>;- isAddAccountPorxy: boolean;- lang: string;+ token?: string+ userInfo?: Partial<UserInfo>+ isAddAccountPorxy: boolean+ lang: string}const state: IUserStore = {@@ -47,8 +47,8 @@ const state: IUserStore = {userInfo: {},// 添加账户是否默认开启代理isAddAccountPorxy: false,- lang: i18next.language || "en",-};+ lang: i18next.language || 'en',+}export const useUserStore = createPersistStore({@@ -60,43 +60,43 @@ export const useUserStore = createPersistStore(setLang(lang: string) {set({lang,- });+ })},setIsAddAccountPorxy(isAddAccountPorxy: boolean) {- set({ isAddAccountPorxy });+ set({ isAddAccountPorxy })},setToken: (token: string) => {- set({ token });+ set({ token })},setUserInfo: (userInfo: UserInfo) => {- set({ userInfo });+ set({ userInfo })},// 获取用户信息async getUserInfo() {- const res = await getUserInfoApi();+ const res = await getUserInfoApi()if (res) {set({userInfo: res.data,- });+ })}},// 清除登录状态clearLoginStatus: () => {- set({ token: undefined, userInfo: undefined });+ set({ token: undefined, userInfo: undefined })},// 登出logout() {- methods.clearLoginStatus();- window.location.href = "/login";+ methods.clearLoginStatus()+ window.location.href = '/login'},- };+ }- return methods;+ return methods},{- name: "User",+ name: 'User',},-);+)diff --git a/project/web/src/utils/FetchService/FetchService.ts b/project/web/src/utils/FetchService/FetchService.tsindex b7de0d7b..fd5e7a1b 100644--- a/project/web/src/utils/FetchService/FetchService.ts+++ b/project/web/src/utils/FetchService/FetchService.ts@@ -1,48 +1,50 @@-import { Dictionary, IFetchServiceConfig, RequestParams } from "./types";+import type { Dictionary, IFetchServiceConfig, RequestParams } from './types'/*** 泛型:* T=返回类型*/-class FetchService<T = Response> {- baseURL: string;+class FetchService<T = Response> {+ baseURL: string// 请求拦截requestInterceptor?: (requestParams: RequestParams,- ) => RequestParams | void | null;+ ) => RequestParams | void | null+// 响应拦截- responseInterceptor?: (response: Response) => T;+ responseInterceptor?: (response: Response) => Tconstructor({baseURL,requestInterceptor,responseInterceptor,}: IFetchServiceConfig<T>) {- this.baseURL = baseURL;- this.requestInterceptor = requestInterceptor;- this.responseInterceptor = responseInterceptor;+ this.baseURL = baseURL+ this.requestInterceptor = requestInterceptor+ this.responseInterceptor = responseInterceptor}// 过滤一个字典 value 为undefined的keyprivate _filterDictUndefined(data: Dictionary) {return Object.fromEntries(Object.entries(data).filter(([_, value]) => value !== undefined),- );+ )}public async request(requestParams: RequestParams): Promise<T> {return new Promise(async (resolve, reject) => {// 请求拦截if (this.requestInterceptor) {- const newRequestParams = this.requestInterceptor(requestParams);- if (!newRequestParams) return reject(null);- requestParams = newRequestParams;+ const newRequestParams = this.requestInterceptor(requestParams)+ if (!newRequestParams)+ return reject(null)+ requestParams = newRequestParams}// body 参数处理- const fetchURL = requestParams.url.startsWith("http")+ const fetchURL = requestParams.url.startsWith('http')? requestParams.url- : this.baseURL + requestParams.url;+ : this.baseURL + requestParams.urlif (!requestParams.body && requestParams.data) {// 检查是否为FormDataif (requestParams.data instanceof FormData) {@@ -51,43 +53,44 @@ class FetchService<T = Response> {...requestParams,body: requestParams.data,// 不手动设置Content-Type,让浏览器自动处理- };- } else {+ }+ }+ else {// 非FormData对象走原来的逻辑- requestParams.data = this._filterDictUndefined(requestParams.data);+ requestParams.data = this._filterDictUndefined(requestParams.data)requestParams = {...requestParams,body: requestParams.body? requestParams.body: JSON.stringify(requestParams.data),headers: {- ...(requestParams["headers"] || {}),- "content-type":+ ...(requestParams.headers || {}),+ 'content-type':// @ts-ignore- requestParams["headers"]["Content-Type"] ?? "application/json",+ requestParams.headers['Content-Type'] ?? 'application/json',},- };+ }}}// params 参数处理- let params: string | null = null;+ let params: string | null = nullif (requestParams.params) {- requestParams.params = this._filterDictUndefined(requestParams.params);- params = new URLSearchParams(requestParams.params).toString();+ requestParams.params = this._filterDictUndefined(requestParams.params)+ params = new URLSearchParams(requestParams.params).toString()}const res = await fetch(params ? `${fetchURL}?${params}` : fetchURL, {...requestParams,- });+ })if (this.responseInterceptor) {- return resolve(this.responseInterceptor(res));+ return resolve(this.responseInterceptor(res))}- resolve(res as T);- });+ resolve(res as T)+ })}}-export default FetchService;+export default FetchServicediff --git a/project/web/src/utils/FetchService/types.d.ts b/project/web/src/utils/FetchService/types.d.tsindex 74251a4e..c89d22b1 100644--- a/project/web/src/utils/FetchService/types.d.ts+++ b/project/web/src/utils/FetchService/types.d.ts@@ -1,18 +1,18 @@export interface RequestParams extends RequestInit {- url: string;- method: "GET" | "POST" | "PUT" | "DELETE";- data?: Dictionary;- params?: Dictionary;+ url: string+ method: 'GET' | 'POST' | 'PUT' | 'DELETE'+ data?: Dictionary+ params?: Dictionary}-export type Dictionary<T = any> = {- [key: string]: T;-};+export interface Dictionary<T = any> {+ [key: string]: T+}export interface IFetchServiceConfig<T = Response> {- baseURL: string;+ baseURL: stringrequestInterceptor?: (requestParams: RequestParams,- ) => RequestParams | void | null;- responseInterceptor?: (response: Response) => T;+ ) => RequestParams | void | null+ responseInterceptor?: (response: Response) => T}diff --git a/project/web/src/utils/createPersistStore.ts b/project/web/src/utils/createPersistStore.tsindex fab9efdf..09cbeaf2 100644--- a/project/web/src/utils/createPersistStore.ts+++ b/project/web/src/utils/createPersistStore.ts@@ -1,9 +1,9 @@-import { create } from "zustand";-import { combine, persist, createJSONStorage } from "zustand/middleware";-import { indexedDBStorage } from "./storage";-import lodash from "lodash";+import lodash from 'lodash'+import { create } from 'zustand'+import { combine, createJSONStorage, persist } from 'zustand/middleware'+import { indexedDBStorage } from './storage'-type Updater<T> = (updater: (value: T) => void) => void;+type Updater<T> = (updater: (value: T) => void) => voidtype SecondParam<T> = T extends (_f: infer _F,@@ -11,21 +11,21 @@ type SecondParam<T> = T extends (...args: infer _U) => any? S- : never;+ : never-type MakeUpdater<T> = {- lastUpdateTime: number;- _hasHydrated: boolean;+interface MakeUpdater<T> {+ lastUpdateTime: number+ _hasHydrated: boolean- markUpdate: () => void;- update: Updater<T>;- setHasHydrated: (state: boolean) => void;-};+ markUpdate: () => void+ update: Updater<T>+ setHasHydrated: (state: boolean) => void+}type SetStoreState<T> = (partial: T | Partial<T> | ((state: T) => T | Partial<T>),replace?: boolean | undefined,-) => void;+) => void/*** 创建一个数据持久化的 store@@ -42,12 +42,12 @@ export function createPersistStore<T extends object, M>() => M,persistOptions: SecondParam<typeof persist<T & M & MakeUpdater<T>>>,) {- persistOptions.storage = createJSONStorage(() => indexedDBStorage);- const oldOonRehydrateStorage = persistOptions?.onRehydrateStorage;+ persistOptions.storage = createJSONStorage(() => indexedDBStorage)+ const oldOonRehydrateStorage = persistOptions?.onRehydrateStoragepersistOptions.onRehydrateStorage = (state) => {- oldOonRehydrateStorage?.(state);- return () => state.setHasHydrated(true);- };+ oldOonRehydrateStorage?.(state)+ return () => state.setHasHydrated(true)+ }return create(persist(@@ -64,23 +64,23 @@ export function createPersistStore<T extends object, M>(markUpdate() {set({ lastUpdateTime: Date.now() } as Partial<T & M & MakeUpdater<T>- >);+ >)},update(updater) {- const state = lodash.cloneDeep(get());- updater(state);+ const state = lodash.cloneDeep(get())+ updater(state)set({...state,lastUpdateTime: Date.now(),- });+ })},setHasHydrated: (state: boolean) => {- set({ _hasHydrated: state } as Partial<T & M & MakeUpdater<T>>);+ set({ _hasHydrated: state } as Partial<T & M & MakeUpdater<T>>)},- } as M & MakeUpdater<T>;+ } as M & MakeUpdater<T>},),persistOptions as any,),- );+ )}diff --git a/project/web/src/utils/general.ts b/project/web/src/utils/general.tsindex 99190795..9924b300 100644--- a/project/web/src/utils/general.ts+++ b/project/web/src/utils/general.ts@@ -1,9 +1,9 @@-import { Metadata } from "next";-import { useTranslation } from "@/app/i18n";+import type { Metadata } from 'next'+import { useTranslation } from '@/app/i18n'export async function getPageTitle(name: string, lng: string) {- const { t } = await useTranslation(lng);- return `${name} —— ${t("title")}`;+ const { t } = await useTranslation(lng)+ return `${name} —— ${t('title')}`}/**@@ -16,16 +16,16 @@ export async function getMetadata(lng: string,): Promise<Metadata> {const title = await getPageTitle(- typeof props.title === "string" ? props.title : "",+ typeof props.title === 'string' ? props.title : '',lng,- );+ )return {...props,title,- referrer: "no-referrer",- };+ referrer: 'no-referrer',+ }}export function sleep(ms: number) {- return new Promise((resolve) => setTimeout(resolve, ms));+ return new Promise(resolve => setTimeout(resolve, ms))}diff --git a/project/web/src/utils/index.ts b/project/web/src/utils/index.tsindex 3c00b640..76b9cbe2 100644--- a/project/web/src/utils/index.ts+++ b/project/web/src/utils/index.ts@@ -1,42 +1,43 @@-import dayjs from "dayjs";-import { message } from "antd";+import { message } from 'antd'+import dayjs from 'dayjs'/*** 生成唯一ID*/export function generateUUID(): string {- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {- const r = (Math.random() * 16) | 0;- const v = c === "x" ? r : (r & 0x3) | 0x8;- return v.toString(16);- });+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {+ const r = (Math.random() * 16) | 0+ const v = c === 'x' ? r : (r & 0x3) | 0x8+ return v.toString(16)+ })}// 等待n毫秒export function sleep(ms: number) {- return new Promise((resolve) => setTimeout(resolve, ms));+ return new Promise(resolve => setTimeout(resolve, ms))}// 获取文件路径中的文件名和后缀-export const getFilePathName = (path: string) => {- if (!path)+export function getFilePathName(path: string) {+ if (!path) {return {- filename: "",- suffix: "",- };- const path1 = path.split("\\")[path.split("\\").length - 1];- const filename = path1.split("/")[path1.split("/").length - 1];+ filename: '',+ suffix: '',+ }+ }+ const path1 = path.split('\\')[path.split('\\').length - 1]+ const filename = path1.split('/')[path1.split('/').length - 1]return {filename,- suffix: filename.split(".")[filename.split(".").length - 1],- };-};+ suffix: filename.split('.')[filename.split('.').length - 1],+ }+}// 格式化时间export function formatTime(time: string | number | Date,- format: string = "YYYY-MM-DD HH:mm:ss",+ format: string = 'YYYY-MM-DD HH:mm:ss',) {- return dayjs(time).format(format);+ return dayjs(time).format(format)}/**@@ -46,13 +47,13 @@ export function formatTime(* @returns 格式化后的时间字符串*/export function formatSeconds(seconds: number): string {- const hours = Math.floor(seconds / 3600);- const minutes = Math.floor((seconds % 3600) / 60);- const secs = seconds % 60;+ const hours = Math.floor(seconds / 3600)+ const minutes = Math.floor((seconds % 3600) / 60)+ const secs = seconds % 60- const pad = (num: number) => num.toString().padStart(2, "0");+ const pad = (num: number) => num.toString().padStart(2, '0')- return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;+ return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`}/**@@ -61,69 +62,72 @@ export function formatSeconds(seconds: number): string {* @returns 如果数值超过1000返回'n千',超过10000返回'n万'*/export function describeNumber(value: number): string {- if (!value) return `${value ?? 0}`;+ if (!value)+ return `${value ?? 0}`if (value >= 10000) {- return `${(value / 10000).toFixed(2).replace(/\.?0+$/, "")}w`;- } else if (value >= 1000) {- return `${(value / 1000).toFixed(2).replace(/\.?0+$/, "")}k`;- } else {- return value.toString();+ return `${(value / 10000).toFixed(2).replace(/\.?0+$/, '')}w`+ }+ else if (value >= 1000) {+ return `${(value / 1000).toFixed(2).replace(/\.?0+$/, '')}k`+ }+ else {+ return value.toString()}}// 去除字符串中的话题export function parseTopicString(input: string): {- topics: string[];- cleanedString: string;+ topics: string[]+ cleanedString: string} {// 使用正则表达式提取字符串中的部分- const extractedParts = input.match(/#(\S+)/g) || [];+ const extractedParts = input.match(/#(\S+)/g) || []// 在原始输入中用空字符串替换提取的部分- let cleanedString = input;+ let cleanedString = inputextractedParts.forEach((part) => {- cleanedString = cleanedString.replace(part, "").trim();- });+ cleanedString = cleanedString.replace(part, '').trim()+ })// 创建提取的话题数组const topics = extractedParts.map((part) => {- const match = part.match(/#(\S+)/);- return match ? match[1] : "";- });+ const match = part.match(/#(\S+)/)+ return match ? match[1] : ''+ })- return { topics, cleanedString };+ return { topics, cleanedString }}// 敏感词检测-多余检测动画export async function sensitivityLoading() {- const key = generateUUID();+ const key = generateUUID()const msgs = [- "敏感词检测中",- "色情检测中",- "abuse检测中",- "广告法检测中",- "Error检测中",- ];+ '敏感词检测中',+ '色情检测中',+ 'abuse检测中',+ '广告法检测中',+ 'Error检测中',+ ]for (const msg of msgs) {message.open({key,- type: "loading",+ type: 'loading',content: `${msg} ...`,- });- await sleep(200);+ })+ await sleep(200)}- message.destroy(key);+ message.destroy(key)}// base64转Blobexport function dataURLToBlob(dataURL: string): Blob {- const [header, data] = dataURL.split(",");- const mime = header.match(/data:(.*?);base64/)?.[1] || "image/png";- const binary = atob(data);- const len = binary.length;- const u8 = new Uint8Array(len);- for (let i = 0; i < len; i++) u8[i] = binary.charCodeAt(i);- return new Blob([u8], { type: mime });+ const [header, data] = dataURL.split(',')+ const mime = header.match(/data:(.*?);base64/)?.[1] || 'image/png'+ const binary = atob(data)+ const len = binary.length+ const u8 = new Uint8Array(len)+ for (let i = 0; i < len; i++) u8[i] = binary.charCodeAt(i)+ return new Blob([u8], { type: mime })}diff --git a/project/web/src/utils/ipLocation.ts b/project/web/src/utils/ipLocation.tsindex 68d789d5..91eeec63 100644--- a/project/web/src/utils/ipLocation.ts+++ b/project/web/src/utils/ipLocation.ts@@ -4,80 +4,80 @@*/export interface IpLocationInfo {- ip: string;- location: string;- asn: string;- org: string;+ ip: string+ location: string+ asn: string+ org: string}/*** 获取IP地理位置信息* @returns Promise<IpLocationInfo>*/-export const getIpLocation = (): Promise<IpLocationInfo> => {+export function getIpLocation(): Promise<IpLocationInfo> {return new Promise((resolve, reject) => {// 创建全局回调函数const callbackName = `ipLocationCallback_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;-+// 定义回调函数(window as any)[callbackName] = (ip: string, location: string, asn: string, org: string) => {// 清理回调函数和script标签- delete (window as any)[callbackName];- const script = document.getElementById(`ip-location-script-${callbackName}`);+ delete (window as any)[callbackName]+ const script = document.getElementById(`ip-location-script-${callbackName}`)if (script) {- document.head.removeChild(script);+ document.head.removeChild(script)}-- resolve({ ip, location, asn, org });- };++ resolve({ ip, location, asn, org })+ }// 创建script标签- const script = document.createElement('script');- script.id = `ip-location-script-${callbackName}`;- script.src = `https://ping0.cc/geo/jsonp/${callbackName}`;+ const script = document.createElement('script')+ script.id = `ip-location-script-${callbackName}`+ script.src = `https://ping0.cc/geo/jsonp/${callbackName}`script.onerror = () => {// 清理回调函数- delete (window as any)[callbackName];- reject(new Error('获取IP地理位置信息失败'));- };+ delete (window as any)[callbackName]+ reject(new Error('获取IP地理位置信息失败'))+ }// 设置超时const timeout = setTimeout(() => {- delete (window as any)[callbackName];- const scriptElement = document.getElementById(`ip-location-script-${callbackName}`);+ delete (window as any)[callbackName]+ const scriptElement = document.getElementById(`ip-location-script-${callbackName}`)if (scriptElement) {- document.head.removeChild(scriptElement);+ document.head.removeChild(scriptElement)}- reject(new Error('获取IP地理位置信息超时'));- }, 10000);+ reject(new Error('获取IP地理位置信息超时'))+ }, 10000)// 监听加载完成script.onload = () => {- clearTimeout(timeout);- };+ clearTimeout(timeout)+ }// 添加到页面- document.head.appendChild(script);- });-};+ document.head.appendChild(script)+ })+}/*** 从位置信息中提取国家* @param location 位置信息字符串* @returns 国家名称*/-export const extractCountry = (location: string): string => {+export function extractCountry(location: string): string {// 位置信息通常格式为: "国家 省份 城市" 或 "国家"- const parts = location.split(' ');- return parts[0] || location;-};+ const parts = location.split(' ')+ return parts[0] || location+}/*** 格式化地理位置信息* @param info IP地理位置信息* @returns 格式化后的字符串*/-export const formatLocationInfo = (info: IpLocationInfo): string => {- const country = extractCountry(info.location);- return `${country} | ${info.ip}`;-};+export function formatLocationInfo(info: IpLocationInfo): string {+ const country = extractCountry(info.location)+ return `${country} | ${info.ip}`+}diff --git a/project/web/src/utils/oss.ts b/project/web/src/utils/oss.tsindex 08254651..2d27b188 100644--- a/project/web/src/utils/oss.ts+++ b/project/web/src/utils/oss.ts@@ -1,6 +1,8 @@// 获取完整的OSS URL-export const getOssUrl = (path: string) => {- if (!path) return "";- if (path.startsWith("http") || path.startsWith("https") || path.startsWith("ossProxy")) return path;- return `${process.env.NEXT_PUBLIC_OSS_URL_PROXY}${path}`;-};+export function getOssUrl(path: string) {+ if (!path)+ return ''+ if (path.startsWith('http') || path.startsWith('https') || path.startsWith('ossProxy'))+ return path+ return `${process.env.NEXT_PUBLIC_OSS_URL_PROXY}${path}`+}diff --git a/project/web/src/utils/otherRequest.ts b/project/web/src/utils/otherRequest.tsindex ba476db7..2648b976 100644--- a/project/web/src/utils/otherRequest.ts+++ b/project/web/src/utils/otherRequest.ts@@ -1,61 +1,61 @@-import FetchService from "@/utils/FetchService/FetchService";-import { RequestParams } from "@/utils/FetchService/types";-import { request } from "@/utils/request";+import type { RequestParams } from '@/utils/FetchService/types'+import FetchService from '@/utils/FetchService/FetchService'+import { request } from '@/utils/request'class OtherRequest {- fetchService;+ fetchServiceconstructor(baseURL: string) {this.fetchService = new FetchService({baseURL,requestInterceptor(requestParams) {- return requestParams;+ return requestParams},responseInterceptor(response) {- return response;+ return response},- });+ })}async request<T = any>(params: RequestParams) {- const res = await this.fetchService.request(params);- return (await res.json()) as T;+ const res = await this.fetchService.request(params)+ return (await res.json()) as T}get<T>(url: string, data?: any) {return request<T>({url,params: data,- method: "GET",- });+ method: 'GET',+ })}post<T>(url: string, data?: any) {return request<T>({url,- data: data,- method: "POST",- });+ data,+ method: 'POST',+ })}put<T>(url: string, data?: any) {return request<T>({url,- data: data,- method: "PUT",- });+ data,+ method: 'PUT',+ })}delete<T>(url: string, data?: any) {return request<T>({url,- data: data,- method: "DELETE",- });+ data,+ method: 'DELETE',+ })}}-const requestPlatapi = new OtherRequest("");+const requestPlatapi = new OtherRequest('')export async function requestPlatApi<T = any>(params: RequestParams) {- return await requestPlatapi.request(params);+ return await requestPlatapi.request(params)}diff --git a/project/web/src/utils/regulars.ts b/project/web/src/utils/regulars.tsindex 9120920c..fc6f7a73 100644--- a/project/web/src/utils/regulars.ts+++ b/project/web/src/utils/regulars.ts@@ -1,10 +1,10 @@// 身份证号校验正则-export const idNumberReg =- /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/;+export const idNumberReg+ = /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))([\dX])$/i// 手机号正则验证-export const phoneReg = /^(?:(?:\+|00)86)?1\d{10}$/;+export const phoneReg = /^(?:(?:\+|00)86)?1\d{10}$/// 邮箱验证-export const emailReg =- /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;+export const emailReg+ = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\])|(([a-z\-0-9]+\.)+[a-z]{2,}))$/idiff --git a/project/web/src/utils/request.ts b/project/web/src/utils/request.tsindex 4d07c6f8..7893ca7f 100644--- a/project/web/src/utils/request.ts+++ b/project/web/src/utils/request.ts@@ -1,94 +1,95 @@-import FetchService from "@/utils/FetchService/FetchService";-import { RequestParams } from "@/utils/FetchService/types";-import { useUserStore } from "@/store/user";-import { message } from "antd";+import type { RequestParams } from '@/utils/FetchService/types'+import { message } from 'antd'+import { useUserStore } from '@/store/user'+import FetchService from '@/utils/FetchService/FetchService'-type ResponseType<T> = {- code: string | number;- data: T;- message: string;- url: string;-};+interface ResponseType<T> {+ code: string | number+ data: T+ message: string+ url: string+}type RequestParamsWithSilent = RequestParams & {- silent?: boolean; // 是否静默处理错误,不显示提示-};+ silent?: boolean // 是否静默处理错误,不显示提示+}const fetchService = new FetchService({baseURL: `${process.env.NEXT_PUBLIC_API_URL}/`,requestInterceptor(requestParams) {- const token = useUserStore.getState().token;+ const token = useUserStore.getState().tokenrequestParams.headers = {- ...(requestParams["headers"] || {}),- Authorization: token ? `Bearer ${token}` : "",- };+ ...(requestParams.headers || {}),+ Authorization: token ? `Bearer ${token}` : '',+ }// 添加语言头- if (typeof window !== "undefined") {- const lng = useUserStore.getState().lang;+ if (typeof window !== 'undefined') {+ const lng = useUserStore.getState().langrequestParams.headers = {...requestParams.headers,- "Accept-Language": lng,- };+ 'Accept-Language': lng,+ }}- return requestParams;+ return requestParams},responseInterceptor(response) {- return response;+ return response},-});+})export async function request<T>(params: RequestParamsWithSilent) {try {- const res = await fetchService.request(params);- const data: ResponseType<T> = await res.json();+ const res = await fetchService.request(params)+ const data: ResponseType<T> = await res.json()- const lang = useUserStore.getState().lang || "zh-CN";- const isZh = (lang || "").toLowerCase().startsWith("zh");+ const lang = useUserStore.getState().lang || 'zh-CN'+ const isZh = (lang || '').toLowerCase().startsWith('zh')const i18nText = {networkBusy: isZh- ? "网络繁忙,请稍后重试!"- : "Network busy, please try again later!",+ ? '网络繁忙,请稍后重试!'+ : 'Network busy, please try again later!',networkError: isZh- ? "网络异常,请稍后重试!"- : "Network error, please try again later!",- contact: isZh ? "如需帮助请联系客服:" : "Need help? Contact support:",- };+ ? '网络异常,请稍后重试!'+ : 'Network error, please try again later!',+ contact: isZh ? '如需帮助请联系客服:' : 'Need help? Contact support:',+ }// 未登录拦截if (data.code === 401 && !useUserStore.getState().token) {- return null;+ return null}// 已登录、但是登录过期if (data.code === 401) {- useUserStore.getState().logout();+ useUserStore.getState().logout()}if (data.code !== 0) {- if (!params.silent && typeof window !== "undefined") {+ if (!params.silent && typeof window !== 'undefined') {message.warning({content: `${data.message || i18nText.networkBusy} ${i18nText.contact} https://t.me/harryyyy2025`,- key: "apiErrorMessage",+ key: 'apiErrorMessage',duration: 6,- });+ })}- return null;+ return null}- return data;- } catch (e) {- console.warn(e);- if (!params.silent && typeof window !== "undefined") {+ return data+ }+ catch (e) {+ console.warn(e)+ if (!params.silent && typeof window !== 'undefined') {message.error({- content: `${(useUserStore.getState().lang || "zh-CN").toLowerCase().startsWith("zh") ? "网络异常,请稍后重试!" : "Network error, please try again later!"} ${(useUserStore.getState().lang || "zh-CN").toLowerCase().startsWith("zh") ? "如需帮助请联系客服:" : "Need help? Contact support:"} https://t.me/harryyyy2025`,- key: "apiErrorMessage",+ content: `${(useUserStore.getState().lang || 'zh-CN').toLowerCase().startsWith('zh') ? '网络异常,请稍后重试!' : 'Network error, please try again later!'} ${(useUserStore.getState().lang || 'zh-CN').toLowerCase().startsWith('zh') ? '如需帮助请联系客服:' : 'Need help? Contact support:'} https://t.me/harryyyy2025`,+ key: 'apiErrorMessage',duration: 6,- });+ })}- return null;+ return null}}@@ -97,32 +98,32 @@ export default {return request<T>({url,params: data,- method: "GET",+ method: 'GET',silent,- });+ })},post<T>(url: string, data?: any, silent?: boolean) {return request<T>({url,- data: data,- method: "POST",+ data,+ method: 'POST',silent,- });+ })},put<T>(url: string, data?: any, silent?: boolean) {return request<T>({url,- data: data,- method: "PUT",+ data,+ method: 'PUT',silent,- });+ })},delete<T>(url: string, data?: any, silent?: boolean) {return request<T>({url,- data: data,- method: "DELETE",+ data,+ method: 'DELETE',silent,- });+ })},-};+}diff --git a/project/web/src/utils/storage.ts b/project/web/src/utils/storage.tsindex a1d7f797..d2a081d5 100644--- a/project/web/src/utils/storage.ts+++ b/project/web/src/utils/storage.ts@@ -1,19 +1,22 @@-import { StateStorage } from "zustand/middleware";+import type { StateStorage } from 'zustand/middleware'class IndexedDBStorage implements StateStorage {public async getItem(name: string): Promise<string | null> {- if (typeof window === "undefined") return null;- return localStorage.getItem(name);+ if (typeof window === 'undefined')+ return null+ return localStorage.getItem(name)}public async setItem(name: string, value: string): Promise<void> {- if (typeof window === "undefined") return;- localStorage.setItem(name, value);+ if (typeof window === 'undefined')+ return+ localStorage.setItem(name, value)}public async removeItem(name: string): Promise<void> {- if (typeof window === "undefined") return;- localStorage.removeItem(name);+ if (typeof window === 'undefined')+ return+ localStorage.removeItem(name)}public async clear(): Promise<void> {@@ -25,4 +28,4 @@ class IndexedDBStorage implements StateStorage {}}-export const indexedDBStorage = new IndexedDBStorage();+export const indexedDBStorage = new IndexedDBStorage()