liu
3 天以前 2b695bfabdceccb0ee19c12c8e655bd7f47a6e2f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
<script lang="ts" setup>
import type { WxCpNoticeApi } from '#/api/wxcp/notice';
 
import type { NoticeFormType } from '../data';
 
import { computed, ref } from 'vue';
 
import { useVbenModal } from '@vben/common-ui';
import { Button, message } from 'ant-design-vue';
 
import { useVbenForm } from '#/adapter/form';
import { toAccessibleFileUrl } from '#/utils';
import {
  createNotice,
  getNotice,
  updateNotice,
} from '#/api/wxcp/notice';
 
import { NOTICE_TYPE, useNoticeFormSchema } from '../data';
import ArticleEditor from './article-editor.vue';
 
defineOptions({ name: 'WxCpNoticeForm' });
 
const emit = defineEmits<{ success: [] }>();
 
const formType = ref<NoticeFormType>('create');
const id = ref<number>();
const submitting = ref(false);
/** 当前模板类型,用于控制多图文编辑器显隐 */
const noticeType = ref<number>(NOTICE_TYPE.TEXT);
/** 多图文条目(表单项之外单独维护) */
const articles = ref<WxCpNoticeApi.NoticeArticle[]>([]);
 
const showArticleEditor = computed(
  () => noticeType.value === NOTICE_TYPE.MULTI_NEWS,
);
 
const isEdit = computed(() => formType.value !== 'detail');
const title = computed(() => {
  if (formType.value === 'detail') return '查看通知';
  if (id.value) return '编辑通知';
  return '新建通知';
});
 
/**
 * 把附件列表转成上传组件能识别的文件对象
 *
 * 回显对象必须带 response:组件设了 resultField 后只认 item.response,
 * 不带的话「进编辑页不动图直接保存」会走 URL 分支 → NaN → [] → 图被清空
 */
function attachmentsToUploadFiles(
  list: WxCpNoticeApi.NoticeAttachment[] | undefined,
) {
  return (list ?? []).map((item) => {
    const name = item.name || item.originalFilename || '';
    const url = toAccessibleFileUrl(item.url || item.previewURL);
    return {
      uid: String(item.id),
      name,
      url,
      status: 'done',
      id: item.id,
      response: { id: item.id, name, url },
    };
  });
}
 
/**
 * 把上传组件的值规整成 blobId 数组
 *
 * ImageUpload 在 maxNumber=1 时返回单个值而不是数组,这里统一包成数组再提交
 */
function normalizeBlobIds(value: unknown): number[] {
  const list = Array.isArray(value)
    ? value
    : value === '' || value === null || value === undefined
      ? []
      : [value];
  return list
    .map((item) =>
      item && typeof item === 'object' && 'id' in item
        ? Number((item as { id: unknown }).id)
        : Number(item),
    )
    .filter((blobId) => Number.isFinite(blobId));
}
 
/**
 * 把通知详情映射成表单值
 *
 * 图片/附件不落业务表字段,统一存在附件中间表,
 * 回显时把 imageAttachmentList / fileAttachmentList 转成上传组件文件对象。
 * 历史数据只有旧版 fileBlobId,这里兜底成单个附件,避免编辑后附件丢失。
 */
function noticeToForm(
  detail: WxCpNoticeApi.Notice,
): Record<string, unknown> {
  const form: Record<string, unknown> = { ...detail };
  form.imageBlobIds = attachmentsToUploadFiles(detail.imageAttachmentList);
  form.videoBlobIds = attachmentsToUploadFiles(detail.videoAttachmentList);
  form.fileBlobIds =
    detail.fileAttachmentList?.length
      ? attachmentsToUploadFiles(detail.fileAttachmentList)
      : detail.fileBlobId
        ? [
            {
              uid: String(detail.fileBlobId),
              name: detail.fileName || '',
              status: 'done',
              id: detail.fileBlobId,
              response: {
                id: detail.fileBlobId,
                name: detail.fileName || '',
              },
            },
          ]
        : [];
  return form;
}
 
const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: { class: 'w-full' },
    formItemClass: 'col-span-1',
    labelWidth: 90,
  },
  layout: 'horizontal',
  schema: [],
  showDefaultActions: false,
  wrapperClass: 'grid-cols-1',
  handleValuesChange: (values) => {
    noticeType.value = (values.noticeType as number) ?? NOTICE_TYPE.TEXT;
  },
});
 
const [Modal, modalApi] = useVbenModal({
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      id.value = undefined;
      return;
    }
    const data = modalApi.getData<{ formType: NoticeFormType; id?: number }>();
    formType.value = data.formType;
    id.value = data.id;
    formApi.setState({ schema: useNoticeFormSchema(formType.value) });
    formApi.setDisabled(formType.value === 'detail');
    if (data.id) {
      modalApi.lock();
      try {
        const detail = await getNotice(data.id);
        noticeType.value = detail.noticeType ?? NOTICE_TYPE.TEXT;
        articles.value = (detail.articleList ?? []).map((item) => ({
          ...item,
        }));
        await formApi.setValues(noticeToForm(detail));
      } finally {
        modalApi.unlock();
      }
    } else {
      await formApi.resetForm();
      noticeType.value = NOTICE_TYPE.TEXT;
      articles.value = [];
      await formApi.setValues({ noticeType: NOTICE_TYPE.TEXT }, false);
    }
  },
});
 
async function handleSubmit() {
  const { valid } = await formApi.validate();
  if (!valid) {
    return;
  }
  submitting.value = true;
  try {
    const data = (await formApi.getValues()) as WxCpNoticeApi.Notice;
    // 保存时只做文件归一化;具体模板必填项在推送时按所选模板校验
    const payload = {
      ...data,
      // null = 不改动,[] = 清空;这里统一提交数组,切换模板后旧附件会被清掉
      imageBlobIds: normalizeBlobIds(data.imageBlobIds),
      fileBlobIds: normalizeBlobIds(data.fileBlobIds),
      videoBlobIds: normalizeBlobIds(data.videoBlobIds),
      // 多图文条目单独维护,只有该模板提交;null 表示不改动
      articleList: showArticleEditor.value ? articles.value : undefined,
      // 旧版单附件字段不再使用,避免和 fileBlobIds 重复
      fileBlobId: undefined,
      fileName: undefined,
    } as WxCpNoticeApi.Notice;
    if (id.value) {
      await updateNotice({ ...payload, id: id.value });
      message.success('修改成功');
    } else {
      await createNotice(payload);
      message.success('创建成功,请在列表中发布后再推送');
    }
    await modalApi.close();
    emit('success');
  } catch (error: unknown) {
    message.error((error as Error)?.message || '提交失败');
  } finally {
    submitting.value = false;
  }
}
</script>
 
<template>
  <Modal :title="title" class="w-3/5">
    <Form class="mx-4" />
 
    <div v-if="showArticleEditor" class="mx-4 mt-2">
      <ArticleEditor
        v-model="articles"
        :disabled="formType === 'detail'"
      />
    </div>
 
    <template #footer>
      <div class="flex justify-end gap-2">
        <Button @click="modalApi.close()">取消</Button>
        <Button
          v-if="isEdit"
          type="primary"
          :loading="submitting"
          @click="handleSubmit"
        >
          确认
        </Button>
        <Button v-else type="primary" @click="modalApi.close()">关闭</Button>
      </div>
    </template>
  </Modal>
</template>