feat: 图文草稿箱迁移

This commit is contained in:
hw
2025-11-05 17:01:42 +08:00
parent c59e03073f
commit 6a3e8173e0
19 changed files with 2293 additions and 37 deletions

View File

@@ -4,9 +4,9 @@ VITE_PORT=5666
VITE_BASE=/ VITE_BASE=/
# 请求路径 # 请求路径
VITE_BASE_URL=http://127.0.0.1:48080 VITE_BASE_URL=http://47.103.66.220:48080
# 接口地址 # 接口地址
VITE_GLOB_API_URL=/admin-api VITE_GLOB_API_URL=http://47.103.66.220:48080/admin-api
# 文件上传类型server - 后端上传, client - 前端直连上传仅支持S3服务 # 文件上传类型server - 后端上传, client - 前端直连上传仅支持S3服务
VITE_UPLOAD_TYPE=server VITE_UPLOAD_TYPE=server
# 是否打开 devtoolstrue 为打开false 为关闭 # 是否打开 devtoolstrue 为打开false 为关闭

View File

@@ -35,9 +35,13 @@ export function getDraftPage(params: PageParam) {
/** 创建草稿 */ /** 创建草稿 */
export function createDraft(accountId: number, articles: MpDraftApi.Article[]) { export function createDraft(accountId: number, articles: MpDraftApi.Article[]) {
return requestClient.post('/mp/draft/create', articles, { return requestClient.post(
params: { accountId }, '/mp/draft/create',
}); { articles },
{
params: { accountId },
},
);
} }
/** 更新草稿 */ /** 更新草稿 */
@@ -46,9 +50,13 @@ export function updateDraft(
mediaId: string, mediaId: string,
articles: MpDraftApi.Article[], articles: MpDraftApi.Article[],
) { ) {
return requestClient.put('/mp/draft/update', articles, { return requestClient.put(
params: { accountId, mediaId }, '/mp/draft/update',
}); { articles },
{
params: { accountId, mediaId },
},
);
} }
/** 删除草稿 */ /** 删除草稿 */

View File

@@ -0,0 +1,41 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { markRaw } from 'vue';
import WxAccountSelect from '#/views/mp/modules/wx-account-select/main.vue';
/** 获取表格列配置 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
field: 'content',
title: '图文内容',
minWidth: 300,
slots: { default: 'content' },
},
{
field: 'updateTime',
title: '更新时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{
title: '操作',
width: 200,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'accountId',
label: '公众号',
component: markRaw(WxAccountSelect),
},
];
}

View File

@@ -1,29 +1,316 @@
<script lang="ts" setup> <script lang="ts" setup>
import { DocAlert, Page } from '@vben/common-ui'; import type { Article } from './modules/types';
import { Button } from 'ant-design-vue'; import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { nextTick, onMounted, provide, ref, watch } from 'vue';
import { confirm, DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { message } from 'ant-design-vue';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import * as MpDraftApi from '#/api/mp/draft';
import * as MpFreePublishApi from '#/api/mp/freePublish';
import { createEmptyNewsItem } from '#/views/mp/draft/modules/types';
import { useGridColumns, useGridFormSchema } from './data';
import DraftTableCell from './modules/draft-table.vue';
import Form from './modules/form.vue';
defineOptions({ name: 'MpDraft' });
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
submitOnChange: true,
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
// 更新 accountId
if (formValues?.accountId) {
accountId.value = formValues.accountId;
}
const drafts = await MpDraftApi.getDraftPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
// 处理 API 返回的数据,兼容不同的数据结构
const formattedList: Article[] = drafts.list.map((draft: any) => {
// 如果已经是 content.newsItem 格式,直接使用
if (draft.content?.newsItem) {
const newsItem = draft.content.newsItem.map((item: any) => ({
...item,
picUrl: item.thumbUrl || item.picUrl,
}));
return {
mediaId: draft.mediaId,
content: {
newsItem,
},
updateTime:
draft.updateTime ||
(draft.createTime
? new Date(draft.createTime).getTime()
: Date.now()),
};
}
// 如果是 articles 格式,转换为 content.newsItem 格式
if (draft.articles) {
const newsItem = draft.articles.map((article: any) => ({
...article,
thumbUrl: article.thumbUrl || article.thumbMediaId,
picUrl: article.thumbUrl || article.thumbMediaId,
}));
return {
mediaId: draft.mediaId,
content: {
newsItem,
},
updateTime:
draft.updateTime ||
(draft.createTime
? new Date(draft.createTime).getTime()
: Date.now()),
};
}
// 默认返回空结构
return {
mediaId: draft.mediaId || '',
content: {
newsItem: [],
},
updateTime: draft.updateTime || Date.now(),
};
});
return {
page: {
total: drafts.total,
},
result: formattedList,
};
},
},
autoLoad: false,
},
rowConfig: {
keyField: 'mediaId',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<Article>,
});
// 提供 accountId 给子组件
const accountId = ref<number>(-1);
// 监听表单提交,更新 accountId
watch(
() => gridApi.formApi?.getLatestSubmissionValues?.()?.accountId,
(newAccountId) => {
if (newAccountId !== undefined) {
accountId.value = newAccountId;
}
},
);
provide('accountId', accountId);
/** 新增按钮操作 */
async function handleCreate() {
const formValues = await gridApi.formApi.getValues();
const accountId = formValues.accountId;
if (!accountId || accountId === -1) {
message.warning('请先选择公众号');
return;
}
formModalApi
.setData({
isCreating: true,
accountId,
newsList: [createEmptyNewsItem()],
})
.open();
}
/** 修改按钮操作 */
async function handleEdit(row: Article) {
const formValues = await gridApi.formApi.getValues();
const accountId = formValues.accountId;
if (!accountId || accountId === -1) {
message.warning('请先选择公众号');
return;
}
formModalApi
.setData({
isCreating: false,
accountId,
mediaId: row.mediaId,
newsList: structuredClone(row.content.newsItem),
})
.open();
}
/** 发布按钮操作 */
async function handlePublish(row: Article) {
const formValues = await gridApi.formApi.getValues();
const accountId = formValues.accountId;
if (!accountId || accountId === -1) {
message.warning('请先选择公众号');
return;
}
const content =
'你正在通过发布的方式发表内容。 发布不占用群发次数,一天可多次发布。' +
'已发布内容不会推送给用户,也不会展示在公众号主页中。 ' +
'发布后,你可以前往发表记录获取链接,也可以将发布内容添加到自定义菜单、自动回复、话题和页面模板中。';
try {
await confirm(content);
const hideLoading = message.loading({
content: '发布中...',
duration: 0,
});
try {
await MpFreePublishApi.submitFreePublish(accountId, row.mediaId);
message.success('发布成功');
await gridApi.query();
} finally {
hideLoading();
}
} catch {
//
}
}
/** 删除按钮操作 */
async function handleDelete(row: Article) {
const formValues = await gridApi.formApi.getValues();
const accountId = formValues.accountId;
if (!accountId || accountId === -1) {
message.warning('请先选择公众号');
return;
}
try {
await confirm('此操作将永久删除该草稿, 是否继续?');
const hideLoading = message.loading({
content: '删除中...',
duration: 0,
});
try {
await MpDraftApi.deleteDraft(accountId, row.mediaId);
message.success('删除成功');
await gridApi.query();
} finally {
hideLoading();
}
} catch {
//
}
}
// 页面挂载后,等待表单初始化完成再加载数据
onMounted(async () => {
await nextTick();
if (gridApi.formApi) {
const formValues = await gridApi.formApi.getValues();
if (formValues.accountId) {
accountId.value = formValues.accountId;
gridApi.formApi.setLatestSubmissionValues(formValues);
await gridApi.query();
}
}
});
</script> </script>
<template> <template>
<Page> <Page auto-content-height>
<DocAlert title="公众号图文" url="https://doc.iocoder.cn/mp/article/" /> <DocAlert title="公众号图文" url="https://doc.iocoder.cn/mp/article/" />
<Button
danger <FormModal
type="link" @success="
target="_blank" () => {
href="https://github.com/yudaocode/yudao-ui-admin-vue3" gridApi.query();
> }
该功能支持 Vue3 + element-plus 版本 "
</Button> />
<br />
<Button <Grid table-title="草稿列表">
type="link" <template #toolbar-tools>
target="_blank" <TableAction
href="https://github.com/yudaocode/yudao-ui-admin-vue3/blob/master/src/views/mp/draft/index" :actions="[
> {
可参考 label: '新增',
https://github.com/yudaocode/yudao-ui-admin-vue3/blob/master/src/views/mp/draft/index type: 'primary',
代码pull request 贡献给我们 icon: ACTION_ICON.ADD,
</Button> auth: ['mp:draft:create'],
onClick: handleCreate,
},
]"
/>
</template>
<template #content="{ row }">
<DraftTableCell :row="row" />
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: '发布',
type: 'link',
icon: ACTION_ICON.UPLOAD,
auth: ['mp:free-publish:submit'],
onClick: handlePublish.bind(null, row),
},
{
label: '编辑',
type: 'link',
icon: ACTION_ICON.EDIT,
auth: ['mp:draft:update'],
onClick: handleEdit.bind(null, row),
},
{
label: '删除',
type: 'link',
danger: true,
icon: ACTION_ICON.DELETE,
auth: ['mp:draft:delete'],
popConfirm: {
title: '是否确认删除此数据?',
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page> </Page>
</template> </template>
<style lang="scss" scoped>
:deep(.vxe-table--body-wrapper) {
.vxe-table--body {
.vxe-body--column {
.vxe-cell {
padding: 0;
}
}
}
}
</style>

View File

@@ -0,0 +1,189 @@
<script lang="ts" setup>
import type { UploadFile } from 'ant-design-vue';
import type { NewsItem } from './types';
import { computed, inject, reactive, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { useAccessStore } from '@vben/stores';
import { Button, Image, message, Modal, Upload } from 'ant-design-vue';
import { UploadType, useBeforeUpload } from '#/utils/useUpload';
import WxMaterialSelect from '#/views/mp/modules/wx-material-select';
// 设置上传的请求头部
const props = defineProps<{
isFirst: boolean;
modelValue: NewsItem;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', v: NewsItem): void;
}>();
const UPLOAD_URL = `${import.meta.env.VITE_BASE_URL}/admin-api/mp/material/upload-permanent`; // 上传永久素材的地址
const HEADERS = { Authorization: `Bearer ${useAccessStore().accessToken}` };
const newsItem = computed<NewsItem>({
get() {
return props.modelValue;
},
set(val) {
emit('update:modelValue', val);
},
});
const accountId = inject<number>('accountId');
const showImageDialog = ref(false);
const fileList = ref<UploadFile[]>([]);
interface UploadData {
type: UploadType;
accountId: number;
}
const uploadData: UploadData = reactive({
type: UploadType.Image,
accountId: accountId!,
});
/** 素材选择完成事件*/
function onMaterialSelected(item: any) {
showImageDialog.value = false;
newsItem.value.thumbMediaId = item.mediaId;
newsItem.value.thumbUrl = item.url;
}
const onBeforeUpload = (file: UploadFile) =>
useBeforeUpload(UploadType.Image, 2)(file as any);
function onUploadChange(info: any) {
if (info.file.status === 'done') {
onUploadSuccess(info.file.response || info.file);
} else if (info.file.status === 'error') {
onUploadError(info.file.error || new Error('上传失败'));
}
}
function onUploadSuccess(res: any) {
if (res.code !== 0) {
message.error(`上传出错:${res.msg}`);
return false;
}
// 重置上传文件的表单
fileList.value = [];
// 设置草稿的封面字段
newsItem.value.thumbMediaId = res.data.mediaId;
newsItem.value.thumbUrl = res.data.url;
}
function onUploadError(err: Error) {
message.error(`上传失败: ${err.message}`);
}
</script>
<template>
<div>
<p>封面:</p>
<div class="thumb-div">
<Image
v-if="newsItem.thumbUrl"
style="width: 300px; max-height: 300px"
:src="newsItem.thumbUrl"
:preview="false"
/>
<IconifyIcon
v-else
icon="ep:plus"
class="avatar-uploader-icon"
:class="isFirst ? 'avatar' : 'avatar1'"
/>
<div class="thumb-but">
<div class="flex items-center justify-center">
<Upload
:action="UPLOAD_URL"
:headers="HEADERS"
:file-list="fileList"
:data="{ ...uploadData }"
:before-upload="onBeforeUpload"
@change="onUploadChange"
>
<template #default>
<Button size="small" type="primary">本地上传</Button>
</template>
</Upload>
<Button
size="small"
type="primary"
@click="showImageDialog = true"
style="margin-left: 5px"
>
素材库选择
</Button>
</div>
<div class="upload-tip">
支持 bmp/png/jpeg/jpg/gif 格式大小不超过 2M
</div>
</div>
<Modal
title="选择图片"
v-model:open="showImageDialog"
width="80%"
destroy-on-close
>
<WxMaterialSelect
type="image"
:account-id="accountId!"
@select-material="onMaterialSelected"
/>
</Modal>
</div>
</div>
</template>
<style lang="scss" scoped>
.upload-tip {
margin-left: 5px;
margin-top: 5px;
font-size: 12px;
color: #999;
}
.thumb-div {
display: inline-block;
width: 100%;
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
.avatar-uploader-icon {
width: 120px;
height: 120px;
font-size: 28px;
line-height: 120px;
color: #8c939d;
text-align: center;
border: 1px solid #d9d9d9;
}
.avatar {
width: 230px;
height: 120px;
}
.avatar1 {
width: 120px;
height: 120px;
}
.thumb-but {
margin: 5px;
}
}
</style>

View File

@@ -0,0 +1,25 @@
<script lang="ts" setup>
import type { Article } from './types';
import WxNews from '#/views/mp/modules/wx-news/main.vue';
defineOptions({ name: 'DraftTableCell' });
const props = defineProps<{
row: Article;
}>();
</script>
<template>
<div class="draft-content">
<div v-if="props.row.content && props.row.content.newsItem">
<WxNews :articles="props.row.content.newsItem" />
</div>
</div>
</template>
<style lang="scss" scoped>
.draft-content {
padding: 10px;
}
</style>

View File

@@ -0,0 +1,103 @@
<script lang="ts" setup>
import type { NewsItem } from './types';
import { computed, ref } from 'vue';
import { confirm, useVbenModal } from '@vben/common-ui';
import { message, Spin } from 'ant-design-vue';
import * as MpDraftApi from '#/api/mp/draft';
import NewsForm from './news-form.vue';
const emit = defineEmits(['success']);
const formData = ref<{
accountId: number;
isCreating: boolean;
mediaId?: string;
newsList?: NewsItem[];
}>();
const newsList = ref<NewsItem[]>([]);
const isSubmitting = ref(false);
const isSaved = ref(false);
const getTitle = computed(() => {
return formData.value?.isCreating ? '新建图文' : '修改图文';
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
if (!formData.value) {
return;
}
isSubmitting.value = true;
modalApi.lock();
try {
if (formData.value.isCreating) {
await MpDraftApi.createDraft(formData.value.accountId, newsList.value);
message.success('新增成功');
} else if (formData.value.mediaId) {
await MpDraftApi.updateDraft(
formData.value.accountId,
formData.value.mediaId,
newsList.value,
);
message.success('更新成功');
}
isSaved.value = true;
await modalApi.close();
emit('success');
} finally {
isSubmitting.value = false;
modalApi.unlock();
}
},
async onBeforeClose() {
// 如果已经成功保存,直接关闭,不显示提示
if (isSaved.value) {
return true;
}
try {
await confirm('修改内容可能还未保存,确定关闭吗?');
return true;
} catch {
return false;
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
newsList.value = [];
isSaved.value = false;
return;
}
isSaved.value = false;
const data = modalApi.getData<{
accountId: number;
isCreating: boolean;
mediaId?: string;
newsList?: NewsItem[];
}>();
if (!data) {
return;
}
formData.value = data;
newsList.value = data.newsList || [];
},
});
</script>
<template>
<Modal :title="getTitle" class="w-4/5" destroy-on-close>
<Spin :spinning="isSubmitting">
<NewsForm
v-if="formData"
v-model="newsList"
:is-creating="formData.isCreating"
/>
</Spin>
</Modal>
</template>

View File

@@ -0,0 +1,341 @@
<script lang="ts" setup>
import type { NewsItem } from './types';
import { computed, ref } from 'vue';
import { confirm } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
import { Button, Col, Input, Layout, Row, Textarea } from 'ant-design-vue';
import { Tinymce as RichTextarea } from '#/components/tinymce';
import CoverSelect from './cover-select.vue';
import { createEmptyNewsItem } from './types';
defineOptions({ name: 'NewsForm' });
const props = defineProps<{
isCreating: boolean;
modelValue: NewsItem[] | null;
}>();
// v-model=newsList
const emit = defineEmits<{
(e: 'update:modelValue', v: NewsItem[]): void;
}>();
const newsList = computed<NewsItem[]>({
get() {
return props.modelValue === null
? [createEmptyNewsItem()]
: props.modelValue;
},
set(val) {
emit('update:modelValue', val);
},
});
const activeNewsIndex = ref(0);
const activeNewsItem = computed(() => {
const item = newsList.value[activeNewsIndex.value];
if (!item) {
return createEmptyNewsItem();
}
return item;
});
// 将图文向下移动
function moveDownNews(index: number) {
const current = newsList.value[index];
const next = newsList.value[index + 1];
if (current && next) {
newsList.value[index] = next;
newsList.value[index + 1] = current;
activeNewsIndex.value = index + 1;
}
}
// 将图文向上移动
function moveUpNews(index: number) {
const current = newsList.value[index];
const prev = newsList.value[index - 1];
if (current && prev) {
newsList.value[index] = prev;
newsList.value[index - 1] = current;
activeNewsIndex.value = index - 1;
}
}
// 删除指定 index 的图文
async function removeNews(index: number) {
try {
await confirm('确定删除该图文吗?');
newsList.value.splice(index, 1);
if (activeNewsIndex.value === index) {
activeNewsIndex.value = 0;
}
} catch {
// empty
}
}
// 添加一个图文
function plusNews() {
newsList.value.push(createEmptyNewsItem());
activeNewsIndex.value = newsList.value.length - 1;
}
</script>
<template>
<Layout>
<Layout.Sider width="40%" theme="light">
<div class="select-item">
<div v-for="(news, index) in newsList" :key="index">
<div
class="news-main father"
v-if="index === 0"
:class="{ activeAddNews: activeNewsIndex === index }"
@click="activeNewsIndex = index"
>
<div class="news-content">
<img class="material-img" :src="news.thumbUrl" />
<div class="news-content-title">{{ news.title }}</div>
</div>
<div class="child" v-if="newsList.length > 1">
<Button
type="default"
shape="circle"
size="small"
@click="() => moveDownNews(index)"
>
<IconifyIcon icon="ep:arrow-down-bold" />
</Button>
<Button
v-if="isCreating"
type="primary"
danger
shape="circle"
size="small"
@click="() => removeNews(index)"
>
<IconifyIcon icon="ep:delete" />
</Button>
</div>
</div>
<div
class="news-main-item father"
v-if="index > 0"
:class="{ activeAddNews: activeNewsIndex === index }"
@click="activeNewsIndex = index"
>
<div class="news-content-item">
<div class="news-content-item-title">{{ news.title }}</div>
<div class="news-content-item-img">
<img class="material-img" :src="news.thumbUrl" width="100%" />
</div>
</div>
<div class="child">
<Button
v-if="newsList.length > index + 1"
shape="circle"
type="default"
size="small"
@click="() => moveDownNews(index)"
>
<IconifyIcon icon="ep:arrow-down-bold" />
</Button>
<Button
v-if="index > 0"
type="default"
shape="circle"
size="small"
@click="() => moveUpNews(index)"
>
<IconifyIcon icon="ep:arrow-up-bold" />
</Button>
<Button
v-if="isCreating"
type="primary"
danger
size="small"
shape="circle"
@click="() => removeNews(index)"
>
<IconifyIcon icon="ep:delete" />
</Button>
</div>
</div>
</div>
<Row justify="center" class="ope-row">
<Button
type="primary"
shape="circle"
@click="plusNews"
v-if="newsList.length < 8 && isCreating"
>
<IconifyIcon icon="ep:plus" />
</Button>
</Row>
</div>
</Layout.Sider>
<Layout.Content :style="{ backgroundColor: '#fff' }">
<div v-if="newsList.length > 0 && activeNewsItem">
<!-- 标题作者原文地址 -->
<Row :gutter="20">
<Col :span="24">
<Input
v-model:value="activeNewsItem.title"
placeholder="请输入标题(必填)"
/>
</Col>
<Col :span="24" style="margin-top: 5px">
<Input
v-model:value="activeNewsItem.author"
placeholder="请输入作者"
/>
</Col>
<Col :span="24" style="margin-top: 5px">
<Input
v-model:value="activeNewsItem.contentSourceUrl"
placeholder="请输入原文地址"
/>
</Col>
</Row>
<!-- 封面和摘要 -->
<Row :gutter="20">
<Col :span="12">
<CoverSelect
v-model="activeNewsItem"
:is-first="activeNewsIndex === 0"
/>
</Col>
<Col :span="12">
<p>摘要:</p>
<Textarea
:rows="8"
v-model:value="activeNewsItem.digest"
placeholder="请输入摘要"
class="digest"
:maxlength="120"
:show-count="true"
/>
</Col>
</Row>
<!--富文本编辑器组件-->
<Row>
<Col :span="24">
<RichTextarea v-model="activeNewsItem.content" />
</Col>
</Row>
</div>
</Layout.Content>
</Layout>
</template>
<style lang="scss" scoped>
.ope-row {
padding-top: 5px;
margin-top: 5px;
text-align: center;
border-top: 1px solid #eaeaea;
}
:deep(.ant-row) {
margin-bottom: 20px;
}
:deep(.ant-row:last-child) {
margin-bottom: 0;
}
.digest {
display: inline-block;
width: 100%;
vertical-align: top;
}
/* 新增图文 */
.news-main {
width: 100%;
height: 120px;
margin: auto;
background-color: #fff;
}
.news-content {
position: relative;
width: 100%;
height: 120px;
background-color: #acadae;
}
.news-content-title {
position: absolute;
bottom: 0;
left: 0;
display: inline-block;
width: 98%;
height: 25px;
padding: 1%;
overflow: hidden;
font-size: 15px;
color: #fff;
text-overflow: ellipsis;
white-space: nowrap;
background-color: black;
opacity: 0.65;
}
.news-main-item {
width: 100%;
padding: 5px 0;
margin: auto;
background-color: #fff;
border-top: 1px solid #eaeaea;
}
.news-content-item {
position: relative;
margin-left: -3px;
}
.news-content-item-title {
display: inline-block;
width: 70%;
font-size: 12px;
}
.news-content-item-img {
display: inline-block;
width: 25%;
background-color: #acadae;
}
.select-item {
width: 60%;
padding: 10px;
margin: 0 auto 10px;
border: 1px solid #eaeaea;
.activeAddNews {
border: 5px solid #2bb673;
}
}
.father .child {
position: relative;
bottom: 25px;
display: none;
text-align: center;
}
.father:hover .child {
display: block;
}
.material-img {
width: 100%;
height: 100%;
}
</style>

View File

@@ -0,0 +1,41 @@
interface NewsItem {
title: string;
thumbMediaId: string;
author: string;
digest: string;
showCoverPic: number;
content: string;
contentSourceUrl: string;
needOpenComment: number;
onlyFansCanComment: number;
thumbUrl: string;
picUrl?: string; // 用于预览封面
}
interface NewsItemList {
newsItem: NewsItem[];
}
interface Article {
mediaId: string;
content: NewsItemList;
updateTime: number;
}
const createEmptyNewsItem = (): NewsItem => {
return {
title: '',
thumbMediaId: '',
author: '',
digest: '',
showCoverPic: 0,
content: '',
contentSourceUrl: '',
needOpenComment: 0,
onlyFansCanComment: 0,
thumbUrl: '',
};
};
export type { Article, NewsItem, NewsItemList };
export { createEmptyNewsItem };

View File

@@ -4,9 +4,11 @@ VITE_PORT=5777
VITE_BASE=/ VITE_BASE=/
# 请求路径 # 请求路径
VITE_BASE_URL=http://127.0.0.1:48080 VITE_BASE_URL=http://47.103.66.220:48080
# VITE_BASE_URL=http://192.168.1.49:48080
# 接口地址 # 接口地址
VITE_GLOB_API_URL=/admin-api VITE_GLOB_API_URL=http://47.103.66.220:48080/admin-api
# VITE_GLOB_API_URL=http://192.168.1.49:48080/admin-api
# 文件上传类型server - 后端上传, client - 前端直连上传仅支持S3服务 # 文件上传类型server - 后端上传, client - 前端直连上传仅支持S3服务
VITE_UPLOAD_TYPE=server VITE_UPLOAD_TYPE=server
# 是否打开 devtoolstrue 为打开false 为关闭 # 是否打开 devtoolstrue 为打开false 为关闭

View File

@@ -35,9 +35,13 @@ export function getDraftPage(params: PageParam) {
/** 创建草稿 */ /** 创建草稿 */
export function createDraft(accountId: number, articles: MpDraftApi.Article[]) { export function createDraft(accountId: number, articles: MpDraftApi.Article[]) {
return requestClient.post('/mp/draft/create', articles, { return requestClient.post(
params: { accountId }, '/mp/draft/create',
}); { articles },
{
params: { accountId },
},
);
} }
/** 更新草稿 */ /** 更新草稿 */
@@ -46,9 +50,13 @@ export function updateDraft(
mediaId: string, mediaId: string,
articles: MpDraftApi.Article[], articles: MpDraftApi.Article[],
) { ) {
return requestClient.put('/mp/draft/update', articles, { return requestClient.put(
params: { accountId, mediaId }, '/mp/draft/update',
}); { articles },
{
params: { accountId, mediaId },
},
);
} }
/** 删除草稿 */ /** 删除草稿 */

View File

@@ -0,0 +1,41 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { markRaw } from 'vue';
import WxAccountSelect from '#/views/mp/modules/wx-account-select/main.vue';
/** 获取表格列配置 */
export function useGridColumns(): VxeTableGridOptions['columns'] {
return [
{
field: 'content',
title: '图文内容',
minWidth: 300,
slots: { default: 'content' },
},
{
field: 'updateTime',
title: '更新时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{
title: '操作',
width: 200,
fixed: 'right',
slots: { default: 'actions' },
},
];
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'accountId',
label: '公众号',
component: markRaw(WxAccountSelect),
},
];
}

View File

@@ -0,0 +1,316 @@
<script lang="ts" setup>
import type { Article } from './modules/types';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { nextTick, onMounted, provide, ref, watch } from 'vue';
import { DocAlert, Page, useVbenModal } from '@vben/common-ui';
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import * as MpDraftApi from '#/api/mp/draft';
import * as MpFreePublishApi from '#/api/mp/freePublish';
import { createEmptyNewsItem } from '#/views/mp/draft/modules/types';
import { useGridColumns, useGridFormSchema } from './data';
import DraftTableCell from './modules/draft-table.vue';
import Form from './modules/form.vue';
defineOptions({ name: 'MpDraft' });
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
submitOnChange: true,
},
gridOptions: {
columns: useGridColumns(),
height: 'auto',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
// 更新 accountId
if (formValues?.accountId) {
accountId.value = formValues.accountId;
}
const drafts = await MpDraftApi.getDraftPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
// 处理 API 返回的数据,兼容不同的数据结构
const formattedList: Article[] = drafts.list.map((draft: any) => {
// 如果已经是 content.newsItem 格式,直接使用
if (draft.content?.newsItem) {
const newsItem = draft.content.newsItem.map((item: any) => ({
...item,
picUrl: item.thumbUrl || item.picUrl,
}));
return {
mediaId: draft.mediaId,
content: {
newsItem,
},
updateTime:
draft.updateTime ||
(draft.createTime
? new Date(draft.createTime).getTime()
: Date.now()),
};
}
// 如果是 articles 格式,转换为 content.newsItem 格式
if (draft.articles) {
const newsItem = draft.articles.map((article: any) => ({
...article,
thumbUrl: article.thumbUrl || article.thumbMediaId,
picUrl: article.thumbUrl || article.thumbMediaId,
}));
return {
mediaId: draft.mediaId,
content: {
newsItem,
},
updateTime:
draft.updateTime ||
(draft.createTime
? new Date(draft.createTime).getTime()
: Date.now()),
};
}
// 默认返回空结构
return {
mediaId: draft.mediaId || '',
content: {
newsItem: [],
},
updateTime: draft.updateTime || Date.now(),
};
});
return {
page: {
total: drafts.total,
},
result: formattedList,
};
},
},
autoLoad: false,
},
rowConfig: {
keyField: 'mediaId',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<Article>,
});
// 提供 accountId 给子组件
const accountId = ref<number>(-1);
// 监听表单提交,更新 accountId
watch(
() => gridApi.formApi?.getLatestSubmissionValues?.()?.accountId,
(newAccountId) => {
if (newAccountId !== undefined) {
accountId.value = newAccountId;
}
},
);
provide('accountId', accountId);
/** 新增按钮操作 */
async function handleCreate() {
const formValues = await gridApi.formApi.getValues();
const accountId = formValues.accountId;
if (!accountId || accountId === -1) {
ElMessage.warning('请先选择公众号');
return;
}
formModalApi
.setData({
isCreating: true,
accountId,
newsList: [createEmptyNewsItem()],
})
.open();
}
/** 修改按钮操作 */
async function handleEdit(row: Article) {
const formValues = await gridApi.formApi.getValues();
const accountId = formValues.accountId;
if (!accountId || accountId === -1) {
ElMessage.warning('请先选择公众号');
return;
}
formModalApi
.setData({
isCreating: false,
accountId,
mediaId: row.mediaId,
newsList: structuredClone(row.content.newsItem),
})
.open();
}
/** 发布按钮操作 */
async function handlePublish(row: Article) {
const formValues = await gridApi.formApi.getValues();
const accountId = formValues.accountId;
if (!accountId || accountId === -1) {
ElMessage.warning('请先选择公众号');
return;
}
const content =
'你正在通过发布的方式发表内容。 发布不占用群发次数,一天可多次发布。' +
'已发布内容不会推送给用户,也不会展示在公众号主页中。 ' +
'发布后,你可以前往发表记录获取链接,也可以将发布内容添加到自定义菜单、自动回复、话题和页面模板中。';
try {
await ElMessageBox.confirm(content);
const loadingInstance = ElLoading.service({
text: '发布中...',
});
try {
await MpFreePublishApi.submitFreePublish(accountId, row.mediaId);
ElMessage.success('发布成功');
await gridApi.query();
} finally {
loadingInstance.close();
}
} catch {
//
}
}
/** 删除按钮操作 */
async function handleDelete(row: Article) {
const formValues = await gridApi.formApi.getValues();
const accountId = formValues.accountId;
if (!accountId || accountId === -1) {
ElMessage.warning('请先选择公众号');
return;
}
try {
await ElMessageBox.confirm('此操作将永久删除该草稿, 是否继续?');
const loadingInstance = ElLoading.service({
text: '删除中...',
});
try {
await MpDraftApi.deleteDraft(accountId, row.mediaId);
ElMessage.success('删除成功');
await gridApi.query();
} finally {
loadingInstance.close();
}
} catch {
//
}
}
// 页面挂载后,等待表单初始化完成再加载数据
onMounted(async () => {
await nextTick();
if (gridApi.formApi) {
const formValues = await gridApi.formApi.getValues();
if (formValues.accountId) {
accountId.value = formValues.accountId;
gridApi.formApi.setLatestSubmissionValues(formValues);
await gridApi.query();
}
}
});
</script>
<template>
<Page auto-content-height>
<DocAlert title="公众号图文" url="https://doc.iocoder.cn/mp/article/" />
<FormModal
@success="
() => {
gridApi.query();
}
"
/>
<Grid table-title="草稿列表">
<template #toolbar-tools>
<TableAction
:actions="[
{
label: '新增',
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['mp:draft:create'],
onClick: handleCreate,
},
]"
/>
</template>
<template #content="{ row }">
<DraftTableCell :row="row" />
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: '发布',
type: 'success',
link: true,
icon: ACTION_ICON.UPLOAD,
auth: ['mp:free-publish:submit'],
onClick: handlePublish.bind(null, row),
},
{
label: '编辑',
type: 'primary',
link: true,
icon: ACTION_ICON.EDIT,
auth: ['mp:draft:update'],
onClick: handleEdit.bind(null, row),
},
{
label: '删除',
type: 'danger',
link: true,
icon: ACTION_ICON.DELETE,
auth: ['mp:draft:delete'],
popConfirm: {
title: '是否确认删除此数据?',
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</Page>
</template>
<style lang="scss" scoped>
:deep(.vxe-table--body-wrapper) {
.vxe-table--body {
.vxe-body--column {
.vxe-cell {
padding: 0;
}
}
}
}
</style>

View File

@@ -0,0 +1,164 @@
export default {
list: [
{
mediaId:
'r6ryvl6LrxBU0miaST4Y-q-G9pdsmZw0OYG4FzHQkKfpLfEwIH51wy2bxisx8PvW',
content: {
newsItem: [
{
title: '我是标题OOO',
author: '我是作者',
digest: '我是摘要',
content: '我是内容',
contentSourceUrl: 'https://www.iocoder.cn',
thumbMediaId:
'r6ryvl6LrxBU0miaST4Y-pIcmK-zAAId-9TGgy-DrSLhjVuWbuT3ZBjk9K1yQ0Dn',
showCoverPic: 0,
needOpenComment: 0,
onlyFansCanComment: 0,
url: 'http://mp.weixin.qq.com/s?__biz=MzA3NjM4MzQzOQ==&tempkey=MTIxMl9XaFphcmtJVFh3VEc4Q1MxQWwxQ3R5R0JGTXBDM1Q0N2ZFQm8zeUphOFlwNEpXSWxTYm9RQnJ6cHVuN2QxTE56SFBCYXc2RE9NcUxIeS1CQjJuUHhTWjBlN2VOeGRpRi1fZUhwN1FNQjdrQV9yRU9EU0hibHREZmZoVW5acnZrN3ZjaWsxejR3RGpKczBzTHFIM0dFNFZWVkpBc0dWWlAzUEhlVmpnfn4%3D&chksm=1f6354802814dd969ef83c0f3babe555c614270b30bc383beaf7ffd13b0257f0fe5ced9af694#rd',
thumbUrl:
'http://test.yudao.iocoder.cn/r6ryvl6LrxBU0miaST4Y-pIcmK-zAAId-9TGgy-DrSLhjVuWbuT3ZBjk9K1yQ0Dn.png',
},
{
title: '我是标题XXX',
author: '我是作者',
digest: '我是摘要',
content: '我是内容',
contentSourceUrl: 'https://www.iocoder.cn',
thumbMediaId:
'r6ryvl6LrxBU0miaST4Y-pIcmK-zAAId-9TGgy-DrSLhjVuWbuT3ZBjk9K1yQ0Dn',
showCoverPic: 0,
needOpenComment: 0,
onlyFansCanComment: 0,
url: 'http://mp.weixin.qq.com/s?__biz=MzA3NjM4MzQzOQ==&tempkey=MTIxMl9yTlYwOEs1clpwcE5OUEhCQWwxQ3R5R0JGTXBDM1Q0N2ZFQm8zeUphOFlwNEpXSWxTYm9RQnJ6cHVuN0NSMjFqN3N1aUZMbFNVLTZHN2ZDME9qOGp2THk2RFNlSTlKZ3Y1czFVZDdQQm5IeUg3dEppSUtpQUh5SExOOTRkT3dHNUdBdHdWSWlOendlREV3dS1jUEVQbFpiVTZmVW5iRWhZcGdkNTFRfn4%3D&chksm=1f6354802814dd96a403151cd44c7da4eecf0e475d25423e46ecd795b513bafd829a75daef9b#rd',
thumbUrl:
'http://test.yudao.iocoder.cn/r6ryvl6LrxBU0miaST4Y-pIcmK-zAAId-9TGgy-DrSLhjVuWbuT3ZBjk9K1yQ0Dn.png',
},
],
},
updateTime: 1_673_655_730,
},
{
mediaId:
'r6ryvl6LrxBU0miaST4Y-jGpXnO73ihN0lsNXknCRQHapp2xgHMRxHKG50LituFe',
content: {
newsItem: [
{
title: '我是标题(修改)',
author: '我是作者',
digest: '我是摘要',
content: '我是内容',
contentSourceUrl: 'https://www.iocoder.cn',
thumbMediaId:
'r6ryvl6LrxBU0miaST4Y-pIcmK-zAAId-9TGgy-DrSLhjVuWbuT3ZBjk9K1yQ0Dn',
showCoverPic: 0,
needOpenComment: 0,
onlyFansCanComment: 0,
url: 'http://mp.weixin.qq.com/s?__biz=MzA3NjM4MzQzOQ==&tempkey=MTIxMl95WVFXYndIZnZJd0t5cjgvQWwxQ3R5R0JGTXBDM1Q0N2ZFQm8zeUphOFlwNEpXSWxTYm9RQnJ6cHVuN1dlNURPbWswbEF4RDd5dVJTdjQ4cm9Cc0Q1TWhpMUh6SE1hVEE3ZHljaHhlZjZYSGF5N2JNSHpDTlh6ajNZbkpGTGpTcUQ4M3NMdW41ZUpXNFZZQ1VKbVlaMVp5ekxEV1czREdsY1dOYTZnfn4%3D&chksm=1f6354be2814dda8e6238037c2ebd52b1c8e80e93249a861ad80e4d40e5ca7207233475ca689#rd',
thumbUrl:
'http://test.yudao.iocoder.cn/r6ryvl6LrxBU0miaST4Y-pIcmK-zAAId-9TGgy-DrSLhjVuWbuT3ZBjk9K1yQ0Dn.png',
},
],
},
updateTime: 1_673_655_584,
},
{
mediaId:
'r6ryvl6LrxBU0miaST4Y-v5SrbNCPpD6M_p3TmSrYwTjKogs-0DMJgmjMyNZPeMO',
content: {
newsItem: [
{
title: '1321',
author: '3232',
digest: '1333',
content: '<p>444</p>',
contentSourceUrl: 'http://www.iocoder.cn',
thumbMediaId:
'r6ryvl6LrxBU0miaST4Y-tlQmcl3RdC-Jcgns6IQtf7zenGy3b86WLT7GzUcrb1T',
showCoverPic: 0,
needOpenComment: 0,
onlyFansCanComment: 0,
url: 'http://mp.weixin.qq.com/s?__biz=MzA3NjM4MzQzOQ==&tempkey=MTIxMl9jelJiaDAzbmdpSkJOZ2M2QWwxQ3R5R0JGTXBDM1Q0N2ZFQm8zeUphOFlwNEpXSWxTYm9RQnJ6cHVuNDNXVVc2ZDRYeTY0Zm1weXR6dE9vQWh1TzEwbEpUVnRfVzJyaGFDNXBkZ0ZXM2JFOTNaRHNhOHRUeFdEanhMeS01X01kMUNWQ1BpRER3cjYwTl9pMnpFLUJhZXFucVVfM1pDUXlTUEl1S25nfn4%3D&chksm=1f6354bc2814ddaa56a90ad5bc3d078601c8d1589ba01827a8170587bc830ff9747b5f59c3a0#rd',
thumbUrl:
'http://mmbiz.qpic.cn/mmbiz_png/btUmCVHwbJUoicwBiacjVeQbu6QxgBVrukfSJXz509boa21SpH8OVHAqXCJiaiaAaHQJNxwwsa0gHRXVr0G5EZYamw/0?wx_fmt=png',
},
],
},
updateTime: 1_673_628_969,
},
{
mediaId:
'r6ryvl6LrxBU0miaST4Y-vdWrisK5EZbk4Y3tzh8P0PG0eEUbnQrh0BcsEb3WNP0',
content: {
newsItem: [
{
title: 'tudou',
author: 'haha',
digest: '312',
content: '<p>132312</p>',
contentSourceUrl: 'http://www.iocoder.cn',
thumbMediaId:
'r6ryvl6LrxBU0miaST4Y-pgFtUNLu1foMSAMkoOsrQrTZ8EtTMssBLfTtzP0dfjG',
showCoverPic: 0,
needOpenComment: 0,
onlyFansCanComment: 0,
url: 'http://mp.weixin.qq.com/s?__biz=MzA3NjM4MzQzOQ==&tempkey=MTIxMl9qdkJ1ZjBoUmg2Uk9TS3RlQWwxQ3R5R0JGTXBDM1Q0N2ZFQm8zeUphOFlwNEpXSWxTYm9RQnJ6cHVuNVg2aTJsaC1fMkU2eXNacUplN3VDTTZFZkhtMjhuTUZvWkxsNDBRSXExY2tiVXRHb09TaHgtREhzY3doZ0JYeC1TSTZ5eWZldXJsOWtfbV8yMi1aYkcyZ2pOY0haM0Ntb3VSWEtxUGVFRlNBfn4%3D&chksm=1f6354ba2814ddacf0184b24d310483641ef190b1faac098c285eb416c70017e2f54decfa1af#rd',
thumbUrl:
'http://test.yudao.iocoder.cn/r6ryvl6LrxBU0miaST4Y-pgFtUNLu1foMSAMkoOsrQrTZ8EtTMssBLfTtzP0dfjG.png',
},
],
},
updateTime: 1_673_628_760,
},
{
mediaId:
'r6ryvl6LrxBU0miaST4Y-u9kTIm1DhWZDdXyxsxUVv2Z5DAB99IPxkIRTUUD206k',
content: {
newsItem: [
{
title: '12',
author: '333',
digest: '123',
content: '123',
contentSourceUrl: 'https://www.iocoder.cn',
thumbMediaId:
'r6ryvl6LrxBU0miaST4Y-jVixJGgnBnkBPRbuVptOW0CHYuQFyiOVNtamctS8xU8',
showCoverPic: 0,
needOpenComment: 0,
onlyFansCanComment: 0,
url: 'http://mp.weixin.qq.com/s?__biz=MzA3NjM4MzQzOQ==&tempkey=MTIxMl9qVVhpSDZUaFJWTzBBWWRVQWwxQ3R5R0JGTXBDM1Q0N2ZFQm8zeUphOFlwNEpXSWxTYm9RQnJ6cHVuNWRnTDJWYmF2NER0clV1bThmQ0xUR3hqQnJkZ3BJSUNmNDJmc0lCZ1dadkVnZ3Z5bkN4YWtVUjhoaWZWYzZURUR4NnpMd0Y4Z3U5aUdib0lkMzI4Rjg3SG9JX2FycTMxbUctOHplaTlQVVhnfn4%3D&chksm=1f6354b62814dda076c778af33f06580165d8aa81f7798d55cfabb1886b5c74d9b2124a3535c#rd',
thumbUrl:
'http://test.yudao.iocoder.cn/r6ryvl6LrxBU0miaST4Y-jVixJGgnBnkBPRbuVptOW0CHYuQFyiOVNtamctS8xU8.jpg',
},
],
},
updateTime: 1_673_626_494,
},
{
mediaId:
'r6ryvl6LrxBU0miaST4Y-sO24upobaENDmeByfBTfaozB3aOqSMAV0lGy-UkHXE7',
content: {
newsItem: [
{
title: '我是标题',
author: '我是作者',
digest: '我是摘要',
content: '我是内容',
contentSourceUrl: 'https://www.iocoder.cn',
thumbMediaId:
'r6ryvl6LrxBU0miaST4Y-pIcmK-zAAId-9TGgy-DrSLhjVuWbuT3ZBjk9K1yQ0Dn',
showCoverPic: 0,
needOpenComment: 0,
onlyFansCanComment: 0,
url: 'http://mp.weixin.qq.com/s?__biz=MzA3NjM4MzQzOQ==&tempkey=MTIxMl9LT2dqRnpMNUpsR0hjYWtBQWwxQ3R5R0JGTXBDM1Q0N2ZFQm8zeUphOFlwNEpXSWxTYm9RQnJ6cHVuNGNmazZTdlE5WkxvU0tfX2V5cjV2WjJiR0xjQUhyREFSZWo2eWNrUW9EYVh6ZkpWRXBLR3FmTEV6YldBMno3Q2ZvVXBSdzlaVDc3aFhndEpQWUwzWmFMUWt0YVVURE1VZ1FsQTdPMlRtc3JBfn4%3D&chksm=1f6354aa2814ddbcc2637382f963a8742993ac38ebcebe6e3411df5ac82ac7bbdb391be6494a#rd',
thumbUrl:
'http://test.yudao.iocoder.cn/r6ryvl6LrxBU0miaST4Y-pIcmK-zAAId-9TGgy-DrSLhjVuWbuT3ZBjk9K1yQ0Dn.png',
},
],
},
updateTime: 1_673_534_279,
},
],
total: 6,
};

View File

@@ -0,0 +1,181 @@
<script lang="ts" setup>
import type { UploadFiles, UploadProps, UploadRawFile } from 'element-plus';
import type { NewsItem } from './types';
import { computed, inject, reactive, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { useAccessStore } from '@vben/stores';
import { ElButton, ElDialog, ElImage, ElMessage, ElUpload } from 'element-plus';
import { UploadType, useBeforeUpload } from '#/utils/useUpload';
import WxMaterialSelect from '#/views/mp/modules/wx-material-select';
// 设置上传的请求头部
const props = defineProps<{
isFirst: boolean;
modelValue: NewsItem;
}>();
const emit = defineEmits<{
(e: 'update:modelValue', v: NewsItem): void;
}>();
const UPLOAD_URL = `${import.meta.env.VITE_BASE_URL}/admin-api/mp/material/upload-permanent`; // 上传永久素材的地址
const HEADERS = { Authorization: `Bearer ${useAccessStore().accessToken}` };
const newsItem = computed<NewsItem>({
get() {
return props.modelValue;
},
set(val) {
emit('update:modelValue', val);
},
});
const accountId = inject<number>('accountId');
const showImageDialog = ref(false);
const fileList = ref<UploadFiles>([]);
interface UploadData {
type: UploadType;
accountId: number;
}
const uploadData: UploadData = reactive({
type: UploadType.Image,
accountId: accountId!,
});
/** 素材选择完成事件*/
function onMaterialSelected(item: any) {
showImageDialog.value = false;
newsItem.value.thumbMediaId = item.mediaId;
newsItem.value.thumbUrl = item.url;
}
const onBeforeUpload: UploadProps['beforeUpload'] = (rawFile: UploadRawFile) =>
useBeforeUpload(UploadType.Image, 2)(rawFile);
function onUploadSuccess(res: any) {
if (res.code !== 0) {
ElMessage.error(`上传出错:${res.msg}`);
return false;
}
// 重置上传文件的表单
fileList.value = [];
// 设置草稿的封面字段
newsItem.value.thumbMediaId = res.data.mediaId;
newsItem.value.thumbUrl = res.data.url;
}
function onUploadError(err: Error) {
ElMessage.error(`上传失败: ${err.message}`);
}
</script>
<template>
<div>
<p>封面:</p>
<div class="thumb-div">
<ElImage
v-if="newsItem.thumbUrl"
style="width: 300px; max-height: 300px"
:src="newsItem.thumbUrl"
fit="contain"
/>
<IconifyIcon
v-else
icon="ep:plus"
class="avatar-uploader-icon"
:class="isFirst ? 'avatar' : 'avatar1'"
/>
<div class="thumb-but">
<ElUpload
:action="UPLOAD_URL"
:headers="HEADERS"
multiple
:limit="1"
:file-list="fileList"
:data="uploadData"
:before-upload="onBeforeUpload"
:on-error="onUploadError"
:on-success="onUploadSuccess"
>
<template #trigger>
<ElButton size="small" type="primary">本地上传</ElButton>
</template>
<ElButton
size="small"
type="primary"
@click="showImageDialog = true"
style="margin-left: 5px"
>
素材库选择
</ElButton>
<template #tip>
<div class="el-upload__tip">
支持 bmp/png/jpeg/jpg/gif 格式大小不超过 2M
</div>
</template>
</ElUpload>
</div>
<ElDialog
title="选择图片"
v-model="showImageDialog"
width="80%"
append-to-body
destroy-on-close
>
<WxMaterialSelect
type="image"
:account-id="accountId!"
@select-material="onMaterialSelected"
/>
</ElDialog>
</div>
</div>
</template>
<style lang="scss" scoped>
.el-upload__tip {
margin-left: 5px;
}
.thumb-div {
display: inline-block;
width: 100%;
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
.avatar-uploader-icon {
width: 120px;
height: 120px;
font-size: 28px;
line-height: 120px;
color: #8c939d;
text-align: center;
border: 1px solid #d9d9d9;
}
.avatar {
width: 230px;
height: 120px;
}
.avatar1 {
width: 120px;
height: 120px;
}
.thumb-but {
margin: 5px;
}
}
</style>

View File

@@ -0,0 +1,25 @@
<script lang="ts" setup>
import type { Article } from './types';
import WxNews from '#/views/mp/modules/wx-news';
defineOptions({ name: 'DraftTableCell' });
const props = defineProps<{
row: Article;
}>();
</script>
<template>
<div class="draft-content">
<div v-if="props.row.content && props.row.content.newsItem">
<WxNews :articles="props.row.content.newsItem" />
</div>
</div>
</template>
<style lang="scss" scoped>
.draft-content {
padding: 10px;
}
</style>

View File

@@ -0,0 +1,102 @@
<script lang="ts" setup>
import type { NewsItem } from './types';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { ElMessage, ElMessageBox } from 'element-plus';
import * as MpDraftApi from '#/api/mp/draft';
import NewsForm from './news-form.vue';
const emit = defineEmits(['success']);
const formData = ref<{
accountId: number;
isCreating: boolean;
mediaId?: string;
newsList?: NewsItem[];
}>();
const newsList = ref<NewsItem[]>([]);
const isSubmitting = ref(false);
const isSaved = ref(false);
const getTitle = computed(() => {
return formData.value?.isCreating ? '新建图文' : '修改图文';
});
const [Modal, modalApi] = useVbenModal({
async onConfirm() {
if (!formData.value) {
return;
}
isSubmitting.value = true;
modalApi.lock();
try {
if (formData.value.isCreating) {
await MpDraftApi.createDraft(formData.value.accountId, newsList.value);
ElMessage.success('新增成功');
} else if (formData.value.mediaId) {
await MpDraftApi.updateDraft(
formData.value.accountId,
formData.value.mediaId,
newsList.value,
);
ElMessage.success('更新成功');
}
isSaved.value = true;
await modalApi.close();
emit('success');
} finally {
isSubmitting.value = false;
modalApi.unlock();
}
},
async onBeforeClose() {
// 如果已经成功保存,直接关闭,不显示提示
if (isSaved.value) {
return true;
}
try {
await ElMessageBox.confirm('修改内容可能还未保存,确定关闭吗?');
return true;
} catch {
return false;
}
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
formData.value = undefined;
newsList.value = [];
isSaved.value = false;
return;
}
isSaved.value = false;
const data = modalApi.getData<{
accountId: number;
isCreating: boolean;
mediaId?: string;
newsList?: NewsItem[];
}>();
if (!data) {
return;
}
formData.value = data;
newsList.value = data.newsList || [];
},
});
</script>
<template>
<Modal :title="getTitle" class="w-4/5" destroy-on-close>
<NewsForm
v-if="formData"
v-model="newsList"
v-loading="isSubmitting"
:is-creating="formData.isCreating"
/>
</Modal>
</template>

View File

@@ -0,0 +1,341 @@
<script lang="ts" setup>
import type { NewsItem } from './types';
import { computed, ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import {
ElAside,
ElButton,
ElCol,
ElContainer,
ElInput,
ElMain,
ElMessageBox,
ElRow,
} from 'element-plus';
import { Tinymce as RichTextarea } from '#/components/tinymce';
import CoverSelect from './cover-select.vue';
import { createEmptyNewsItem } from './types';
defineOptions({ name: 'NewsForm' });
const props = defineProps<{
isCreating: boolean;
modelValue: NewsItem[] | null;
}>();
// v-model=newsList
const emit = defineEmits<{
(e: 'update:modelValue', v: NewsItem[]): void;
}>();
const newsList = computed<NewsItem[]>({
get() {
return props.modelValue === null
? [createEmptyNewsItem()]
: props.modelValue;
},
set(val) {
emit('update:modelValue', val);
},
});
const activeNewsIndex = ref(0);
const activeNewsItem = computed(() => {
const item = newsList.value[activeNewsIndex.value];
if (!item) {
return createEmptyNewsItem();
}
return item;
});
// 将图文向下移动
function moveDownNews(index: number) {
const current = newsList.value[index];
const next = newsList.value[index + 1];
if (current && next) {
newsList.value[index] = next;
newsList.value[index + 1] = current;
activeNewsIndex.value = index + 1;
}
}
// 将图文向上移动
function moveUpNews(index: number) {
const current = newsList.value[index];
const prev = newsList.value[index - 1];
if (current && prev) {
newsList.value[index] = prev;
newsList.value[index - 1] = current;
activeNewsIndex.value = index - 1;
}
}
// 删除指定 index 的图文
async function removeNews(index: number) {
try {
await ElMessageBox.confirm('确定删除该图文吗?');
newsList.value.splice(index, 1);
if (activeNewsIndex.value === index) {
activeNewsIndex.value = 0;
}
} catch {
// empty
}
}
// 添加一个图文
function plusNews() {
newsList.value.push(createEmptyNewsItem());
activeNewsIndex.value = newsList.value.length - 1;
}
</script>
<template>
<ElContainer>
<ElAside width="40%">
<div class="select-item">
<div v-for="(news, index) in newsList" :key="index">
<div
class="news-main father"
v-if="index === 0"
:class="{ activeAddNews: activeNewsIndex === index }"
@click="activeNewsIndex = index"
>
<div class="news-content">
<img class="material-img" :src="news.thumbUrl" />
<div class="news-content-title">{{ news.title }}</div>
</div>
<div class="child" v-if="newsList.length > 1">
<ElButton
type="info"
circle
size="small"
@click="() => moveDownNews(index)"
>
<IconifyIcon icon="ep:arrow-down-bold" />
</ElButton>
<ElButton
v-if="isCreating"
type="danger"
circle
size="small"
@click="() => removeNews(index)"
>
<IconifyIcon icon="ep:delete" />
</ElButton>
</div>
</div>
<div
class="news-main-item father"
v-if="index > 0"
:class="{ activeAddNews: activeNewsIndex === index }"
@click="activeNewsIndex = index"
>
<div class="news-content-item">
<div class="news-content-item-title">{{ news.title }}</div>
<div class="news-content-item-img">
<img class="material-img" :src="news.thumbUrl" width="100%" />
</div>
</div>
<div class="child">
<ElButton
v-if="newsList.length > index + 1"
circle
type="info"
size="small"
@click="() => moveDownNews(index)"
>
<IconifyIcon icon="ep:arrow-down-bold" />
</ElButton>
<ElButton
v-if="index > 0"
type="info"
circle
size="small"
@click="() => moveUpNews(index)"
>
<IconifyIcon icon="ep:arrow-up-bold" />
</ElButton>
<ElButton
v-if="isCreating"
type="danger"
size="small"
circle
@click="() => removeNews(index)"
>
<IconifyIcon icon="ep:delete" />
</ElButton>
</div>
</div>
</div>
<ElRow justify="center" class="ope-row">
<ElButton
type="primary"
circle
@click="plusNews"
v-if="newsList.length < 8 && isCreating"
>
<IconifyIcon icon="ep:plus" />
</ElButton>
</ElRow>
</div>
</ElAside>
<ElMain>
<div v-if="newsList.length > 0 && activeNewsItem">
<!-- 标题作者原文地址 -->
<ElRow :gutter="20">
<ElInput
v-model="activeNewsItem.title"
placeholder="请输入标题(必填)"
/>
<ElInput
v-model="activeNewsItem.author"
placeholder="请输入作者"
style="margin-top: 5px"
/>
<ElInput
v-model="activeNewsItem.contentSourceUrl"
placeholder="请输入原文地址"
style="margin-top: 5px"
/>
</ElRow>
<!-- 封面和摘要 -->
<ElRow :gutter="20">
<ElCol :span="12">
<CoverSelect
v-model="activeNewsItem"
:is-first="activeNewsIndex === 0"
/>
</ElCol>
<ElCol :span="12">
<p>摘要:</p>
<ElInput
:rows="8"
type="textarea"
v-model="activeNewsItem.digest"
placeholder="请输入摘要"
class="digest"
maxlength="120"
/>
</ElCol>
</ElRow>
<!--富文本编辑器组件-->
<ElRow>
<RichTextarea v-model="activeNewsItem.content" />
</ElRow>
</div>
</ElMain>
</ElContainer>
</template>
<style lang="scss" scoped>
.ope-row {
padding-top: 5px;
margin-top: 5px;
text-align: center;
border-top: 1px solid #eaeaea;
}
.el-row {
margin-bottom: 20px;
}
.el-row:last-child {
margin-bottom: 0;
}
.digest {
display: inline-block;
width: 100%;
vertical-align: top;
}
/* 新增图文 */
.news-main {
width: 100%;
height: 120px;
margin: auto;
background-color: #fff;
}
.news-content {
position: relative;
width: 100%;
height: 120px;
background-color: #acadae;
}
.news-content-title {
position: absolute;
bottom: 0;
left: 0;
display: inline-block;
width: 98%;
height: 25px;
padding: 1%;
overflow: hidden;
font-size: 15px;
color: #fff;
text-overflow: ellipsis;
white-space: nowrap;
background-color: black;
opacity: 0.65;
}
.news-main-item {
width: 100%;
padding: 5px 0;
margin: auto;
background-color: #fff;
border-top: 1px solid #eaeaea;
}
.news-content-item {
position: relative;
margin-left: -3px;
}
.news-content-item-title {
display: inline-block;
width: 70%;
font-size: 12px;
}
.news-content-item-img {
display: inline-block;
width: 25%;
background-color: #acadae;
}
.select-item {
width: 60%;
padding: 10px;
margin: 0 auto 10px;
border: 1px solid #eaeaea;
.activeAddNews {
border: 5px solid #2bb673;
}
}
.father .child {
position: relative;
bottom: 25px;
display: none;
text-align: center;
}
.father:hover .child {
display: block;
}
.material-img {
width: 100%;
height: 100%;
}
</style>

View File

@@ -0,0 +1,41 @@
interface NewsItem {
title: string;
thumbMediaId: string;
author: string;
digest: string;
showCoverPic: number;
content: string;
contentSourceUrl: string;
needOpenComment: number;
onlyFansCanComment: number;
thumbUrl: string;
picUrl?: string; // 用于预览封面
}
interface NewsItemList {
newsItem: NewsItem[];
}
interface Article {
mediaId: string;
content: NewsItemList;
updateTime: number;
}
const createEmptyNewsItem = (): NewsItem => {
return {
title: '',
thumbMediaId: '',
author: '',
digest: '',
showCoverPic: 0,
content: '',
contentSourceUrl: '',
needOpenComment: 0,
onlyFansCanComment: 0,
thumbUrl: '',
};
};
export type { Article, NewsItem, NewsItemList };
export { createEmptyNewsItem };