This commit is contained in:
dylanmay
2025-11-12 12:25:53 +08:00
594 changed files with 53927 additions and 1669 deletions

View File

@@ -9,7 +9,7 @@
## 🐶 新手必读
- nodejs > 20.10.0 && pnpm > 10.14.0 (强制使用pnpm)
- nodejs > 20.12.0 && pnpm > 10.14.0 (强制使用pnpm)
- 演示地址【Vue3 + element-plus】<http://dashboard-vue3.yudao.iocoder.cn>
- 演示地址【Vue3 + vben5(ant-design-vue)】:<http://dashboard-vben.yudao.iocoder.cn>
- 演示地址【Vue2 + element-ui】<http://dashboard.yudao.iocoder.cn>
@@ -21,7 +21,7 @@
**芋道**,以开发者为中心,打造中国第一流的快速开发平台,全部开源,个人与企业可 100% 免费使用。
- 采用最新 [vue-vben-admin](https://github.com/vbenjs/vue-vben-admin) v5 实现
- 支持 [Ant Design Vue](https://www.antdv.com/) | [Element Plus](https://element-plus.org/zh-CN/) | [Naive UI](https://www.naiveui.com/) 多种免费开源的中后台模版,具备如下特性:
- 支持 [Ant Design Vue](https://www.antdv.com/) | [Element Plus](https://element-plus.org/zh-CN/) | [Naive UI](https://www.naiveui.com/) | [TDesign](https://tdesign.tencent.com/) 多种免费开源的中后台模版,具备如下特性:
![首页](.image/demo/vben.png)
@@ -46,12 +46,14 @@
| [Ant Design Vue](https://www.antdv.com/) | Ant Design Vue | 4.2.6 |
| [Element Plus](https://element-plus.org/zh-CN/) | Element Plus | 2.10.2 |
| [Naive UI](https://www.naiveui.com/) | Naive UI | 2.42.0 |
| [TDesign](https://tdesign.tencent.com/) | TDesign | 1.17.1 |
| [TypeScript](https://www.typescriptlang.org/docs/) | JavaScript 超集 | 5.8.3 |
| [pinia](https://pinia.vuejs.org/) | Vue 存储库替代 vuex5 | 3.0.3 |
| [vueuse](https://vueuse.org/) | 常用工具集 | 13.4.0 |
| [vue-i18n](https://kazupon.github.io/vue-i18n/zh/introduction.html/) | 国际化 | 11.1.7 |
| [vue-router](https://router.vuejs.org/) | Vue 路由 | 4.5.1 |
| [Tailwind CSS](https://tailwindcss.com/) | 原子 CSS | 3.4.17 |
| [Iconify](https://iconify.design/) | 图标组件 | 5.0.0 |
| [Iconify](https://icon-sets.iconify.design/) | 在线图标库 | 2.2.354 |
| [TinyMCE](https://www.tiny.cloud/) | 富文本编辑器 | 6.1.0 |
| [Echarts](https://echarts.apache.org/) | 图表库 | 5.6.0 |

View File

@@ -61,10 +61,11 @@
"pinia": "catalog:",
"steady-xml": "catalog:",
"tinymce": "catalog:",
"video.js": "^7.21.5",
"video.js": "catalog:",
"vue": "catalog:",
"vue-dompurify-html": "catalog:",
"vue-router": "catalog:",
"vue3-print-nb": "catalog:",
"vue3-signature": "catalog:",
"vuedraggable": "catalog:"
}

View File

@@ -20,6 +20,7 @@ export namespace BpmModelApi {
suspensionState: number;
formType?: number;
formCustomViewPath?: string;
formFields?: string[];
}
/** 流程模型 */

View File

@@ -20,6 +20,7 @@ export namespace BpmProcessInstanceApi {
export interface User {
avatar: string;
deptName?: string;
id: number;
nickname: string;
}
@@ -101,6 +102,22 @@ export namespace BpmProcessInstanceApi {
}[];
taskId: string;
}
/** 打印数据任务信息 */
export interface PrintTask {
description: string;
id: number;
name: string;
signPicUrl?: string;
}
/** 打印数据 */
export interface PrintData {
printTemplateEnable: boolean;
printTemplateHtml?: string;
processInstance: ProcessInstance;
tasks: PrintTask[];
}
}
/** 查询我的流程实例分页 */
@@ -205,3 +222,10 @@ export async function getProcessInstanceBpmnModelView(id: string) {
`/bpm/process-instance/get-bpmn-model-view?id=${id}`,
);
}
/** 获取流程实例打印数据 */
export async function getProcessInstancePrintData(id: string) {
return requestClient.get<BpmProcessInstanceApi.PrintData>(
`/bpm/process-instance/get-print-data?processInstanceId=${id}`,
);
}

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

View File

@@ -1,3 +1,5 @@
import type { Rule } from '@form-create/ant-design-vue';
import type { Ref } from 'vue';
import type { Menu } from '#/components/form-create/typing';
@@ -34,7 +36,7 @@ export function encodeFields(designerRef: any) {
// 解码表单 Fields
export function decodeFields(fields: string[]) {
const rule: object[] = [];
const rule: Rule[] = [];
fields.forEach((item) => {
rule.push(formCreate.parseJson(item));
});

View File

@@ -1,81 +0,0 @@
import type { RouteRecordRaw } from 'vue-router';
// import {
// VBEN_DOC_URL,
// VBEN_ELE_PREVIEW_URL,
// VBEN_GITHUB_URL,
// VBEN_LOGO_URL,
// VBEN_NAIVE_PREVIEW_URL,
// } from '@vben/constants';
//
// import { IFrameView } from '#/layouts';
// import { $t } from '#/locales';
const routes: RouteRecordRaw[] = [
// {
// meta: {
// badgeType: 'dot',
// icon: VBEN_LOGO_URL,
// order: 9998,
// title: $t('demos.vben.title'),
// },
// name: 'VbenProject',
// path: '/vben-admin',
// children: [
// {
// name: 'VbenDocument',
// path: '/vben-admin/document',
// component: IFrameView,
// meta: {
// icon: 'lucide:book-open-text',
// link: VBEN_DOC_URL,
// title: $t('demos.vben.document'),
// },
// },
// {
// name: 'VbenGithub',
// path: '/vben-admin/github',
// component: IFrameView,
// meta: {
// icon: 'mdi:github',
// link: VBEN_GITHUB_URL,
// title: 'Github',
// },
// },
// {
// name: 'VbenNaive',
// path: '/vben-admin/naive',
// component: IFrameView,
// meta: {
// badgeType: 'dot',
// icon: 'logos:naiveui',
// link: VBEN_NAIVE_PREVIEW_URL,
// title: $t('demos.vben.naive-ui'),
// },
// },
// {
// name: 'VbenElementPlus',
// path: '/vben-admin/ele',
// component: IFrameView,
// meta: {
// badgeType: 'dot',
// icon: 'logos:element',
// link: VBEN_ELE_PREVIEW_URL,
// title: $t('demos.vben.element-plus'),
// },
// },
// ],
// },
// {
// name: 'VbenAbout',
// path: '/vben-admin/about',
// component: () => import('#/views/_core/about/index.vue'),
// meta: {
// icon: 'lucide:copyright',
// title: $t('demos.vben.about'),
// order: 9999,
// },
// },
];
export default routes; // update by 芋艿:不展示

View File

@@ -1,2 +1,29 @@
import type { Recordable } from '@vben/types';
export * from './rangePickerProps';
export * from './routerHelper';
/**
* 查找数组对象的某个下标
* @param {Array} ary 查找的数组
* @param {Function} fn 判断的方法
*/
type Fn<T = any> = (item: T, index: number, array: Array<T>) => boolean;
export const findIndex = <T = Recordable<any>>(
ary: Array<T>,
fn: Fn<T>,
): number => {
if (ary.findIndex) {
return ary.findIndex((item, index, array) => fn(item, index, array));
}
let index = -1;
ary.some((item: T, i: number, ary: Array<T>) => {
const ret: boolean = fn(item, i, ary);
if (ret) {
index = i;
return true;
}
return false;
});
return index;
};

View File

@@ -1,4 +1,7 @@
import type { RouteLocationNormalizedLoaded } from 'vue-router';
import type {
RouteLocationNormalized,
RouteRecordNormalized,
} from 'vue-router';
import { defineAsyncComponent } from 'vue';
@@ -17,13 +20,19 @@ export function registerComponent(componentPath: string) {
}
}
export function getRawRoute(
route: RouteLocationNormalizedLoaded,
): RouteLocationNormalizedLoaded {
export const getRawRoute = (
route: RouteLocationNormalized,
): RouteLocationNormalized => {
if (!route) return route;
const { matched, ...others } = route;
const { matched, ...opt } = route;
return {
...others,
matched: matched ? matched.map((m) => ({ ...m })) : [],
...opt,
matched: (matched
? matched.map((item) => ({
meta: item.meta,
name: item.name,
path: item.path,
}))
: undefined) as RouteRecordNormalized[],
};
}
};

View File

@@ -0,0 +1,63 @@
import { message } from 'ant-design-vue';
enum UploadType {
Image = 'image',
Video = 'video',
Voice = 'voice',
}
const useBeforeUpload = (type: UploadType, maxSizeMB: number) => {
const fn = (file: File): boolean => {
let allowTypes: string[] = [];
let name = '';
switch (type) {
case UploadType.Image: {
allowTypes = [
'image/jpeg',
'image/png',
'image/gif',
'image/bmp',
'image/jpg',
];
maxSizeMB = 2;
name = '图片';
break;
}
case UploadType.Video: {
allowTypes = ['video/mp4'];
maxSizeMB = 10;
name = '视频';
break;
}
case UploadType.Voice: {
allowTypes = [
'audio/mp3',
'audio/mpeg',
'audio/wma',
'audio/wav',
'audio/amr',
];
maxSizeMB = 2;
name = '语音';
break;
}
}
// 格式不正确
if (!allowTypes.includes(file.type)) {
message.error(`上传${name}格式不对!`);
return false;
}
// 大小不正确
if (file.size / 1024 / 1024 > maxSizeMB) {
message.error(`上传${name}大小不能超过${maxSizeMB}M!`);
return false;
}
return true;
};
return fn;
};
export { UploadType, useBeforeUpload };

View File

@@ -660,16 +660,15 @@ onBeforeUnmount(() => {
<!-- <div id="js-properties-panel" class="panel"></div> -->
<!-- <div class="my-process-designer__canvas" ref="bpmn-canvas"></div> -->
</div>
<Dialog
<Modal
title="预览"
v-model:open="previewModelVisible"
width="80%"
class="max-h-[600px] w-4/5"
:scroll="true"
style="max-height: 600px"
>
<div>
<pre><code v-dompurify-html="highlightedCode(previewResult)" class="hljs"></code></pre>
</div>
</Dialog>
</Modal>
</div>
</template>

View File

@@ -42,6 +42,7 @@ const props = defineProps({
modelValue: {
type: Object,
required: true,
default: () => ({}),
},
});

View File

@@ -272,7 +272,7 @@ defineExpose({ openDrawer }); // 暴露方法给父组件
</template>
<Condition
:ref="(el) => (conditionRef[index] = el)"
:model-value="routerGroups[index] as Record<string, any>"
:model-value="routerGroups[index]"
@update:model-value="(val) => (routerGroups[index] = val)"
/>
</Card>

View File

@@ -248,9 +248,8 @@ defineExpose({ validate });
:rules="rules"
:label-col="{ span: 4 }"
:wrapper-col="{ span: 20 }"
class="mt-5"
>
<Form.Item label="流程标识" name="key" class="mb-5">
<Form.Item label="流程标识" name="key">
<div class="flex items-center">
<Input
class="w-full"
@@ -264,14 +263,11 @@ defineExpose({ validate });
"
placement="top"
>
<IconifyIcon
icon="lucide:circle-help"
class="ml-1 size-5 text-gray-900"
/>
<IconifyIcon icon="lucide:circle-help" class="ml-1 size-5" />
</Tooltip>
</div>
</Form.Item>
<Form.Item label="流程名称" name="name" class="mb-5">
<Form.Item label="流程名称" name="name">
<Input
v-model:value="modelData.name"
:disabled="!!modelData.id"
@@ -279,7 +275,7 @@ defineExpose({ validate });
placeholder="请输入流程名称"
/>
</Form.Item>
<Form.Item label="流程分类" name="category" class="mb-5">
<Form.Item label="流程分类" name="category">
<Select
class="w-full"
v-model:value="modelData.category"
@@ -295,13 +291,13 @@ defineExpose({ validate });
</Select.Option>
</Select>
</Form.Item>
<Form.Item label="流程图标" class="mb-5">
<Form.Item label="流程图标">
<ImageUpload v-model:value="modelData.icon" />
</Form.Item>
<Form.Item label="流程描述" name="description" class="mb-5">
<Form.Item label="流程描述" name="description">
<Input.TextArea v-model:value="modelData.description" allow-clear />
</Form.Item>
<Form.Item label="流程类型" name="type" class="mb-5">
<Form.Item label="流程类型" name="type">
<Radio.Group v-model:value="modelData.type">
<Radio
v-for="dict in getDictOptions(DICT_TYPE.BPM_MODEL_TYPE, 'number')"
@@ -312,7 +308,7 @@ defineExpose({ validate });
</Radio>
</Radio.Group>
</Form.Item>
<Form.Item label="是否可见" name="visible" class="mb-5">
<Form.Item label="是否可见" name="visible">
<Radio.Group v-model:value="modelData.visible">
<Radio
v-for="dict in getDictOptions(
@@ -326,7 +322,7 @@ defineExpose({ validate });
</Radio>
</Radio.Group>
</Form.Item>
<Form.Item label="谁可以发起" name="startUserType" class="mb-5">
<Form.Item label="谁可以发起" name="startUserType">
<Select
v-model:value="modelData.startUserType"
placeholder="请选择谁可以发起"
@@ -343,15 +339,10 @@ defineExpose({ validate });
<div
v-for="user in selectedStartUsers"
:key="user.id"
class="relative flex h-9 items-center rounded-full bg-gray-100 pr-2 hover:bg-gray-200 dark:border dark:border-gray-500 dark:bg-gray-700 dark:hover:bg-gray-600"
class="relative flex h-8 items-center rounded-lg bg-gray-100 pr-2 hover:bg-gray-200 dark:border dark:border-gray-500 dark:bg-gray-700 dark:hover:bg-gray-600"
>
<Avatar
class="m-1"
:size="28"
v-if="user.avatar"
:src="user.avatar"
/>
<Avatar class="m-1" :size="28" v-else>
<Avatar class="m-1 size-7" v-if="user.avatar" :src="user.avatar" />
<Avatar class="m-1 size-7" v-else>
{{ user.nickname?.substring(0, 1) }}
</Avatar>
<span class="text-gray-700 dark:text-gray-200">
@@ -359,7 +350,7 @@ defineExpose({ validate });
</span>
<IconifyIcon
icon="lucide:x"
class="ml-2 size-4 cursor-pointer text-gray-400 hover:text-red-500"
class="ml-2 size-4 cursor-pointer text-gray-400 hover:text-red-500 dark:text-gray-200"
@click="handleRemoveStartUser(user)"
/>
</div>
@@ -381,7 +372,7 @@ defineExpose({ validate });
<div
v-for="dept in selectedStartDepts"
:key="dept.id"
class="relative flex h-9 items-center rounded-full bg-gray-100 pr-2 shadow-sm hover:bg-gray-200 dark:border dark:border-gray-500 dark:bg-gray-700 dark:hover:bg-gray-600"
class="relative flex h-8 items-center rounded-lg bg-gray-100 pr-2 shadow-sm hover:bg-gray-200 dark:border dark:border-gray-500 dark:bg-gray-700 dark:hover:bg-gray-600"
>
<IconifyIcon icon="lucide:building" class="size-6 px-1" />
<span class="text-gray-700 dark:text-gray-200">
@@ -405,20 +396,15 @@ defineExpose({ validate });
</Button>
</div>
</Form.Item>
<Form.Item label="流程管理员" name="managerUserIds" class="mb-5">
<Form.Item label="流程管理员" name="managerUserIds">
<div class="flex flex-wrap gap-1">
<div
v-for="user in selectedManagerUsers"
:key="user.id"
class="relative flex h-9 items-center rounded-full bg-gray-100 pr-2 hover:bg-gray-200 dark:border dark:border-gray-500 dark:bg-gray-700 dark:hover:bg-gray-600"
>
<Avatar
class="m-1"
:size="28"
v-if="user.avatar"
:src="user.avatar"
/>
<Avatar class="m-1" :size="28" v-else>
<Avatar class="m-1 size-7" v-if="user.avatar" :src="user.avatar" />
<Avatar class="m-1 size-7" v-else>
{{ user.nickname?.substring(0, 1) }}
</Avatar>
<span class="text-gray-700 dark:text-gray-200">

View File

@@ -515,5 +515,6 @@ defineExpose({ initData, validate });
</Col>
</Row>
</FormItem>
<!-- TODO @jason这里有个 自定义打印模板 -->
</Form>
</template>

View File

@@ -4,7 +4,7 @@ import type { SystemUserApi } from '#/api/system/user';
import { nextTick, onMounted, ref, shallowRef, watch } from 'vue';
import { Page } from '@vben/common-ui';
import { Page, useVbenModal } from '@vben/common-ui';
import {
BpmFieldPermissionType,
BpmModelFormType,
@@ -13,6 +13,7 @@ import {
DICT_TYPE,
} from '@vben/constants';
import {
IconifyIcon,
SvgBpmApproveIcon,
SvgBpmCancelIcon,
SvgBpmRejectIcon,
@@ -33,6 +34,7 @@ import { registerComponent } from '#/utils';
import ProcessInstanceBpmnViewer from './modules/bpm-viewer.vue';
import ProcessInstanceOperationButton from './modules/operation-button.vue';
import ProcessssPrint from './modules/processs-print.vue';
import ProcessInstanceSimpleViewer from './modules/simple-bpm-viewer.vue';
import BpmProcessInstanceTaskList from './modules/task-list.vue';
import ProcessInstanceTimeline from './modules/time-line.vue';
@@ -189,6 +191,16 @@ const refresh = () => {
getDetail();
};
const [PrintModal, printModalApi] = useVbenModal({
connectedComponent: ProcessssPrint,
destroyOnClose: true,
});
/** 打开打印对话框 */
function handlePrint() {
printModalApi.setData({ processInstanceId: props.id }).open();
}
/** 监听 Tab 切换,当切换到 "record" 标签时刷新任务列表 */
watch(
() => activeTab.value,
@@ -218,7 +230,14 @@ onMounted(async () => {
}"
>
<template #title>
<span class="text-gray-500">编号{{ id || '-' }}</span>
<div class="flex items-center gap-4">
<span class="text-gray-500">编号{{ id || '-' }}</span>
<IconifyIcon
icon="lucide:printer"
class="hover:text-primary cursor-pointer"
@click="handlePrint"
/>
</div>
</template>
<div class="flex h-full flex-col">
@@ -371,6 +390,8 @@ onMounted(async () => {
</div>
</template>
</Card>
<!-- 打印对话框 -->
<PrintModal />
</Page>
</template>

View File

@@ -0,0 +1,315 @@
<script setup lang="ts">
import type { BpmProcessInstanceApi } from '#/api/bpm/processInstance';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { DICT_TYPE } from '@vben/constants';
import { getDictLabel } from '@vben/hooks';
import { useUserStore } from '@vben/stores';
import { formatDate } from '@vben/utils';
import { Button } from 'ant-design-vue';
// @ts-ignore - 安装 vue3-print-nb 局部指令 v-print
import vPrint from 'vue3-print-nb';
import { getProcessInstancePrintData } from '#/api/bpm/processInstance';
import { decodeFields } from '#/components/form-create';
const userStore = useUserStore();
const printData = ref<BpmProcessInstanceApi.PrintData>();
const userName = computed(() => userStore.userInfo?.nickname ?? '');
const printTime = ref(formatDate(new Date(), 'YYYY-MM-DD HH:mm'));
const formFields = ref<any[]>([]);
const printDataMap = ref<Record<string, any>>({});
/** 打印配置 */
const printObj = ref({
id: 'printDivTag',
popTitle: '&nbsp;',
extraCss: '/print.css',
extraHead: '',
zIndex: 20_003,
});
const [Modal, modalApi] = useVbenModal({
closable: true,
footer: false,
title: '打印流程',
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
return;
}
modalApi.lock();
try {
const { processInstanceId } = modalApi.getData<{
processInstanceId: string;
}>();
if (processInstanceId) {
await fetchPrintData(processInstanceId);
}
} finally {
modalApi.unlock();
}
},
});
/** 获取打印数据 */
async function fetchPrintData(id: string) {
printData.value = await getProcessInstancePrintData(id);
initPrintDataMap();
parseFormFields();
}
/** 解析表单字段 */
function parseFormFields() {
if (!printData.value) return;
const formFieldsObj = decodeFields(
printData.value.processInstance.processDefinition?.formFields || [],
);
const processVariables = printData.value.processInstance.formVariables;
const res: any = [];
for (const item of formFieldsObj) {
const id = item.field;
const name = item.title;
const fieldKey = item.field as string;
const variable = processVariables[fieldKey];
let html = variable;
switch (item.type) {
case 'checkbox':
case 'radio':
case 'select': {
const options = item.options;
const temp: any = [];
if (Array.isArray(options)) {
if (Array.isArray(variable)) {
const labels = options
.filter((o: any) => variable.includes(o.value))
.map((o: any) => o.label);
temp.push(...labels);
} else {
const opt = options.find((o: any) => o.value === variable);
if (opt) {
temp.push(opt.label);
}
}
}
html = temp.join(',');
break;
}
case 'UploadImg': {
const imgEl = document.createElement('img');
imgEl.setAttribute('src', variable);
imgEl.setAttribute('style', 'max-width: 600px;');
html = imgEl.outerHTML;
break;
}
// TODO 更多表单打印展示
}
printDataMap.value[fieldKey] = html;
res.push({ id, name, html });
}
formFields.value = res;
}
/** 初始化打印数据映射 */
function initPrintDataMap() {
if (!printData.value) return;
printDataMap.value.startUser =
printData.value.processInstance.startUser?.nickname || '';
printDataMap.value.startUserDept =
printData.value.processInstance.startUser?.deptName || '';
printDataMap.value.processName = printData.value.processInstance.name;
printDataMap.value.processNum = printData.value.processInstance.id;
printDataMap.value.startTime = formatDate(
printData.value.processInstance.startTime,
);
printDataMap.value.endTime = formatDate(
printData.value.processInstance.endTime,
);
printDataMap.value.processStatus = getDictLabel(
DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS,
printData.value.processInstance.status,
);
printDataMap.value.printUser = userName.value;
printDataMap.value.printTime = printTime.value;
}
/** 获取打印模板 HTML TODO 需求实现配置打印模板) */
function getPrintTemplateHTML() {
if (!printData.value?.printTemplateHtml) return '';
const parser = new DOMParser();
const doc = parser.parseFromString(
printData.value.printTemplateHtml,
'text/html',
);
// table 添加 border
const tables = doc.querySelectorAll('table');
tables.forEach((item) => {
item.setAttribute('border', '1');
item.setAttribute(
'style',
`${item.getAttribute('style') || ''}border-collapse:collapse;`,
);
});
// 替换 mentions
const mentions = doc.querySelectorAll('[data-w-e-type="mention"]');
mentions.forEach((item) => {
const htmlElement = item as HTMLElement;
const mentionId = JSON.parse(
decodeURIComponent(htmlElement.dataset.info ?? ''),
).id;
item.innerHTML = printDataMap.value[mentionId] ?? '';
});
// 替换流程记录
const processRecords = doc.querySelectorAll(
'[data-w-e-type="process-record"]',
);
const processRecordTable: Element = document.createElement('table');
if (processRecords.length > 0) {
// 构建流程记录 html
processRecordTable.setAttribute('border', '1');
processRecordTable.setAttribute(
'style',
'width:100%;border-collapse:collapse;',
);
const headTr = document.createElement('tr');
const headTd = document.createElement('td');
headTd.setAttribute('colspan', '2');
headTd.setAttribute('width', 'auto');
headTd.setAttribute('style', 'text-align: center;');
headTd.innerHTML = '流程节点';
headTr.append(headTd);
processRecordTable.append(headTr);
printData.value?.tasks.forEach((item) => {
const tr = document.createElement('tr');
const td1 = document.createElement('td');
td1.innerHTML = item.name;
const td2 = document.createElement('td');
td2.innerHTML = item.description;
tr.append(td1);
tr.append(td2);
processRecordTable.append(tr);
});
}
processRecords.forEach((item) => {
item.innerHTML = processRecordTable.outerHTML;
});
// 返回 html
return doc.body.innerHTML;
}
</script>
<template>
<Modal class="w-2/3">
<div id="printDivTag" class="break-all">
<!-- eslint-disable vue/no-v-html 使用自定义打印模板 -->
<div
v-if="printData?.printTemplateEnable"
v-html="getPrintTemplateHTML()"
></div>
<div v-else-if="printData">
<h2 class="mb-3 text-center text-xl font-bold">
{{ printData.processInstance.name }}
</h2>
<div class="mb-2 text-right text-sm">
{{ `打印人员: ${userName}` }}
</div>
<div class="mb-2 flex justify-between text-sm">
<div>
{{ `流程编号: ${printData.processInstance.id}` }}
</div>
<div>{{ `打印时间: ${printTime}` }}</div>
</div>
<table class="mt-3 w-full border-collapse border border-gray-400">
<tbody>
<tr>
<td class="w-1/4 border border-gray-400 p-1.5">发起人</td>
<td class="w-1/4 border border-gray-400 p-1.5">
{{ printData.processInstance.startUser?.nickname }}
</td>
<td class="w-1/4 border border-gray-400 p-1.5">发起时间</td>
<td class="w-1/4 border border-gray-400 p-1.5">
<!-- TODO @jason这里会告警呢 -->
{{ formatDate(printData.processInstance.startTime) }}
</td>
</tr>
<tr>
<td class="w-1/4 border border-gray-400 p-1.5">所属部门</td>
<td class="w-1/4 border border-gray-400 p-1.5">
{{ printData.processInstance.startUser?.deptName }}
</td>
<td class="w-1/4 border border-gray-400 p-1.5">流程状态</td>
<td class="w-1/4 border border-gray-400 p-1.5">
{{
getDictLabel(
DICT_TYPE.BPM_PROCESS_INSTANCE_STATUS,
printData.processInstance.status,
)
}}
</td>
</tr>
<tr>
<td
class="w-full border border-gray-400 p-1.5 text-center"
colspan="4"
>
<h4>表单内容</h4>
</td>
</tr>
<tr v-for="item in formFields" :key="item.id">
<td class="w-1/5 border border-gray-400 p-1.5">
{{ item.name }}
</td>
<td class="w-4/5 border border-gray-400 p-1.5" colspan="3">
<div v-html="item.html"></div>
</td>
</tr>
<tr>
<td
class="w-full border border-gray-400 p-1.5 text-center"
colspan="4"
>
<h4>流程节点</h4>
</td>
</tr>
<tr v-for="item in printData.tasks" :key="item.id">
<td class="w-1/5 border border-gray-400 p-1.5">
{{ item.name }}
</td>
<td class="w-4/5 border border-gray-400 p-1.5" colspan="3">
{{ item.description }}
<div v-if="item.signPicUrl && item.signPicUrl.length > 0">
<img class="h-10 w-[90px]" :src="item.signPicUrl" alt="" />
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<template #footer>
<div class="flex justify-end gap-2">
<Button @click="modalApi.close()"> </Button>
<Button v-print="printObj" type="primary"> </Button>
</div>
</template>
</Modal>
</template>

View File

@@ -197,6 +197,27 @@ const emptyMessage = computed(() => {
}
});
// 计算属性:无配置消息
// const noConfigMessage = computed(() => {
// switch (props.type) {
// case JsonParamsInputTypeEnum.CUSTOM: {
// return JSON_PARAMS_INPUT_CONSTANTS.NO_CONFIG_MESSAGES.CUSTOM;
// }
// case JsonParamsInputTypeEnum.EVENT: {
// return JSON_PARAMS_INPUT_CONSTANTS.NO_CONFIG_MESSAGES.EVENT;
// }
// case JsonParamsInputTypeEnum.PROPERTY: {
// return JSON_PARAMS_INPUT_CONSTANTS.NO_CONFIG_MESSAGES.PROPERTY;
// }
// case JsonParamsInputTypeEnum.SERVICE: {
// return JSON_PARAMS_INPUT_CONSTANTS.NO_CONFIG_MESSAGES.SERVICE;
// }
// default: {
// return JSON_PARAMS_INPUT_CONSTANTS.NO_CONFIG_MESSAGES.DEFAULT;
// }
// }
// });
/**
* 处理参数变化事件
*/

View File

@@ -0,0 +1 @@
export { default as ProductCategorySelect } from './select.vue';

View File

@@ -11,26 +11,25 @@ import { getCategoryList } from '#/api/mall/product/category';
defineOptions({ name: 'ProductCategorySelect' });
const props = defineProps({
// ID
modelValue: {
type: [Number, Array<Number>],
default: undefined,
},
//
}, // ID
multiple: {
type: Boolean,
default: false,
},
//
}, //
parentId: {
type: Number,
default: undefined,
},
}, //
});
/** 分类选择 */
const emit = defineEmits(['update:modelValue']);
const categoryList = ref<any[]>([]); //
/** 选中的分类 ID */
const selectCategoryId = computed({
get: () => {
@@ -42,7 +41,6 @@ const selectCategoryId = computed({
});
/** 初始化 */
const categoryList = ref<any[]>([]); //
onMounted(async () => {
const data = await getCategoryList({
parentId: props.parentId,
@@ -61,7 +59,7 @@ onMounted(async () => {
}"
:multiple="multiple"
:tree-checkable="multiple"
class="w-1/1"
class="w-full"
placeholder="请选择商品分类"
allow-clear
tree-default-expand-all

View File

@@ -0,0 +1,2 @@
export { default as CombinationShowcase } from './showcase.vue';

View File

@@ -0,0 +1,146 @@
<!-- 拼团活动橱窗组件用于展示和选择拼团活动 -->
<script lang="ts" setup>
import type { MallCombinationActivityApi } from '#/api/mall/promotion/combination/combinationActivity';
import { computed, ref, watch } from 'vue';
import { CloseCircleFilled, PlusOutlined } from '@vben/icons';
import { Image, Tooltip } from 'ant-design-vue';
import { getCombinationActivityListByIds } from '#/api/mall/promotion/combination/combinationActivity';
import CombinationTableSelect from './table-select.vue';
interface CombinationShowcaseProps {
modelValue?: number | number[];
limit?: number;
disabled?: boolean;
}
const props = withDefaults(defineProps<CombinationShowcaseProps>(), {
modelValue: undefined,
limit: Number.MAX_VALUE,
disabled: false,
});
const emit = defineEmits(['update:modelValue', 'change']);
const activityList = ref<MallCombinationActivityApi.CombinationActivity[]>([]); // 已选择的活动列表
const combinationTableSelectRef =
ref<InstanceType<typeof CombinationTableSelect>>(); // 活动选择表格组件引用
const isMultiple = computed(() => props.limit !== 1); // 是否为多选模式
/** 计算是否可以添加 */
const canAdd = computed(() => {
if (props.disabled) {
return false;
}
if (!props.limit) {
return true;
}
return activityList.value.length < props.limit;
});
/** 监听 modelValue 变化,加载活动详情 */
watch(
() => props.modelValue,
async (newValue) => {
// eslint-disable-next-line unicorn/no-nested-ternary
const ids = Array.isArray(newValue) ? newValue : newValue ? [newValue] : [];
if (ids.length === 0) {
activityList.value = [];
return;
}
// 只有活动发生变化时才重新查询
if (
activityList.value.length === 0 ||
activityList.value.some((activity) => !ids.includes(activity.id!))
) {
activityList.value = await getCombinationActivityListByIds(ids);
}
},
{ immediate: true },
);
/** 打开活动选择对话框 */
function handleOpenActivitySelect() {
combinationTableSelectRef.value?.open(activityList.value);
}
/** 选择活动后触发 */
function handleActivitySelected(
activities:
| MallCombinationActivityApi.CombinationActivity
| MallCombinationActivityApi.CombinationActivity[],
) {
activityList.value = Array.isArray(activities) ? activities : [activities];
emitActivityChange();
}
/** 删除活动 */
function handleRemoveActivity(index: number) {
activityList.value.splice(index, 1);
emitActivityChange();
}
/** 触发变更事件 */
function emitActivityChange() {
if (props.limit === 1) {
const activity =
activityList.value.length > 0 ? activityList.value[0] : null;
emit('update:modelValue', activity?.id || 0);
emit('change', activity);
} else {
emit(
'update:modelValue',
activityList.value.map((activity) => activity.id!),
);
emit('change', activityList.value);
}
}
</script>
<template>
<div class="flex flex-wrap items-center gap-2">
<!-- 已选活动列表 -->
<div
v-for="(activity, index) in activityList"
:key="activity.id"
class="group relative h-[60px] w-[60px] overflow-hidden rounded-lg"
>
<Tooltip :title="activity.name">
<div class="relative h-full w-full">
<Image
:src="activity.picUrl"
class="h-full w-full rounded-lg object-cover"
/>
<!-- 删除按钮 -->
<CloseCircleFilled
v-if="!disabled"
class="absolute -right-2 -top-2 cursor-pointer text-xl text-red-500 opacity-0 transition-opacity hover:text-red-600 group-hover:opacity-100"
@click="handleRemoveActivity(index)"
/>
</div>
</Tooltip>
</div>
<!-- 添加活动按钮 -->
<Tooltip v-if="canAdd" title="选择活动">
<div
class="hover:border-primary hover:bg-primary/5 flex h-[60px] w-[60px] cursor-pointer items-center justify-center rounded-lg border-2 border-dashed transition-colors"
@click="handleOpenActivitySelect"
>
<PlusOutlined class="text-xl text-gray-400" />
</div>
</Tooltip>
</div>
<!-- 活动选择对话框 -->
<CombinationTableSelect
ref="combinationTableSelectRef"
:multiple="isMultiple"
@change="handleActivitySelected"
/>
</template>

View File

@@ -0,0 +1,285 @@
<!-- 拼团活动选择弹窗组件 -->
<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { MallCategoryApi } from '#/api/mall/product/category';
import type { MallCombinationActivityApi } from '#/api/mall/promotion/combination/combinationActivity';
import { computed, onMounted, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { fenToYuan, formatDate, handleTree } from '@vben/utils';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getCategoryList } from '#/api/mall/product/category';
import { getCombinationActivityPage } from '#/api/mall/promotion/combination/combinationActivity';
interface CombinationTableSelectProps {
multiple?: boolean; // 是否多选true - checkboxfalse - radio
}
const props = withDefaults(defineProps<CombinationTableSelectProps>(), {
multiple: false,
});
const emit = defineEmits<{
change: [
activity:
| MallCombinationActivityApi.CombinationActivity
| MallCombinationActivityApi.CombinationActivity[],
];
}>();
const categoryList = ref<MallCategoryApi.Category[]>([]); // 分类列表
const categoryTreeList = ref<any[]>([]); // 分类树
/** 单选:处理选中变化 */
function handleRadioChange() {
const selectedRow =
gridApi.grid.getRadioRecord() as MallCombinationActivityApi.CombinationActivity;
if (selectedRow) {
emit('change', selectedRow);
modalApi.close();
}
}
/**
* 格式化拼团价格
* @param products
*/
const formatCombinationPrice = (
products: MallCombinationActivityApi.CombinationProduct[],
) => {
if (!products || products.length === 0) return '-';
const combinationPrice = Math.min(
...products.map((item) => item.combinationPrice || 0),
);
return `${fenToYuan(combinationPrice)}`;
};
/** 搜索表单 Schema */
const formSchema = computed<VbenFormSchema[]>(() => [
{
fieldName: 'name',
label: '活动名称',
component: 'Input',
componentProps: {
placeholder: '请输入活动名称',
clearable: true,
},
},
{
fieldName: 'status',
label: '活动状态',
component: 'Select',
componentProps: {
placeholder: '请选择活动状态',
clearable: true,
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
},
},
]);
/** 表格列配置 */
const gridColumns = computed<VxeGridProps['columns']>(() => {
const columns: VxeGridProps['columns'] = [];
if (props.multiple) {
columns.push({ type: 'checkbox', width: 55 });
} else {
columns.push({ type: 'radio', width: 55 });
}
columns.push(
{
field: 'id',
title: '活动编号',
minWidth: 80,
},
{
field: 'name',
title: '活动名称',
minWidth: 140,
},
{
field: 'activityTime',
title: '活动时间',
minWidth: 210,
formatter: ({ row }) => {
return `${formatDate(row.startTime, 'YYYY-MM-DD')} ~ ${formatDate(row.endTime, 'YYYY-MM-DD')}`;
},
},
{
field: 'picUrl',
title: '商品图片',
width: 100,
cellRender: {
name: 'CellImage',
},
},
{
field: 'spuName',
title: '商品标题',
minWidth: 300,
},
{
field: 'marketPrice',
title: '原价',
minWidth: 100,
formatter: ({ cellValue }) => {
return cellValue ? `${fenToYuan(cellValue)}` : '-';
},
},
{
field: 'products',
title: '拼团价',
minWidth: 100,
formatter: ({ cellValue }) => {
return formatCombinationPrice(cellValue);
},
},
{
field: 'groupCount',
title: '开团组数',
minWidth: 100,
},
{
field: 'groupSuccessCount',
title: '成团组数',
minWidth: 100,
},
{
field: 'recordCount',
title: '购买次数',
minWidth: 100,
},
{
field: 'status',
title: '活动状态',
minWidth: 100,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.COMMON_STATUS },
},
},
{
field: 'createTime',
title: '创建时间',
width: 180,
formatter: 'formatDateTime',
},
);
return columns;
});
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: formSchema.value,
layout: 'horizontal',
collapsed: false,
},
gridOptions: {
columns: gridColumns.value,
height: 500,
border: true,
checkboxConfig: {
reserve: true,
},
radioConfig: {
reserve: true,
},
rowConfig: {
keyField: 'id',
isHover: true,
},
proxyConfig: {
ajax: {
async query({ page }: any, formValues: any) {
return await getCombinationActivityPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
},
gridEvents: {
radioChange: handleRadioChange,
},
});
const [Modal, modalApi] = useVbenModal({
destroyOnClose: true,
showConfirmButton: props.multiple, // 特殊radio 单选情况下,走 handleRadioChange 处理。
onConfirm: () => {
const selectedRows =
gridApi.grid.getCheckboxRecords() as MallCombinationActivityApi.CombinationActivity[];
emit('change', selectedRows);
modalApi.close();
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
gridApi.grid.clearCheckboxRow();
gridApi.grid.clearRadioRow();
return;
}
// 1. 先查询数据
await gridApi.query();
// 2. 设置已选中行
const data = modalApi.getData<
| MallCombinationActivityApi.CombinationActivity
| MallCombinationActivityApi.CombinationActivity[]
>();
if (props.multiple && Array.isArray(data) && data.length > 0) {
setTimeout(() => {
const tableData = gridApi.grid.getTableData().fullData;
data.forEach((activity) => {
const row = tableData.find(
(item: MallCombinationActivityApi.CombinationActivity) =>
item.id === activity.id,
);
if (row) {
gridApi.grid.setCheckboxRow(row, true);
}
});
}, 300);
} else if (!props.multiple && data && !Array.isArray(data)) {
setTimeout(() => {
const tableData = gridApi.grid.getTableData().fullData;
const row = tableData.find(
(item: MallCombinationActivityApi.CombinationActivity) =>
item.id === data.id,
);
if (row) {
gridApi.grid.setRadioRow(row);
}
}, 300);
}
},
});
/** 对外暴露的方法 */
defineExpose({
open: (
data?:
| MallCombinationActivityApi.CombinationActivity
| MallCombinationActivityApi.CombinationActivity[],
) => {
modalApi.setData(data).open();
},
});
/** 初始化分类数据 */
onMounted(async () => {
categoryList.value = await getCategoryList({});
categoryTreeList.value = handleTree(categoryList.value, 'id', 'parentId');
});
</script>
<template>
<Modal title="选择活动" class="w-[950px]">
<Grid />
</Modal>
</template>

View File

@@ -3,7 +3,7 @@ import { ref, watch } from 'vue';
import { Button, Input } from 'ant-design-vue';
import AppLinkSelectDialog from './app-link-select-dialog.vue';
import AppLinkSelectDialog from './select-dialog.vue';
/** APP 链接输入框 */
defineOptions({ name: 'AppLinkInput' });
@@ -56,5 +56,6 @@ watch(
</Button>
</template>
</Input>
<AppLinkSelectDialog ref="dialogRef" @change="handleLinkSelected" />
</template>

View File

@@ -3,11 +3,12 @@ import type { AppLink } from './data';
import { nextTick, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { getUrlNumberValue } from '@vben/utils';
import { Button, Form, FormItem, Modal, Tooltip } from 'ant-design-vue';
import { Button, Form, FormItem, Tooltip } from 'ant-design-vue';
import ProductCategorySelect from '#/views/mall/product/category/components/product-category-select.vue';
import { ProductCategorySelect } from '#/views/mall/product/category/components/';
import { APP_LINK_GROUP_LIST, APP_LINK_TYPE_ENUM } from './data';
@@ -30,21 +31,31 @@ const groupBtnRefs = ref<HTMLButtonElement[]>([]); // 分组引用列表
const detailSelectDialog = ref<{
id?: number;
type?: APP_LINK_TYPE_ENUM;
visible: boolean;
}>({
visible: false,
id: undefined,
type: undefined,
}); //
const dialogVisible = ref(false);
const [Modal, modalApi] = useVbenModal({
onConfirm() {
emit('change', activeAppLink.value.path);
emit('appLinkChange', activeAppLink.value);
modalApi.close();
},
});
const [DetailSelectModal, detailSelectModalApi] = useVbenModal({
onConfirm() {
detailSelectModalApi.close();
},
});
defineExpose({ open });
/** 打开弹窗 */
async function open(link: string) {
activeAppLink.value.path = link;
dialogVisible.value = true;
modalApi.open();
//
const group = APP_LINK_GROUP_LIST.find((group) =>
group.links.some((linkItem) => {
@@ -76,7 +87,7 @@ function handleAppLinkSelected(appLink: AppLink) {
'id',
`http://127.0.0.1${activeAppLink.value.path}`,
) || undefined;
detailSelectDialog.value.visible = true;
detailSelectModalApi.open();
break;
}
default: {
@@ -85,13 +96,6 @@ function handleAppLinkSelected(appLink: AppLink) {
}
}
/** 处理确认提交 */
function handleSubmit() {
emit('change', activeAppLink.value.path);
emit('appLinkChange', activeAppLink.value);
dialogVisible.value = false;
}
/**
* 处理右侧链接列表滚动
*
@@ -138,7 +142,7 @@ function scrollToGroupBtn(group: string) {
/** 是否为相同的链接(不比较参数,只比较链接) */
function isSameLink(link1: string, link2: string) {
return link2 ? link1.split('?')[0] === link2.split('?')[0] : false;
return link2 ? link1?.split('?')[0] === link2.split('?')[0] : false;
}
/** 处理详情选择 */
@@ -149,17 +153,12 @@ function handleProductCategorySelected(id: number) {
activeAppLink.value.path = `${url.pathname}${url.search}`;
// id
detailSelectDialog.value.visible = false;
detailSelectModalApi.close();
detailSelectDialog.value.id = undefined;
}
</script>
<template>
<Modal
v-model:open="dialogVisible"
title="选择链接"
width="65%"
@ok="handleSubmit"
>
<Modal title="选择链接" class="w-[65%]">
<div class="flex h-[500px] gap-2">
<!-- 左侧分组列表 -->
<div
@@ -218,7 +217,7 @@ function handleProductCategorySelected(id: number) {
</div>
</Modal>
<Modal v-model:open="detailSelectDialog.visible" title="选择分类" width="65%">
<DetailSelectModal title="选择分类" class="w-[65%]">
<Form class="min-h-[200px]">
<FormItem
label="选择分类"
@@ -233,11 +232,5 @@ function handleProductCategorySelected(id: number) {
/>
</FormItem>
</Form>
</Modal>
</DetailSelectModal>
</template>
<style lang="scss" scoped>
:deep(.ant-btn + .ant-btn) {
margin-left: 0 !important;
}
</style>

View File

@@ -133,6 +133,7 @@ function handleSliderChange(prop: string) {
</TabPane>
<!-- 每个组件的通用内容 -->
<!-- TODO @xingyu这里的样式貌似没 ele 版本的好看 -->
<TabPane tab="样式" key="style" force-render>
<p class="text-lg font-bold">组件样式</p>
<div class="flex flex-col gap-2 rounded-md p-4 shadow-lg">
@@ -159,6 +160,7 @@ function handleSliderChange(prop: string) {
<template #tip>建议宽度 750px</template>
</UploadImg>
</FormItem>
<!-- TODO @xingyu没完全对齐 -->
<Tree :tree-data="treeData" default-expand-all :block-node="true">
<template #title="{ dataRef }">
<FormItem

View File

@@ -49,6 +49,7 @@ const emits = defineEmits<{
type DiyComponentWithStyle = DiyComponent<any> & {
property: { style?: ComponentStyle };
};
/** 组件样式 */
const style = computed(() => {
const componentStyle = props.component.property.style;
@@ -108,6 +109,8 @@ const handleDeleteComponent = () => {
class="component-toolbar"
v-if="showToolbar && component.name && active"
>
<!-- TODO @xingyu按钮少的时候会存在遮住的情况 -->
<!-- TODO @xingyu貌似中间的选中框框没全部框柱上面多了点下面少了点 -->
<VerticalButtonGroup size="small">
<Button
:disabled="!canMoveUp"

View File

@@ -19,6 +19,7 @@ const props = defineProps<{
list: DiyComponentLibrary[];
}>();
// TODO @xingyu要不要换成 reactive和 ele 一致
const groups = ref<any[]>([]); // 组件分组
const extendGroups = ref<string[]>([]); // 展开的折叠面板
@@ -99,4 +100,5 @@ function handleCloneComponent(component: DiyComponent<any>) {
</Collapse.Panel>
</Collapse>
</div>
<!-- TODO @xingyuele 里面有一些 style看看是不是都迁移完了特别是 drag-area 是全局样式 -->
</template>

View File

@@ -1,53 +0,0 @@
<script setup lang="ts">
import type { CarouselProperty } from './config';
import { ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { Carousel, Image } from 'ant-design-vue';
/** 轮播图 */
defineOptions({ name: 'Carousel' });
defineProps<{ property: CarouselProperty }>();
const currentIndex = ref(0);
const handleIndexChange = (index: number) => {
currentIndex.value = index + 1;
};
</script>
<template>
<div>
<!-- 无图片 -->
<div
class="bg-card flex h-64 items-center justify-center"
v-if="property.items.length === 0"
>
<IconifyIcon icon="tdesign:image" class="size-6 text-gray-800" />
</div>
<div v-else class="relative">
<Carousel
:autoplay="property.autoplay"
:autoplay-speed="property.interval * 1000"
:dots="property.indicator !== 'number'"
@change="handleIndexChange"
class="h-44"
>
<div v-for="(item, index) in property.items" :key="index">
<Image
class="h-full w-full object-cover"
:src="item.imgUrl"
:preview="false"
/>
</div>
</Carousel>
<div
v-if="property.indicator === 'number'"
class="absolute bottom-2.5 right-2.5 rounded-xl bg-black px-2 py-1 text-xs text-white opacity-40"
>
{{ currentIndex }} / {{ property.items.length }}
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,56 @@
<script setup lang="ts">
import type { CarouselProperty } from './config';
import { ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { Carousel, Image } from 'ant-design-vue';
/** 轮播图 */
defineOptions({ name: 'Carousel' });
defineProps<{ property: CarouselProperty }>();
const currentIndex = ref(0); // 当前索引
/** 处理索引变化 */
const handleIndexChange = (index: number) => {
currentIndex.value = index + 1;
};
</script>
<template>
<!-- 无图片 -->
<div
class="flex items-center justify-center bg-gray-300"
:style="{
height: property.items.length === 0 ? '250px' : `${property.height}px`,
}"
v-if="property.items.length === 0"
>
<IconifyIcon icon="tdesign:image" class="text-[120px] text-gray-800" />
</div>
<div v-else class="relative">
<Carousel
:autoplay="property.autoplay"
:autoplay-speed="property.interval * 1000"
:dots="property.indicator !== 'number'"
@change="handleIndexChange"
:style="{ height: `${property.height}px` }"
>
<div v-for="(item, index) in property.items" :key="index">
<Image
class="h-full w-full object-cover"
:src="item.imgUrl"
:preview="false"
/>
</div>
</Carousel>
<div
v-if="property.indicator === 'number'"
class="absolute bottom-[10px] right-[10px] rounded-xl bg-black px-[8px] py-[2px] text-[10px] text-white opacity-40"
>
{{ currentIndex }} / {{ property.items.length }}
</div>
</div>
</template>

View File

@@ -7,6 +7,7 @@ import { useVModel } from '@vueuse/core';
import {
Form,
FormItem,
InputNumber,
Radio,
RadioButton,
RadioGroup,
@@ -21,11 +22,13 @@ import { AppLinkInput, Draggable } from '#/views/mall/promotion/components';
import ComponentContainerProperty from '../../component-container-property.vue';
//
/** 轮播图属性面板 */
defineOptions({ name: 'CarouselProperty' });
const props = defineProps<{ modelValue: CarouselProperty }>();
const emit = defineEmits(['update:modelValue']);
const formData = useVModel(props, 'modelValue', emit);
</script>
@@ -35,7 +38,7 @@ const formData = useVModel(props, 'modelValue', emit);
<p class="text-base font-bold">样式设置</p>
<div class="flex flex-col gap-2 rounded-md p-4 shadow-lg">
<FormItem label="样式" prop="type">
<RadioGroup v-model="formData.type">
<RadioGroup v-model:value="formData.type">
<Tooltip class="item" content="默认" placement="bottom">
<RadioButton value="default">
<IconifyIcon icon="system-uicons:carousel" class="size-6" />
@@ -48,18 +51,26 @@ const formData = useVModel(props, 'modelValue', emit);
</Tooltip>
</RadioGroup>
</FormItem>
<FormItem label="高度" prop="height">
<InputNumber
v-model:value="formData.height"
class="mr-[10px] !w-1/2"
controls-position="right"
/>
px
</FormItem>
<FormItem label="指示器" prop="indicator">
<RadioGroup v-model="formData.indicator">
<RadioGroup v-model:value="formData.indicator">
<Radio value="dot">小圆点</Radio>
<Radio value="number">数字</Radio>
</RadioGroup>
</FormItem>
<FormItem label="是否轮播" prop="autoplay">
<Switch v-model="formData.autoplay" />
<Switch v-model:checked="formData.autoplay" />
</FormItem>
<FormItem label="播放间隔" prop="interval" v-if="formData.autoplay">
<Slider
v-model="formData.interval"
v-model:value="formData.interval"
:max="10"
:min="0.5"
:step="0.5"
@@ -75,7 +86,7 @@ const formData = useVModel(props, 'modelValue', emit);
<Draggable v-model="formData.items" :empty-item="{ type: 'img' }">
<template #default="{ element }">
<FormItem label="类型" prop="type" class="mb-2" label-width="40px">
<RadioGroup v-model="element.type">
<RadioGroup v-model:value="element.type">
<Radio value="img">图片</Radio>
<Radio value="video">视频</Radio>
</RadioGroup>

View File

@@ -1,4 +1,87 @@
// 导出所有优惠券相关组件
export { CouponDiscount } from './coupon-discount';
export { CouponDiscountDesc } from './coupon-discount-desc';
export { CouponValidTerm } from './coupon-validTerm';
import type { MallCouponTemplateApi } from '#/api/mall/promotion/coupon/couponTemplate';
import { defineComponent } from 'vue';
import {
CouponTemplateValidityTypeEnum,
PromotionDiscountTypeEnum,
} from '@vben/constants';
import { floatToFixed2, formatDate } from '@vben/utils';
/** 有效期 */
export const CouponValidTerm = defineComponent({
name: 'CouponValidTerm',
props: {
coupon: {
type: Object as () => MallCouponTemplateApi.CouponTemplate,
required: true,
},
},
setup(props) {
const coupon = props.coupon as MallCouponTemplateApi.CouponTemplate;
const text =
coupon.validityType === CouponTemplateValidityTypeEnum.DATE.type
? `有效期:${formatDate(coupon.validStartTime, 'YYYY-MM-DD')}${formatDate(
coupon.validEndTime,
'YYYY-MM-DD',
)}`
: `领取后第 ${coupon.fixedStartTerm} - ${coupon.fixedEndTerm} 天内可用`;
return () => <div>{text}</div>;
},
});
/** 优惠值 */
export const CouponDiscount = defineComponent({
name: 'CouponDiscount',
props: {
coupon: {
type: Object as () => MallCouponTemplateApi.CouponTemplate,
required: true,
},
},
setup(props) {
const coupon = props.coupon as MallCouponTemplateApi.CouponTemplate;
// 折扣
let value = `${(coupon.discountPercent ?? 0) / 10}`;
let suffix = ' 折';
// 满减
if (coupon.discountType === PromotionDiscountTypeEnum.PRICE.type) {
value = floatToFixed2(coupon.discountPrice);
suffix = ' 元';
}
return () => (
<div>
<span class={'text-20px font-bold'}>{value}</span>
<span>{suffix}</span>
</div>
);
},
});
/** 优惠描述 */
export const CouponDiscountDesc = defineComponent({
name: 'CouponDiscountDesc',
props: {
coupon: {
type: Object as () => MallCouponTemplateApi.CouponTemplate,
required: true,
},
},
setup(props) {
const coupon = props.coupon as MallCouponTemplateApi.CouponTemplate;
// 使用条件
const useCondition =
coupon.usePrice > 0 ? `${floatToFixed2(coupon.usePrice)}元,` : '';
// 优惠描述
const discountDesc =
coupon.discountType === PromotionDiscountTypeEnum.PRICE.type
? `${floatToFixed2(coupon.discountPrice)}`
: `${(coupon.discountPercent ?? 0) / 10}`;
return () => (
<div>
<span>{useCondition}</span>
<span>{discountDesc}</span>
</div>
);
},
});

View File

@@ -1,34 +0,0 @@
import type { MallCouponTemplateApi } from '#/api/mall/promotion/coupon/couponTemplate';
import { defineComponent } from 'vue';
import { PromotionDiscountTypeEnum } from '@vben/constants';
import { floatToFixed2 } from '@vben/utils';
// 优惠描述
export const CouponDiscountDesc = defineComponent({
name: 'CouponDiscountDesc',
props: {
coupon: {
type: Object as () => MallCouponTemplateApi.CouponTemplate,
required: true,
},
},
setup(props) {
const coupon = props.coupon as MallCouponTemplateApi.CouponTemplate;
// 使用条件
const useCondition =
coupon.usePrice > 0 ? `${floatToFixed2(coupon.usePrice)}元,` : '';
// 优惠描述
const discountDesc =
coupon.discountType === PromotionDiscountTypeEnum.PRICE.type
? `${floatToFixed2(coupon.discountPrice)}`
: `${(coupon.discountPercent ?? 0) / 10}`;
return () => (
<div>
<span>{useCondition}</span>
<span>{discountDesc}</span>
</div>
);
},
});

View File

@@ -1,34 +0,0 @@
import type { MallCouponTemplateApi } from '#/api/mall/promotion/coupon/couponTemplate';
import { defineComponent } from 'vue';
import { PromotionDiscountTypeEnum } from '@vben/constants';
import { floatToFixed2 } from '@vben/utils';
// 优惠值
export const CouponDiscount = defineComponent({
name: 'CouponDiscount',
props: {
coupon: {
type: Object as () => MallCouponTemplateApi.CouponTemplate,
required: true,
},
},
setup(props) {
const coupon = props.coupon as MallCouponTemplateApi.CouponTemplate;
// 折扣
let value = `${(coupon.discountPercent ?? 0) / 10}`;
let suffix = ' 折';
// 满减
if (coupon.discountType === PromotionDiscountTypeEnum.PRICE.type) {
value = floatToFixed2(coupon.discountPrice);
suffix = ' 元';
}
return () => (
<div>
<span class={'text-20px font-bold'}>{value}</span>
<span>{suffix}</span>
</div>
);
},
});

View File

@@ -1,28 +0,0 @@
import type { MallCouponTemplateApi } from '#/api/mall/promotion/coupon/couponTemplate';
import { defineComponent } from 'vue';
import { CouponTemplateValidityTypeEnum } from '@vben/constants';
import { formatDate } from '@vben/utils';
// 有效期
export const CouponValidTerm = defineComponent({
name: 'CouponValidTerm',
props: {
coupon: {
type: Object as () => MallCouponTemplateApi.CouponTemplate,
required: true,
},
},
setup(props) {
const coupon = props.coupon as MallCouponTemplateApi.CouponTemplate;
const text =
coupon.validityType === CouponTemplateValidityTypeEnum.DATE.type
? `有效期:${formatDate(coupon.validStartTime, 'YYYY-MM-DD')}${formatDate(
coupon.validEndTime,
'YYYY-MM-DD',
)}`
: `领取后第 ${coupon.fixedStartTerm} - ${coupon.fixedEndTerm} 天内可用`;
return () => <div>{text}</div>;
},
});

View File

@@ -13,12 +13,19 @@ import {
CouponValidTerm,
} from './component';
/** 商品卡片 */
/** 优惠劵卡片 */
defineOptions({ name: 'CouponCard' });
// 定义属性
/** 定义属性 */
const props = defineProps<{ property: CouponCardProperty }>();
// 商品列表
const couponList = ref<MallCouponTemplateApi.CouponTemplate[]>([]);
const couponList = ref<MallCouponTemplateApi.CouponTemplate[]>([]); // 优惠劵列表
const phoneWidth = ref(375); // 手机宽度
const containerRef = ref(); // 容器引用
const scrollbarWidth = ref('100%'); // 滚动条宽度
const couponWidth = ref(375); // 优惠券宽度
/** 监听优惠券 ID 变化,加载优惠券列表 */
watch(
() => props.property.couponIds,
async () => {
@@ -32,15 +39,7 @@ watch(
},
);
// 手机宽度
const phoneWidth = ref(384);
// 容器
const containerRef = ref();
// 滚动条宽度
const scrollbarWidth = ref('100%');
// 优惠券的宽度
const couponWidth = ref(384);
// 计算布局参数
/** 计算布局参数 */
watch(
() => [props.property, phoneWidth, couponList.value.length],
() => {
@@ -56,9 +55,10 @@ watch(
},
{ immediate: true, deep: true },
);
/** 初始化 */
onMounted(() => {
// 提取手机宽度
phoneWidth.value = containerRef.value?.wrapRef?.offsetWidth || 384;
phoneWidth.value = containerRef.value?.wrapRef?.offsetWidth || 375;
});
</script>
<template>
@@ -82,17 +82,14 @@ onMounted(() => {
v-for="(coupon, index) in couponList"
:key="index"
>
<!-- 布局11-->
<!-- 布局 11 -->
<div
v-if="property.columns === 1"
class="ml-4 flex flex-row justify-between p-2"
>
<div class="flex flex-col justify-evenly gap-1">
<!-- 优惠值 -->
<CouponDiscount :coupon="coupon" />
<!-- 优惠描述 -->
<CouponDiscountDesc :coupon="coupon" />
<!-- 有效期 -->
<CouponValidTerm :coupon="coupon" />
</div>
<div class="flex flex-col justify-evenly">
@@ -107,17 +104,14 @@ onMounted(() => {
</div>
</div>
</div>
<!-- 布局22-->
<!-- 布局 22 -->
<div
v-else-if="property.columns === 2"
class="ml-4 flex flex-row justify-between p-2"
>
<div class="flex flex-col justify-evenly gap-1">
<!-- 优惠值 -->
<CouponDiscount :coupon="coupon" />
<!-- 优惠描述 -->
<CouponDiscountDesc :coupon="coupon" />
<!-- 领取说明 -->
<div v-if="coupon.totalCount >= 0">
仅剩{{ coupon.totalCount - coupon.takeCount }}
</div>
@@ -135,11 +129,9 @@ onMounted(() => {
</div>
</div>
</div>
<!-- 布局33-->
<!-- 布局 33 -->
<div v-else class="flex flex-col items-center justify-around gap-1 p-1">
<!-- 优惠值 -->
<CouponDiscount :coupon="coupon" />
<!-- 优惠描述 -->
<CouponDiscountDesc :coupon="coupon" />
<div
class="rounded-full px-2 py-0.5"

View File

@@ -5,23 +5,20 @@ import { ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { Button, Image, message } from 'ant-design-vue';
import { Button, Image } from 'ant-design-vue';
/** 悬浮按钮 */
defineOptions({ name: 'FloatingActionButton' });
// 定义属性
/** 定义属性 */
defineProps<{ property: FloatingActionButtonProperty }>();
// 是否展开
const expanded = ref(false);
// 处理展开/折叠
const handleToggleFab = () => {
expanded.value = !expanded.value;
};
const expanded = ref(false); // 是否展开
const handleActive = (index: number) => {
message.success(`点击了${index}`);
};
/** 处理展开/折叠 */
function handleToggleFab() {
expanded.value = !expanded.value;
}
</script>
<template>
<div
@@ -38,9 +35,8 @@ const handleActive = (index: number) => {
v-for="(item, index) in property.list"
:key="index"
class="flex flex-col items-center"
@click="handleActive(index)"
>
<Image :src="item.imgUrl" fit="contain" class="h-7 w-7">
<Image :src="item.imgUrl" fit="contain" class="!h-7 !w-7">
<template #error>
<div class="flex h-full w-full items-center justify-center">
<IconifyIcon
@@ -64,33 +60,15 @@ const handleActive = (index: number) => {
<Button type="primary" size="large" circle @click="handleToggleFab">
<IconifyIcon
icon="lucide:plus"
class="fab-icon"
:class="[{ active: expanded }]"
class="transition-transform duration-300"
:class="expanded ? 'rotate-[135deg]' : 'rotate-0'"
/>
</Button>
</div>
<!-- 模态背景展开时显示点击后折叠 -->
<div v-if="expanded" class="modal-bg" @click="handleToggleFab"></div>
<div
v-if="expanded"
class="absolute left-[calc(50%-384px/2)] top-0 z-[11] h-full w-[384px] bg-black/40"
@click="handleToggleFab"
></div>
</template>
<style scoped lang="scss">
/* 模态背景 */
.modal-bg {
position: absolute;
top: 0;
left: calc(50% - 384px / 2);
z-index: 11;
width: 384px;
height: 100%;
background-color: rgb(0 0 0 / 40%);
}
.fab-icon {
transform: rotate(0deg);
transition: transform 0.3s;
&.active {
transform: rotate(135deg);
}
}
</style>

View File

@@ -2,10 +2,9 @@ import type { StyleValue } from 'vue';
import type { HotZoneItemProperty } from '../../config';
// 热区的最小宽高
export const HOT_ZONE_MIN_SIZE = 100;
export const HOT_ZONE_MIN_SIZE = 100; // 热区的最小宽高
// 控制的类型
/** 控制的类型 */
export enum CONTROL_TYPE_ENUM {
LEFT,
TOP,
@@ -13,14 +12,14 @@ export enum CONTROL_TYPE_ENUM {
HEIGHT,
}
// 定义热区的控制点
/** 定义热区的控制点 */
export interface ControlDot {
position: string;
types: CONTROL_TYPE_ENUM[];
style: StyleValue;
}
// 热区的8个控制点
/** 热区的 8 个控制点 */
export const CONTROL_DOT_LIST = [
{
position: '左上角',
@@ -98,10 +97,10 @@ export const CONTROL_DOT_LIST = [
] as ControlDot[];
// region 热区的缩放
// 热区的缩放比例
export const HOT_ZONE_SCALE_RATE = 2;
// 缩小:缩回适合手机屏幕的大小
export const zoomOut = (list?: HotZoneItemProperty[]) => {
export const HOT_ZONE_SCALE_RATE = 2; // 热区的缩放比例
/** 缩小:缩回适合手机屏幕的大小 */
export function zoomOut(list?: HotZoneItemProperty[]) {
return (
list?.map((hotZone) => ({
...hotZone,
@@ -111,9 +110,10 @@ export const zoomOut = (list?: HotZoneItemProperty[]) => {
height: (hotZone.height /= HOT_ZONE_SCALE_RATE),
})) || []
);
};
// 放大:作用是为了方便在电脑屏幕上编辑
export const zoomIn = (list?: HotZoneItemProperty[]) => {
}
/** 放大:作用是为了方便在电脑屏幕上编辑 */
export function zoomIn(list?: HotZoneItemProperty[]) {
return (
list?.map((hotZone) => ({
...hotZone,
@@ -123,7 +123,8 @@ export const zoomIn = (list?: HotZoneItemProperty[]) => {
height: (hotZone.height *= HOT_ZONE_SCALE_RATE),
})) || []
);
};
}
// endregion
/**

View File

@@ -11,7 +11,7 @@ import { IconifyIcon } from '@vben/icons';
import { Button, Image } from 'ant-design-vue';
import AppLinkSelectDialog from '#/views/mall/promotion/components/app-link-input/app-link-select-dialog.vue';
import { AppLinkSelectDialog } from '#/views/mall/promotion/components';
import {
CONTROL_DOT_LIST,
@@ -213,8 +213,9 @@ const handleAppLinkChange = (appLink: AppLink) => {
</span>
<IconifyIcon
icon="lucide:x"
class="absolute inset-0 right-0 top-0 hidden size-6 cursor-pointer items-center rounded-bl-[80%] p-[2px_2px_6px_6px] text-right text-white group-hover:block"
class="absolute right-0 top-0 hidden cursor-pointer rounded-bl-[80%] p-[2px_2px_6px_6px] text-right text-white group-hover:block"
:style="{ backgroundColor: 'hsl(var(--primary))' }"
:size="14"
@click="handleRemove(item)"
/>
@@ -230,9 +231,7 @@ const handleAppLinkChange = (appLink: AppLink) => {
</div>
<template #prepend-footer>
<Button @click="handleAdd" type="primary" ghost>
<template #icon>
<IconifyIcon icon="lucide:plus" />
</template>
<IconifyIcon icon="lucide:plus" class="mr-5px" />
添加热区
</Button>
</template>

View File

@@ -2,8 +2,10 @@
import type { HotZoneProperty } from './config';
import { Image } from 'ant-design-vue';
/** 热区 */
defineOptions({ name: 'HotZone' });
const props = defineProps<{ property: HotZoneProperty }>();
</script>
@@ -12,21 +14,23 @@ const props = defineProps<{ property: HotZoneProperty }>();
<Image
:src="props.property.imgUrl"
class="pointer-events-none h-full w-full select-none"
:preview="false"
/>
<div
v-for="(item, index) in props.property.list"
:key="index"
class="bg-primary-700 absolute z-10 flex cursor-move items-center justify-center border text-sm opacity-80"
class="absolute z-10 flex cursor-move items-center justify-center border text-sm opacity-80"
:style="{
width: `${item.width}px`,
height: `${item.height}px`,
top: `${item.top}px`,
left: `${item.left}px`,
color: 'hsl(var(--primary))',
background: 'color-mix(in srgb, hsl(var(--primary)) 30%, transparent)',
borderColor: 'hsl(var(--primary))',
}"
>
<p class="text-primary">
{{ item.name }}
</p>
{{ item.name }}
</div>
</div>
</template>

View File

@@ -15,42 +15,40 @@ import HotZoneEditDialog from './components/hot-zone-edit-dialog/index.vue';
defineOptions({ name: 'HotZoneProperty' });
const props = defineProps<{ modelValue: HotZoneProperty }>();
const emit = defineEmits(['update:modelValue']);
const formData = useVModel(props, 'modelValue', emit);
// 热区编辑对话框
const editDialogRef = ref();
// 打开热区编辑对话框
const handleOpenEditDialog = () => {
const editDialogRef = ref(); // 热区编辑对话框
/** 打开热区编辑对话框 */
function handleOpenEditDialog() {
editDialogRef.value.open();
};
}
</script>
<template>
<ComponentContainerProperty v-model="formData.style">
<!-- 表单 -->
<Form
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
:model="formData"
class="mt-2"
>
<Form label-width="80px" :model="formData" class="mt-2">
<FormItem label="上传图片" prop="imgUrl">
<UploadImg
v-model="formData.imgUrl"
height="50px"
width="auto"
class="min-w-20"
class="min-w-[80px]"
:show-description="false"
/>
<p class="text-xs text-gray-500">推荐宽度 750</p>
</FormItem>
<p class="text-center text-sm text-gray-500">推荐宽度 750</p>
</Form>
<Button type="primary" class="mt-4 w-full" @click="handleOpenEditDialog">
<Button type="primary" plain class="w-full" @click="handleOpenEditDialog">
设置热区
</Button>
</ComponentContainerProperty>
<!-- 热区编辑对话框 -->
<HotZoneEditDialog
ref="editDialogRef"
@@ -58,26 +56,3 @@ const handleOpenEditDialog = () => {
:img-url="formData.imgUrl"
/>
</template>
<style scoped lang="scss">
.hot-zone {
position: absolute;
display: flex;
align-items: center;
justify-content: center;
font-size: 12px;
color: hsl(var(--text-color));
cursor: move;
background: color-mix(in srgb, hsl(var(--primary)) 30%, transparent);
border: 1px solid hsl(var(--primary));
/* 控制点 */
.ctrl-dot {
position: absolute;
width: 4px;
height: 4px;
background-color: #fff;
border-radius: 50%;
}
}
</style>

View File

@@ -11,7 +11,6 @@ defineOptions({ name: 'ImageBar' });
defineProps<{ property: ImageBarProperty }>();
</script>
<template>
<!-- 无图片 -->
<div
class="bg-card flex h-12 items-center justify-center"
v-if="!property.imgUrl"

View File

@@ -9,11 +9,13 @@ import { AppLinkInput } from '#/views/mall/promotion/components';
import ComponentContainerProperty from '../../component-container-property.vue';
// 图片展示属性面板
/** 图片展示属性面板 */
defineOptions({ name: 'ImageBarProperty' });
const props = defineProps<{ modelValue: ImageBarProperty }>();
const emit = defineEmits(['update:modelValue']);
const formData = useVModel(props, 'modelValue', emit);
</script>

View File

@@ -9,9 +9,11 @@ import { Image } from 'ant-design-vue';
/** 广告魔方 */
defineOptions({ name: 'MagicCube' });
const props = defineProps<{ property: MagicCubeProperty }>();
// 一个方块的大小
const CUBE_SIZE = 93.75;
const CUBE_SIZE = 93.75; // 一个方块的大小
/**
* 计算方块的行数
* 行数用于计算魔方的总体高度,存在以下情况:

View File

@@ -57,6 +57,7 @@ const handleHotAreaSelected = (_: any, index: number) => {
</FormItem>
</template>
</template>
<!-- TODO @芋艿距离不一致需要看看怎么统一 -->
<FormItem label="上圆角" name="borderRadiusTop">
<Slider v-model:value="formData.borderRadiusTop" :max="100" :min="0" />
</FormItem>

View File

@@ -5,6 +5,7 @@ import { Image } from 'ant-design-vue';
/** 宫格导航 */
defineOptions({ name: 'MenuGrid' });
defineProps<{ property: MenuGridProperty }>();
</script>

View File

@@ -9,6 +9,7 @@ import {
AppLinkInput,
ColorInput,
Draggable,
InputWithColor,
} from '#/views/mall/promotion/components';
import ComponentContainerProperty from '../../component-container-property.vue';
@@ -18,7 +19,9 @@ import { EMPTY_MENU_GRID_ITEM_PROPERTY } from './config';
defineOptions({ name: 'MenuGridProperty' });
const props = defineProps<{ modelValue: MenuGridProperty }>();
const emit = defineEmits(['update:modelValue']);
const formData = useVModel(props, 'modelValue', emit);
</script>
@@ -27,12 +30,11 @@ const formData = useVModel(props, 'modelValue', emit);
<!-- 表单 -->
<Form label-width="80px" :model="formData" class="mt-2">
<FormItem label="每行数量" prop="column">
<RadioGroup v-model="formData.column">
<RadioGroup v-model:value="formData.column">
<Radio :value="3">3</Radio>
<Radio :value="4">4</Radio>
</RadioGroup>
</FormItem>
<p class="text-base font-bold">菜单设置</p>
<div class="flex flex-col gap-2 rounded-md p-4 shadow-lg">
<Draggable
@@ -47,17 +49,17 @@ const formData = useVModel(props, 'modelValue', emit);
width="80px"
:show-description="false"
>
<template #tip> 建议尺寸44 * 44 </template>
<template #tip> 建议尺寸44 * 44</template>
</UploadImg>
</FormItem>
<FormItem label="标题" prop="title">
<ColorInput
<InputWithColor
v-model="element.title"
v-model:color="element.titleColor"
/>
</FormItem>
<FormItem label="副标题" prop="subtitle">
<ColorInput
<InputWithColor
v-model="element.subtitle"
v-model:color="element.subtitleColor"
/>
@@ -70,7 +72,7 @@ const formData = useVModel(props, 'modelValue', emit);
</FormItem>
<template v-if="element.badge.show">
<FormItem label="角标内容" prop="badge.text">
<ColorInput
<InputWithColor
v-model="element.badge.text"
v-model:color="element.badge.textColor"
/>

View File

@@ -7,6 +7,7 @@ import { Image } from 'ant-design-vue';
/** 列表导航 */
defineOptions({ name: 'MenuList' });
defineProps<{ property: MenuListProperty }>();
</script>

View File

@@ -7,22 +7,19 @@ import { Image } from 'ant-design-vue';
/** 菜单导航 */
defineOptions({ name: 'MenuSwiper' });
const props = defineProps<{ property: MenuSwiperProperty }>();
// 标题的高度
const TITLE_HEIGHT = 20;
// 图标的高度
const ICON_SIZE = 32;
// 垂直间距:一行上下的间距
const SPACE_Y = 16;
// 分页
const pages = ref<MenuSwiperItemProperty[][]>([]);
// 轮播图高度
const carouselHeight = ref(0);
// 行高
const rowHeight = ref(0);
// 列宽
const columnWidth = ref('');
const props = defineProps<{ property: MenuSwiperProperty }>();
const TITLE_HEIGHT = 20; // 标题的高度
const ICON_SIZE = 32; // 图标的高度
const SPACE_Y = 16; // 垂直间距:一行上下的间距
const pages = ref<MenuSwiperItemProperty[][]>([]); // 分页
const carouselHeight = ref(0); // 轮播图高度
const rowHeight = ref(0); // 行高
const columnWidth = ref(''); // 列宽
watch(
() => props.property,
() => {
@@ -75,9 +72,7 @@ watch(
class="relative flex flex-col items-center justify-center"
:style="{ width: columnWidth, height: `${rowHeight}px` }"
>
<!-- 图标 + 角标 -->
<div class="relative" :class="`h-${ICON_SIZE}px w-${ICON_SIZE}px`">
<!-- 右上角角标 -->
<span
v-if="item.badge?.show"
class="absolute -right-2.5 -top-2.5 z-10 h-5 rounded-[10px] px-1.5 text-center text-xs leading-5"
@@ -95,7 +90,6 @@ watch(
:preview="false"
/>
</div>
<!-- 标题 -->
<span
v-if="property.layout === 'iconText'"
class="text-xs"

View File

@@ -1,18 +1,18 @@
<script lang="ts" setup>
import type { NavigationBarCellProperty } from '../config';
import type { Rect } from '#/views/mall/promotion/components/magic-cube-editor/util';
import { computed, ref } from 'vue';
import { useVModel } from '@vueuse/core';
import {
FormItem,
Image,
Input,
Radio,
RadioButton,
RadioGroup,
Slider,
Switch,
Tooltip,
} from 'ant-design-vue';
import appNavBarMp from '#/assets/imgs/diy/app-nav-bar-mp.png';
@@ -23,7 +23,7 @@ import {
MagicCubeEditor,
} from '#/views/mall/promotion/components';
// 导航栏属性面板
/** 导航栏单元格属性面板 */
defineOptions({ name: 'NavigationBarCellProperty' });
const props = defineProps({
@@ -36,54 +36,64 @@ const props = defineProps({
default: () => [],
},
});
const emit = defineEmits(['update:modelValue']);
const cellList = useVModel(props, 'modelValue', emit);
// 单元格数量小程序6个右侧胶囊按钮占了2个其它平台8个
/**
* 计算单元格数量
* 1. 小程序6 个(因为右侧有胶囊按钮占据 2 个格子的空间)
* 2. 其它平台8 个(全部空间可用)
*/
const cellCount = computed(() => (props.isMp ? 6 : 8));
// 转换为Rect格式的数据
const rectList = computed<Rect[]>(() => {
return cellList.value.map((cell) => ({
left: cell.left,
top: cell.top,
width: cell.width,
height: cell.height,
right: cell.left + cell.width,
bottom: cell.top + cell.height,
}));
});
const selectedHotAreaIndex = ref(0); // 选中的热区
// 选中的热区
const selectedHotAreaIndex = ref(0);
const handleHotAreaSelected = (
/** 处理热区被选中事件 */
function handleHotAreaSelected(
cellValue: NavigationBarCellProperty,
index: number,
) => {
) {
selectedHotAreaIndex.value = index;
// 默认设置为选中文字,并设置属性
if (!cellValue.type) {
cellValue.type = 'text';
cellValue.textColor = '#111111';
}
};
// 如果点击的是搜索框,则初始化搜索框的属性
if (cellValue.type === 'search') {
cellValue.placeholderPosition = 'left';
cellValue.backgroundColor = '#EEEEEE';
cellValue.textColor = '#969799';
}
}
</script>
<template>
<div class="h-40px flex items-center justify-center">
<MagicCubeEditor
v-model="rectList"
v-model="cellList as any"
:cols="cellCount"
:cube-size="38"
:rows="1"
class="m-b-16px"
@hot-area-selected="handleHotAreaSelected"
/>
<Image v-if="isMp" alt="" class="w-19 h-8" :src="appNavBarMp" />
<img
v-if="isMp"
alt=""
style="width: 76px; height: 30px"
:src="appNavBarMp"
/>
</div>
<template v-for="(cell, cellIndex) in cellList" :key="cellIndex">
<template v-if="selectedHotAreaIndex === Number(cellIndex)">
<FormItem label="类型">
<RadioGroup v-model:value="cell.type">
<FormItem :prop="`cell[${cellIndex}].type`" label="类型">
<RadioGroup
v-model:value="cell.type"
@change="handleHotAreaSelected(cell, cellIndex)"
>
<Radio value="text">文字</Radio>
<Radio value="image">图片</Radio>
<Radio value="search">搜索框</Radio>
@@ -91,38 +101,69 @@ const handleHotAreaSelected = (
</FormItem>
<!-- 1. 文字 -->
<template v-if="cell.type === 'text'">
<FormItem label="内容">
<FormItem :prop="`cell[${cellIndex}].text`" label="内容">
<Input v-model:value="cell!.text" :maxlength="10" show-count />
</FormItem>
<FormItem label="颜色">
<FormItem :prop="`cell[${cellIndex}].text`" label="颜色">
<ColorInput v-model="cell!.textColor" />
</FormItem>
<FormItem label="链接">
<FormItem :prop="`cell[${cellIndex}].url`" label="链接">
<AppLinkInput v-model="cell.url" />
</FormItem>
</template>
<!-- 2. 图片 -->
<template v-else-if="cell.type === 'image'">
<FormItem label="图片">
<FormItem :prop="`cell[${cellIndex}].imgUrl`" label="图片">
<UploadImg
v-model="cell.imgUrl"
:limit="1"
height="56px"
width="56px"
:show-description="false"
class="size-14"
/>
<span class="text-xs text-gray-500">建议尺寸 56*56</span>
</FormItem>
<FormItem label="链接">
<FormItem :prop="`cell[${cellIndex}].url`" label="链接">
<AppLinkInput v-model="cell.url" />
</FormItem>
</template>
<!-- 3. 搜索框 -->
<template v-else>
<FormItem label="提示文字">
<FormItem label="框体颜色" prop="backgroundColor">
<ColorInput v-model="cell.backgroundColor" />
</FormItem>
<FormItem class="lef" label="文本颜色" prop="textColor">
<ColorInput v-model="cell.textColor" />
</FormItem>
<FormItem :prop="`cell[${cellIndex}].placeholder`" label="提示文字">
<Input v-model:value="cell.placeholder" :maxlength="10" show-count />
</FormItem>
<FormItem label="圆角">
<Slider v-model:value="cell.borderRadius" :max="100" :min="0" />
<FormItem label="文本位置" prop="placeholderPosition">
<RadioGroup v-model:value="cell!.placeholderPosition">
<Tooltip content="居左" placement="top">
<RadioButton value="left">
<IconifyIcon icon="ant-design:align-left-outlined" />
</RadioButton>
</Tooltip>
<Tooltip content="居中" placement="top">
<RadioButton value="center">
<IconifyIcon icon="ant-design:align-center-outlined" />
</RadioButton>
</Tooltip>
</RadioGroup>
</FormItem>
<FormItem label="扫一扫" prop="showScan">
<Switch v-model:checked="cell!.showScan" />
</FormItem>
<FormItem :prop="`cell[${cellIndex}].borderRadius`" label="圆角">
<Slider
v-model:value="cell.borderRadius"
:max="100"
:min="0"
:show-input-controls="false"
input-size="small"
show-input
/>
</FormItem>
</template>
</template>

View File

@@ -18,7 +18,7 @@ defineOptions({ name: 'NavigationBar' });
const props = defineProps<{ property: NavigationBarProperty }>();
// 背景
/** 计算背景样式 */
const bgStyle = computed(() => {
const background =
props.property.bgType === 'img' && props.property.bgImg
@@ -26,27 +26,31 @@ const bgStyle = computed(() => {
: props.property.bgColor;
return { background };
});
// 单元格列表
/** 获取当前预览的单元格列表 */
const cellList = computed(() =>
props.property._local?.previewMp
? props.property.mpCells
: props.property.otherCells,
);
// 单元格宽度
/** 计算单元格宽度 */
const cellWidth = computed(() => {
return props.property._local?.previewMp
? (384 - 80 - 86) / 6
: (384 - 90) / 8;
? (375 - 80 - 86) / 6
: (375 - 90) / 8;
});
// 获得单元格样式
const getCellStyle = (cell: NavigationBarCellProperty) => {
/** 获取单元格样式 */
function getCellStyle(cell: NavigationBarCellProperty) {
return {
width: `${cell.width * cellWidth.value + (cell.width - 1) * 10}px`,
left: `${cell.left * cellWidth.value + (cell.left + 1) * 10}px`,
position: 'absolute',
} as StyleValue;
};
// 获得搜索框属性
}
/** 获取搜索框属性配置 */
const getSearchProp = computed(() => (cell: NavigationBarCellProperty) => {
return {
height: 30,
@@ -57,7 +61,10 @@ const getSearchProp = computed(() => (cell: NavigationBarCellProperty) => {
});
</script>
<template>
<div class="navigation-bar" :style="bgStyle">
<div
class="flex h-[50px] items-center justify-between bg-white px-[6px]"
:style="bgStyle"
>
<div class="flex h-full w-full items-center">
<div
v-for="(cell, cellIndex) in cellList"
@@ -78,35 +85,7 @@ const getSearchProp = computed(() => (cell: NavigationBarCellProperty) => {
v-if="property._local?.previewMp"
:src="appNavbarMp"
alt=""
class="w-22 h-8"
style="width: 86px; height: 30px"
/>
</div>
</template>
<style lang="scss" scoped>
.navigation-bar {
display: flex;
align-items: center;
justify-content: space-between;
height: 50px;
padding: 0 6px;
background: #fff;
/* 左边 */
.left {
margin-left: 8px;
}
.center {
flex: 1;
font-size: 14px;
line-height: 35px;
color: #333;
text-align: center;
}
/* 右边 */
.right {
margin-right: 8px;
}
}
</style>

View File

@@ -17,16 +17,16 @@ import { ColorInput } from '#/views/mall/promotion/components';
import NavigationBarCellProperty from './components/cell-property.vue';
// 导航栏属性面板
/** 导航栏属性面板 */
defineOptions({ name: 'NavigationBarProperty' });
const props = defineProps<{ modelValue: NavigationBarProperty }>();
const emit = defineEmits(['update:modelValue']);
// 表单校验
const rules: Record<string, any> = {
name: [{ required: true, message: '请输入页面名称', trigger: 'blur' }],
};
}; // 表单校验
const formData = useVModel(props, 'modelValue', emit);
if (!formData.value._local) {

View File

@@ -1,23 +1,14 @@
<script setup lang="ts">
import type { NoticeBarProperty } from './config';
import { ref } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { Divider, Image } from 'ant-design-vue';
import { Carousel, Divider, Image } from 'ant-design-vue';
/** 公告栏 */
defineOptions({ name: 'NoticeBar' });
const props = defineProps<{ property: NoticeBarProperty }>();
// 自动轮播
const activeIndex = ref(0);
setInterval(() => {
const contents = props.property.contents || [];
activeIndex.value = (activeIndex.value + 1) % (contents.length || 1);
}, 3000);
defineProps<{ property: NoticeBarProperty }>();
</script>
<template>
@@ -30,11 +21,17 @@ setInterval(() => {
>
<Image :src="property.iconUrl" class="h-[18px]" :preview="false" />
<Divider type="vertical" />
<div class="h-6 flex-1 truncate pr-2 leading-6">
{{ property.contents?.[activeIndex]?.text }}
</div>
<Carousel
:autoplay="true"
:dots="false"
vertical
class="flex-1 pr-2"
style="height: 24px"
>
<div v-for="(item, index) in property.contents" :key="index">
<div class="h-6 truncate leading-6">{{ item.text }}</div>
</div>
</Carousel>
<IconifyIcon icon="lucide:arrow-right" />
</div>
</template>
<style scoped lang="scss"></style>

View File

@@ -7,25 +7,18 @@ import { Form, FormItem, Textarea } from 'ant-design-vue';
import UploadImg from '#/components/upload/image-upload.vue';
import { ColorInput } from '#/views/mall/promotion/components';
// 导航栏属性面板
/** 导航栏属性面板 */
defineOptions({ name: 'PageConfigProperty' });
const props = defineProps<{ modelValue: PageConfigProperty }>();
const emit = defineEmits(['update:modelValue']);
// 表单校验
const rules = {};
const formData = useVModel(props, 'modelValue', emit);
</script>
<template>
<Form
:model="formData"
:rules="rules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
>
<Form :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
<FormItem label="页面描述" name="description">
<Textarea
v-model:value="formData!.description"
@@ -47,5 +40,3 @@ const formData = useVModel(props, 'modelValue', emit);
</FormItem>
</Form>
</template>
<style scoped lang="scss"></style>

View File

@@ -9,18 +9,19 @@ import { Image } from 'ant-design-vue';
/** 弹窗广告 */
defineOptions({ name: 'Popover' });
//
defineProps<{ property: PopoverProperty }>();
//
const activeIndex = ref(0);
const handleActive = (index: number) => {
const props = defineProps<{ property: PopoverProperty }>();
const activeIndex = ref(0); // index
/** 处理选中 */
function handleActive(index: number) {
activeIndex.value = index;
};
}
</script>
<template>
<div
v-for="(item, index) in property.list"
v-for="(item, index) in props.property.list"
:key="index"
class="absolute bottom-1/2 right-1/2 h-[454px] w-[292px] rounded border border-gray-300 bg-white p-0.5"
:style="{
@@ -40,5 +41,3 @@ const handleActive = (index: number) => {
<div class="absolute right-1 top-1 text-xs">{{ index + 1 }}</div>
</div>
</template>
<style scoped lang="scss"></style>

View File

@@ -13,10 +13,11 @@ import { getSpuDetailList } from '#/api/mall/product/spu';
/** 商品卡片 */
defineOptions({ name: 'ProductCard' });
// 定义属性
const props = defineProps<{ property: ProductCardProperty }>();
// 商品列表
const spuList = ref<MallSpuApi.Spu[]>([]);
const spuList = ref<MallSpuApi.Spu[]>([]); // 商品列表
watch(
() => props.property.spuIds,
async () => {
@@ -28,28 +29,21 @@ watch(
},
);
/**
* 计算商品的间距
* @param index 商品索引
*/
/** 计算商品的间距 */
function calculateSpace(index: number) {
// 商品的列数
const columns = props.property.layoutType === 'twoCol' ? 2 : 1;
// 第一没有边距
const marginLeft = index % columns === 0 ? '0' : `${props.property.space}px`;
// 第一行没有上边距
const marginTop = index < columns ? '0' : `${props.property.space}px`;
const columns = props.property.layoutType === 'twoCol' ? 2 : 1; // 商品的列数
const marginLeft = index % columns === 0 ? '0' : `${props.property.space}px`; // 第一列没有左边距
const marginTop = index < columns ? '0' : `${props.property.space}px`; // 第一没有边距
return { marginLeft, marginTop };
}
// 容器
const containerRef = ref();
// 计算商品的宽度
const containerRef = ref(); // 容器
/** 计算商品的宽度 */
function calculateWidth() {
let width = '100%';
// 双列时每列的宽度为:(总宽度 - 间距)/ 2
if (props.property.layoutType === 'twoCol') {
// 双列时每列的宽度为:(总宽度 - 间距)/ 2
width = `${(containerRef.value.offsetWidth - props.property.space) / 2}px`;
}
return { width };
@@ -61,7 +55,7 @@ function calculateWidth() {
ref="containerRef"
>
<div
class="bg-card relative box-content flex flex-row flex-wrap overflow-hidden"
class="relative box-content flex flex-row flex-wrap overflow-hidden"
:style="{
...calculateSpace(index),
...calculateWidth(),

View File

@@ -13,10 +13,11 @@ import { getSpuDetailList } from '#/api/mall/product/spu';
/** 商品栏 */
defineOptions({ name: 'ProductList' });
// 定义属性
const props = defineProps<{ property: ProductListProperty }>();
// 商品列表
const spuList = ref<MallSpuApi.Spu[]>([]);
watch(
() => props.property.spuIds,
async () => {
@@ -27,19 +28,15 @@ watch(
deep: true,
},
);
// 手机宽度
const phoneWidth = ref(384);
// 容器
const containerRef = ref();
// 商品的列数
const columns = ref(2);
// 滚动条宽度
const scrollbarWidth = ref('100%');
// 商品图大小
const imageSize = ref('0');
// 商品网络列数
const gridTemplateColumns = ref('');
// 计算布局参数
const phoneWidth = ref(375); // 手机宽度
const containerRef = ref(); // 容器
const columns = ref(2); // 商品的列数
const scrollbarWidth = ref('100%'); // 滚动条宽度
const imageSize = ref('0'); // 商品图大小
const gridTemplateColumns = ref(''); // 商品网络列数
/** 计算布局参数 */
watch(
() => [props.property, phoneWidth, spuList.value.length],
() => {
@@ -69,9 +66,10 @@ watch(
},
{ immediate: true, deep: true },
);
/** 初始化 */
onMounted(() => {
// 提取手机宽度
phoneWidth.value = containerRef.value?.wrapRef?.offsetWidth || 384;
phoneWidth.value = containerRef.value?.wrapRef?.offsetWidth || 375;
});
</script>
<template>
@@ -146,5 +144,3 @@ onMounted(() => {
</div>
</div>
</template>
<style scoped lang="scss"></style>

View File

@@ -17,17 +17,18 @@ import {
} from 'ant-design-vue';
import UploadImg from '#/components/upload/image-upload.vue';
import { InputWithColor as ColorInput } from '#/views/mall/promotion/components';
import SpuShowcase from '#/views/mall/product/spu/components/spu-showcase.vue';
import { ColorInput } from '#/views/mall/promotion/components';
import ComponentContainerProperty from '../../component-container-property.vue';
// TODO: 添加组件
// import SpuShowcase from '#/views/mall/product/spu/components/spu-showcase.vue';
// 商品栏属性面板
/** 商品栏属性面板 */
defineOptions({ name: 'ProductListProperty' });
const props = defineProps<{ modelValue: ProductListProperty }>();
const emit = defineEmits(['update:modelValue']);
const formData = useVModel(props, 'modelValue', emit);
</script>
@@ -39,7 +40,7 @@ const formData = useVModel(props, 'modelValue', emit);
:model="formData"
>
<Card title="商品列表" class="property-group" :bordered="false">
<!-- <SpuShowcase v-model="formData.spuIds" /> -->
<SpuShowcase v-model="formData.spuIds" />
</Card>
<Card title="商品样式" class="property-group" :bordered="false">
<FormItem label="布局" prop="type">
@@ -117,5 +118,3 @@ const formData = useVModel(props, 'modelValue', emit);
</Form>
</ComponentContainerProperty>
</template>
<style scoped lang="scss"></style>

View File

@@ -9,10 +9,10 @@ import { getArticle } from '#/api/mall/promotion/article';
/** 营销文章 */
defineOptions({ name: 'PromotionArticle' });
// 定义属性
const props = defineProps<{ property: PromotionArticleProperty }>();
// 商品列表
const article = ref<MallArticleApi.Article>();
const props = defineProps<{ property: PromotionArticleProperty }>(); // 定义属性
const article = ref<MallArticleApi.Article>(); // 商品列表
watch(
() => props.property.id,

View File

@@ -12,18 +12,18 @@ import { getArticlePage } from '#/api/mall/promotion/article';
import ComponentContainerProperty from '../../component-container-property.vue';
// 营销文章属性面板
/** 营销文章属性面板 */
defineOptions({ name: 'PromotionArticleProperty' });
const props = defineProps<{ modelValue: PromotionArticleProperty }>();
const emit = defineEmits(['update:modelValue']);
const formData = useVModel(props, 'modelValue', emit);
// 文章列表
const articles = ref<MallArticleApi.Article[]>([]);
// 加载中
const loading = ref(false);
// 查询文章列表
const articles = ref<MallArticleApi.Article[]>([]); // 文章列表
const loading = ref(false); // 加载中
/** 查询文章列表 */
const queryArticleList = async (title?: string) => {
loading.value = true;
const { list } = await getArticlePage({
@@ -35,7 +35,7 @@ const queryArticleList = async (title?: string) => {
loading.value = false;
};
// 初始化
/** 初始化 */
onMounted(() => {
queryArticleList();
});

View File

@@ -15,10 +15,10 @@ import { getCombinationActivityListByIds } from '#/api/mall/promotion/combinatio
/** 拼团卡片 */
defineOptions({ name: 'PromotionCombination' });
// 定义属性
const props = defineProps<{ property: PromotionCombinationProperty }>();
// 商品列表
const spuList = ref<MallSpuApi.Spu[]>([]);
const spuList = ref<MallSpuApi.Spu[]>([]); // 商品列表
const spuIdList = ref<number[]>([]);
const combinationActivityList = ref<
MallCombinationActivityApi.CombinationActivity[]
@@ -30,7 +30,7 @@ watch(
try {
// 新添加的拼团组件是没有活动ID的
const activityIds = props.property.activityIds;
// 检查活动ID的有效性
// 检查活动 ID 的有效性
if (Array.isArray(activityIds) && activityIds.length > 0) {
// 获取拼团活动详情列表
combinationActivityList.value =
@@ -68,32 +68,25 @@ watch(
},
);
/**
* 计算商品的间距
* @param index 商品索引
*/
const calculateSpace = (index: number) => {
// 商品的列数
const columns = props.property.layoutType === 'twoCol' ? 2 : 1;
// 第一列没有左边距
const marginLeft = index % columns === 0 ? '0' : `${props.property.space}px`;
// 第一行没有上边距
const marginTop = index < columns ? '0' : `${props.property.space}px`;
/** 计算商品的间距 */
function calculateSpace(index: number) {
const columns = props.property.layoutType === 'twoCol' ? 2 : 1; // 商品的列数
const marginLeft = index % columns === 0 ? '0' : `${props.property.space}px`; // 第一列没有左边距
const marginTop = index < columns ? '0' : `${props.property.space}px`; // 第一行没有上边距
return { marginLeft, marginTop };
};
}
// 容器
const containerRef = ref();
// 计算商品的宽度
const calculateWidth = () => {
const containerRef = ref(); // 容器
/** 计算商品的宽度 */
function calculateWidth() {
let width = '100%';
// 双列时每列的宽度为:(总宽度 - 间距)/ 2
if (props.property.layoutType === 'twoCol') {
// 双列时每列的宽度为:(总宽度 - 间距)/ 2
width = `${(containerRef.value.offsetWidth - props.property.space) / 2}px`;
}
return { width };
};
}
</script>
<template>
<div

View File

@@ -1,11 +1,6 @@
<script setup lang="ts">
import type { PromotionCombinationProperty } from './config';
import type { MallCombinationActivityApi } from '#/api/mall/promotion/combination/combinationActivity';
import { onMounted, ref } from 'vue';
import { CommonStatusEnum } from '@vben/constants';
import { IconifyIcon } from '@vben/icons';
import { useVModel } from '@vueuse/core';
@@ -22,27 +17,20 @@ import {
Tooltip,
} from 'ant-design-vue';
import { getCombinationActivityPage } from '#/api/mall/promotion/combination/combinationActivity';
import UploadImg from '#/components/upload/image-upload.vue';
// import CombinationShowcase from '#/views/mall/promotion/combination/components/combination-showcase.vue';
import { CombinationShowcase } from '#/views/mall/promotion/combination/components';
import { ColorInput } from '#/views/mall/promotion/components';
// 拼团属性面板
import ComponentContainerProperty from '../../component-container-property.vue';
/** 拼团属性面板 */
defineOptions({ name: 'PromotionCombinationProperty' });
const props = defineProps<{ modelValue: PromotionCombinationProperty }>();
const emit = defineEmits(['update:modelValue']);
const formData = useVModel(props, 'modelValue', emit);
// 活动列表
const activityList = ref<MallCombinationActivityApi.CombinationActivity[]>([]);
onMounted(async () => {
const { list } = await getCombinationActivityPage({
pageNo: 1,
pageSize: 10,
status: CommonStatusEnum.ENABLE,
});
activityList.value = list;
});
</script>
<template>
@@ -184,5 +172,3 @@ onMounted(async () => {
</Form>
</ComponentContainerProperty>
</template>
<style scoped lang="scss"></style>

View File

@@ -14,10 +14,10 @@ import { getPointActivityListByIds } from '#/api/mall/promotion/point';
/** 积分商城卡片 */
defineOptions({ name: 'PromotionPoint' });
// 定义属性
const props = defineProps<{ property: PromotionPointProperty }>();
// 商品列表
const spuList = ref<MallPointActivityApi.SpuExtensionWithPoint[]>([]);
const spuList = ref<MallPointActivityApi.SpuExtensionWithPoint[]>([]); // 商品列表
const spuIdList = ref<number[]>([]);
const pointActivityList = ref<MallPointActivityApi.PointActivity[]>([]);
@@ -27,7 +27,7 @@ watch(
try {
// 新添加的积分商城组件是没有活动ID的
const activityIds = props.property.activityIds;
// 检查活动ID的有效性
// 检查活动 ID 的有效性
if (Array.isArray(activityIds) && activityIds.length > 0) {
// 获取积分商城活动详情列表
pointActivityList.value = await getPointActivityListByIds(activityIds);
@@ -65,32 +65,25 @@ watch(
},
);
/**
* 计算商品的间距
* @param index 商品索引
*/
const calculateSpace = (index: number) => {
// 商品的列数
const columns = props.property.layoutType === 'twoCol' ? 2 : 1;
// 第一列没有左边距
const marginLeft = index % columns === 0 ? '0' : `${props.property.space}px`;
// 第一行没有上边距
const marginTop = index < columns ? '0' : `${props.property.space}px`;
/** 计算商品的间距 */
function calculateSpace(index: number) {
const columns = props.property.layoutType === 'twoCol' ? 2 : 1; // 商品的列数
const marginLeft = index % columns === 0 ? '0' : `${props.property.space}px`; // 第一列没有左边距
const marginTop = index < columns ? '0' : `${props.property.space}px`; // 第一行没有上边距
return { marginLeft, marginTop };
};
}
// 容器
const containerRef = ref();
// 计算商品的宽度
const calculateWidth = () => {
const containerRef = ref(); // 容器
/** 计算商品的宽度 */
function calculateWidth() {
let width = '100%';
// 双列时每列的宽度为:(总宽度 - 间距)/ 2
if (props.property.layoutType === 'twoCol') {
// 双列时每列的宽度为:(总宽度 - 间距)/ 2
width = `${(containerRef.value.offsetWidth - props.property.space) / 2}px`;
}
return { width };
};
}
</script>
<template>
<div

View File

@@ -15,10 +15,9 @@ import { getSeckillActivityListByIds } from '#/api/mall/promotion/seckill/seckil
/** 秒杀卡片 */
defineOptions({ name: 'PromotionSeckill' });
// 定义属性
const props = defineProps<{ property: PromotionSeckillProperty }>();
// 商品列表
const spuList = ref<MallSpuApi.Spu[]>([]);
const spuList = ref<MallSpuApi.Spu[]>([]); // 商品列表
const spuIdList = ref<number[]>([]);
const seckillActivityList = ref<MallSeckillActivityApi.SeckillActivity[]>([]);
@@ -28,7 +27,7 @@ watch(
try {
// 新添加的秒杀组件是没有活动ID的
const activityIds = props.property.activityIds;
// 检查活动ID的有效性
// 检查活动 ID 的有效性
if (Array.isArray(activityIds) && activityIds.length > 0) {
// 获取秒杀活动详情列表
seckillActivityList.value =
@@ -66,32 +65,25 @@ watch(
},
);
/**
* 计算商品的间距
* @param index 商品索引
*/
const calculateSpace = (index: number) => {
// 商品的列数
const columns = props.property.layoutType === 'twoCol' ? 2 : 1;
// 第一列没有左边距
const marginLeft = index % columns === 0 ? '0' : `${props.property.space}px`;
// 第一行没有上边距
const marginTop = index < columns ? '0' : `${props.property.space}px`;
/** 计算商品的间距 */
function calculateSpace(index: number) {
const columns = props.property.layoutType === 'twoCol' ? 2 : 1; // 商品的列数
const marginLeft = index % columns === 0 ? '0' : `${props.property.space}px`; // 第一列没有左边距
const marginTop = index < columns ? '0' : `${props.property.space}px`; // 第一行没有上边距
return { marginLeft, marginTop };
};
}
// 容器
const containerRef = ref();
// 计算商品的宽度
const calculateWidth = () => {
const containerRef = ref(); // 容器
/** 计算商品的宽度 */
function calculateWidth() {
let width = '100%';
// 双列时每列的宽度为:(总宽度 - 间距)/ 2
if (props.property.layoutType === 'twoCol') {
// 双列时每列的宽度为:(总宽度 - 间距)/ 2
width = `${(containerRef.value.offsetWidth - props.property.space) / 2}px`;
}
return { width };
};
}
</script>
<template>
<div

View File

@@ -19,8 +19,7 @@ import {
import UploadImg from '#/components/upload/image-upload.vue';
import { ColorInput } from '#/views/mall/promotion/components';
// TODO: 添加组件
// import { SeckillShowcase } from '#/views/mall/promotion/seckill/components';
import { SeckillShowcase } from '#/views/mall/promotion/seckill/components';
import ComponentContainerProperty from '../../component-container-property.vue';

View File

@@ -5,19 +5,19 @@ import { IconifyIcon } from '@vben/icons';
/** 搜索框 */
defineOptions({ name: 'SearchBar' });
defineProps<{ property: SearchProperty }>();
</script>
<template>
<div
class="search-bar"
:style="{
color: property.textColor,
}"
>
<!-- 搜索框 -->
<div
class="inner"
class="relative flex min-h-7 items-center text-sm"
:style="{
height: `${property.height}px`,
background: property.backgroundColor,
@@ -25,7 +25,7 @@ defineProps<{ property: SearchProperty }>();
}"
>
<div
class="placeholder"
class="flex w-full items-center gap-0.5 overflow-hidden text-ellipsis whitespace-nowrap break-all px-2"
:style="{
justifyContent: property.placeholderPosition,
}"
@@ -33,7 +33,7 @@ defineProps<{ property: SearchProperty }>();
<IconifyIcon icon="lucide:search" />
<span>{{ property.placeholder || '搜索商品' }}</span>
</div>
<div class="right">
<div class="absolute right-2 flex items-center justify-center gap-2">
<!-- 搜索热词 -->
<span v-for="(keyword, index) in property.hotKeywords" :key="index">
{{ keyword }}
@@ -44,37 +44,3 @@ defineProps<{ property: SearchProperty }>();
</div>
</div>
</template>
<style scoped lang="scss">
.search-bar {
/* 搜索框 */
.inner {
position: relative;
display: flex;
align-items: center;
min-height: 28px;
font-size: 14px;
.placeholder {
display: flex;
gap: 2px;
align-items: center;
width: 100%;
padding: 0 8px;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-all;
white-space: nowrap;
}
.right {
position: absolute;
right: 8px;
display: flex;
gap: 8px;
align-items: center;
justify-content: center;
}
}
}
</style>

View File

@@ -11,9 +11,9 @@ defineOptions({ name: 'TabBar' });
defineProps<{ property: TabBarProperty }>();
</script>
<template>
<div class="tab-bar">
<div class="z-[2] w-full">
<div
class="tab-bar-bg"
class="flex flex-row items-center justify-around py-2"
:style="{
background:
property.style.bgType === 'color'
@@ -26,12 +26,18 @@ defineProps<{ property: TabBarProperty }>();
<div
v-for="(item, index) in property.items"
:key="index"
class="tab-bar-item"
class="flex w-full flex-col items-center justify-center text-xs"
>
<Image :src="index === 0 ? item.activeIconUrl : item.iconUrl">
<Image
:src="index === 0 ? item.activeIconUrl : item.iconUrl"
class="!h-[26px] w-[26px] rounded"
>
<template #error>
<div class="flex h-full w-full items-center justify-center">
<IconifyIcon icon="lucide:image" />
<IconifyIcon
icon="lucide:image"
class="h-[26px] w-[26px] rounded"
/>
</div>
</template>
</Image>
@@ -47,33 +53,3 @@ defineProps<{ property: TabBarProperty }>();
</div>
</div>
</template>
<style lang="scss" scoped>
.tab-bar {
z-index: 2;
width: 100%;
.tab-bar-bg {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-around;
padding: 8px 0;
.tab-bar-item {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
font-size: 12px;
:deep(img),
.el-icon {
width: 26px;
height: 26px;
border-radius: 4px;
}
}
}
}
</style>

View File

@@ -22,7 +22,8 @@ import {
} from '#/views/mall/promotion/components';
import { component, THEME_LIST } from './config';
// 底部导航栏
/** 底部导航栏 */
defineOptions({ name: 'TabBarProperty' });
const props = defineProps<{ modelValue: TabBarProperty }>();
@@ -32,7 +33,7 @@ const formData = useVModel(props, 'modelValue', emit);
// 将数据库的值更新到右侧属性栏
component.property.items = formData.value.items;
// 要的主题
/** 处理主题变更 */
const handleThemeChange = () => {
const theme = THEME_LIST.find((theme) => theme.id === formData.value.theme);
if (theme?.color) {
@@ -42,7 +43,7 @@ const handleThemeChange = () => {
</script>
<template>
<div class="tab-bar">
<div>
<!-- 表单 -->
<Form
:model="formData"
@@ -142,5 +143,3 @@ const handleThemeChange = () => {
</Form>
</div>
</template>
<style lang="scss" scoped></style>

View File

@@ -11,7 +11,10 @@ defineOptions({ name: 'TitleBar' });
defineProps<{ property: TitleBarProperty }>();
</script>
<template>
<div class="title-bar" :style="{ height: `${property.height}px` }">
<div
class="relative box-border min-h-[20px] w-full"
:style="{ height: `${property.height}px` }"
>
<Image
v-if="property.bgImgUrl"
:src="property.bgImgUrl"
@@ -51,7 +54,7 @@ defineProps<{ property: TitleBarProperty }>();
</div>
<!-- 更多 -->
<div
class="more"
class="absolute bottom-0 right-2 top-0 m-auto flex items-center justify-center text-[10px] text-[#969799]"
v-show="property.more.show"
:style="{
color: property.descriptionColor,
@@ -67,25 +70,3 @@ defineProps<{ property: TitleBarProperty }>();
</div>
</div>
</template>
<style scoped lang="scss">
.title-bar {
position: relative;
box-sizing: border-box;
width: 100%;
min-height: 20px;
/* 更多 */
.more {
position: absolute;
top: 0;
right: 8px;
bottom: 0;
display: flex;
align-items: center;
justify-content: center;
margin: auto;
font-size: 10px;
color: #969799;
}
}
</style>

View File

@@ -5,11 +5,13 @@ import { useVModel } from '@vueuse/core';
import ComponentContainerProperty from '../../component-container-property.vue';
// 用户卡片属性面板
/** 用户卡片属性面板 */
defineOptions({ name: 'UserCardProperty' });
const props = defineProps<{ modelValue: UserCardProperty }>();
const emit = defineEmits(['update:modelValue']);
const formData = useVModel(props, 'modelValue', emit);
</script>

View File

@@ -2,11 +2,10 @@ import type { ComponentStyle, DiyComponent } from '../../../util';
/** 用户卡券属性 */
export interface UserCouponProperty {
// 组件样式
style: ComponentStyle;
style: ComponentStyle; // 组件样式
}
// 定义组件
/** 定义组件 */
export const component = {
id: 'UserCoupon',
name: '用户卡券',

View File

@@ -5,7 +5,8 @@ import { Image } from 'ant-design-vue';
/** 用户订单 */
defineOptions({ name: 'UserOrder' });
// 定义属性
/** 定义属性 */
defineProps<{ property: UserOrderProperty }>();
</script>
<template>

View File

@@ -5,11 +5,13 @@ import { useVModel } from '@vueuse/core';
import ComponentContainerProperty from '../../component-container-property.vue';
// 用户订单属性面板
/** 用户订单属性面板 */
defineOptions({ name: 'UserOrderProperty' });
const props = defineProps<{ modelValue: UserOrderProperty }>();
const emit = defineEmits(['update:modelValue']);
const formData = useVModel(props, 'modelValue', emit);
</script>

View File

@@ -5,7 +5,8 @@ import { Image } from 'ant-design-vue';
/** 用户资产 */
defineOptions({ name: 'UserWallet' });
// 定义属性
/** 定义属性 */
defineProps<{ property: UserWalletProperty }>();
</script>
<template>

View File

@@ -5,11 +5,13 @@ import { useVModel } from '@vueuse/core';
import ComponentContainerProperty from '../../component-container-property.vue';
// 用户资产属性面板
/** 用户资产属性面板 */
defineOptions({ name: 'UserWalletProperty' });
const props = defineProps<{ modelValue: UserWalletProperty }>();
const emit = defineEmits(['update:modelValue']);
const formData = useVModel(props, 'modelValue', emit);
</script>

View File

@@ -9,11 +9,13 @@ import UploadImg from '#/components/upload/image-upload.vue';
import ComponentContainerProperty from '../../component-container-property.vue';
// 视频播放属性面板
/** 视频播放属性面板 */
defineOptions({ name: 'VideoPlayerProperty' });
const props = defineProps<{ modelValue: VideoPlayerProperty }>();
const emit = defineEmits(['update:modelValue']);
const formData = useVModel(props, 'modelValue', emit);
</script>

View File

@@ -38,6 +38,12 @@ const props = defineProps({
const emits = defineEmits(['reset', 'save', 'update:modelValue']); // 工具栏操作
// TODO @xingyu要不要加这个
// const qrcode = useQRCode(props.previewUrl, {
// errorCorrectionLevel: 'H',
// margin: 4,
// }); // 预览二维码
const componentLibrary = ref(); // 左侧组件库
const pageConfigComponent = ref<DiyComponent<any>>(
cloneDeep(PAGE_CONFIG_COMPONENT),
@@ -169,6 +175,7 @@ function handleComponentSelected(
index: number = -1,
) {
// 使用深拷贝避免响应式追踪循环警告
// TODO @xingyu这个是必须的么ele 没有哈。
selectedComponent.value = cloneDeep(component);
selectedComponentIndex.value = index;
}
@@ -308,17 +315,17 @@ onMounted(() => {
>
<Tooltip title="重置">
<Button @click="handleReset">
<IconifyIcon class="size-6" icon="lucide:refresh-cw" />
<IconifyIcon class="size-5" icon="lucide:refresh-cw" />
</Button>
</Tooltip>
<Tooltip v-if="previewUrl" title="预览">
<Button @click="handlePreview">
<IconifyIcon class="size-6" icon="lucide:eye" />
<IconifyIcon class="size-5" icon="lucide:eye" />
</Button>
</Tooltip>
<Tooltip title="保存">
<Button @click="handleSave">
<IconifyIcon class="size-6" icon="lucide:check" />
<IconifyIcon class="size-5" icon="lucide:check" />
</Button>
</Tooltip>
</Button.Group>
@@ -501,4 +508,5 @@ onMounted(() => {
</div>
</PreviewModal>
</Page>
<!-- TODO @xingyu这里改造完后类似 web-ele/src/views/mall/promotion/components/diy-editor/index.vue 里的全局样式递推到子组件里的就没没了类似 property-group -->
</template>

View File

@@ -27,14 +27,11 @@ export interface DiyComponentLibrary {
components: string[]; // 组件列表
}
// 组件样式
/** 组件样式 */
export interface ComponentStyle {
// 背景类型
bgType: 'color' | 'img';
// 背景颜色
bgColor: string;
// 背景图片
bgImg: string;
bgType: 'color' | 'img'; // 背景类型
bgColor: string; // 背景颜色
bgImg: string; // 背景图片
// 外边距
margin: number;
marginTop: number;

View File

@@ -66,10 +66,11 @@ const handleDelete = function (index: number) {
class="drag-icon cursor-move text-gray-500"
/>
</Tooltip>
<Tooltip v-if="formData.length > min" title="删除">
<Tooltip title="删除">
<IconifyIcon
icon="lucide:trash-2"
class="cursor-pointer text-red-500 hover:text-red-600"
icon="ep:delete"
class="cursor-pointer text-red-500"
v-if="formData.length > min"
@click="handleDelete(index)"
/>
</Tooltip>
@@ -79,11 +80,7 @@ const handleDelete = function (index: number) {
</div>
</template>
</VueDraggable>
<Tooltip
:title="
limit > 0 && limit < Number.MAX_VALUE ? `最多添加${limit}个` : undefined
"
>
<Tooltip :title="limit < Number.MAX_VALUE ? `最多添加${limit}个` : undefined">
<Button
type="primary"
ghost
@@ -98,5 +95,3 @@ const handleDelete = function (index: number) {
</Button>
</Tooltip>
</template>
<style scoped lang="scss"></style>

View File

@@ -1,4 +1,5 @@
export { default as AppLinkInput } from './app-link-input/index.vue';
export { default as AppLinkSelectDialog } from './app-link-input/select-dialog.vue';
export { default as ColorInput } from './color-input/index.vue';
export { default as DiyEditor } from './diy-editor/index.vue';
export { type DiyComponentLibrary, PAGE_LIBS } from './diy-editor/util';

View File

@@ -29,7 +29,6 @@ const props = defineProps({
type: Number,
default: 4,
}, // 行数,默认 4 行
cols: {
type: Number,
default: 4,
@@ -167,9 +166,7 @@ function handleHotAreaSelected(hotArea: Rect, index: number) {
emit('hotAreaSelected', hotArea, index);
}
/**
* 结束热区选择模式
*/
/** 结束热区选择模式 */
function exitHotAreaSelectMode() {
// 移除方块激活标记
eachCube((_, __, cube) => {

View File

@@ -1,8 +1,10 @@
<script setup lang="ts">
import { Space } from 'ant-design-vue';
// TODO @芋艿、@xingyu貌似上下移动的按钮被遮住了
/**
* 垂直按钮组
* Ant Design Vue 的按钮组只支持水平显示,通过重写样式实现垂直布局
* Ant Design Vue 的按钮组,通过 Space 实现垂直布局
*/
defineOptions({ name: 'VerticalButtonGroup' });
</script>

View File

@@ -26,35 +26,28 @@ defineOptions({ name: 'DiyTemplateDecorate' });
const route = useRoute();
const { refreshTab } = useTabs();
/** 特殊:存储 reset 重置时,当前 selectedTemplateItem 值,从而进行恢复 */
const DIY_PAGE_INDEX_KEY = 'diy_page_index';
const DIY_PAGE_INDEX_KEY = 'diy_page_index'; // 特殊:存储 reset 重置时,当前 selectedTemplateItem 值,从而进行恢复
const selectedTemplateItem = ref(0);
/** 左上角工具栏操作按钮 */
const templateItems = ref([
{ name: '基础设置', icon: 'lucide:settings' },
{ name: '首页', icon: 'lucide:home' },
{ name: '我的', icon: 'lucide:user' },
]);
]); // 左上角工具栏操作按钮
const formData = ref<MallDiyTemplateApi.DiyTemplateProperty>();
/** 当前编辑的属性 */
const currentFormData = ref<
MallDiyPageApi.DiyPage | MallDiyTemplateApi.DiyTemplateProperty
>({
property: '',
} as MallDiyPageApi.DiyPage);
/** templateItem 对应的缓存 */
} as MallDiyPageApi.DiyPage); // 当前编辑的属性
const currentFormDataMap = ref<
Map<string, MallDiyPageApi.DiyPage | MallDiyTemplateApi.DiyTemplateProperty>
>(new Map());
>(new Map()); // templateItem 对应的缓存
/** 商城 H5 预览地址 */
const previewUrl = ref('');
const previewUrl = ref(''); // 商城 H5 预览地址
/** 模板组件库 */
const templateLibs = [] as DiyComponentLibrary[];
/** 当前组件库 */
const templateLibs = [] as DiyComponentLibrary[]; // 模板组件库
const libs = ref<DiyComponentLibrary[]>(templateLibs); // 当前组件库
/** 获取详情 */
@@ -76,6 +69,7 @@ async function getPageDetail(id: any) {
}
/** 模板选项切换 */
// TODO @xingyu貌似切换不对“个人中心”切换不过去
function handleTemplateItemChange(event: any) {
// 从事件对象中获取值
const val = event.target?.value ?? event;
@@ -227,7 +221,7 @@ onMounted(async () => {
>
<IconifyIcon
:icon="item.icon"
class="mt-2 flex size-6 items-center"
class="mt-2 flex size-5 items-center"
/>
</Radio.Button>
</template>

View File

@@ -1,7 +1,5 @@
<!-- eslint-disable unicorn/no-nested-ternary -->
<!-- 积分活动橱窗组件 - 用于装修时展示和选择积分活动 -->
<!-- 积分商城活动橱窗组件用于展示和选择积分商城活动 -->
<script lang="ts" setup>
// TODO @puhui999看看是不是整体优化下代码风格参考别的模块
import type { MallPointActivityApi } from '#/api/mall/promotion/point';
import { computed, ref, watch } from 'vue';
@@ -15,128 +13,113 @@ import { getPointActivityListByIds } from '#/api/mall/promotion/point';
import PointTableSelect from './point-table-select.vue';
interface PointShowcaseProps {
modelValue: number | number[];
modelValue?: number | number[];
limit?: number;
disabled?: boolean;
}
const props = withDefaults(defineProps<PointShowcaseProps>(), {
modelValue: undefined,
limit: Number.MAX_VALUE,
disabled: false,
});
const emit = defineEmits<{
change: [value: any];
'update:modelValue': [value: number | number[]];
}>();
const emit = defineEmits(['update:modelValue', 'change']);
// 积分活动列表
const pointActivityList = ref<MallPointActivityApi.PointActivity[]>([]);
const pointActivityList = ref<MallPointActivityApi.PointActivity[]>([]); // 已选择的活动列表
const pointTableSelectRef = ref<InstanceType<typeof PointTableSelect>>(); // 活动选择表格组件引用
const isMultiple = computed(() => props.limit !== 1); // 是否为多选模式
// 计算是否可以添加
/** 计算是否可以添加 */
const canAdd = computed(() => {
if (props.disabled) return false;
if (!props.limit) return true;
if (props.disabled) {
return false;
}
if (!props.limit) {
return true;
}
return pointActivityList.value.length < props.limit;
});
// 积分活动选择器引用
const pointActivityTableSelectRef = ref();
/**
* 打开积分活动选择器
*/
function openPointActivityTableSelect() {
pointActivityTableSelectRef.value.open(pointActivityList.value);
}
/**
* 选择活动后触发
*/
function handleActivitySelected(
activityList:
| MallPointActivityApi.PointActivity
| MallPointActivityApi.PointActivity[],
) {
pointActivityList.value = Array.isArray(activityList)
? activityList
: [activityList];
emitActivityChange();
}
/**
* 删除活动
*/
function handleRemoveActivity(index: number) {
pointActivityList.value.splice(index, 1);
emitActivityChange();
}
/**
* 发送变更事件
*/
function emitActivityChange() {
if (props.limit === 1) {
const pointActivity =
pointActivityList.value.length > 0 ? pointActivityList.value[0] : null;
emit('update:modelValue', pointActivity?.id || 0);
emit('change', pointActivity);
} else {
emit(
'update:modelValue',
pointActivityList.value.map((pointActivity) => pointActivity.id),
);
emit('change', pointActivityList.value);
}
}
// 监听 modelValue 变化
/** 监听 modelValue 变化,加载活动详情 */
watch(
() => props.modelValue,
async () => {
const ids = Array.isArray(props.modelValue)
? props.modelValue
: props.modelValue
? [props.modelValue]
: [];
// 不需要返显
async (newValue) => {
// eslint-disable-next-line unicorn/no-nested-ternary
const ids = Array.isArray(newValue) ? newValue : newValue ? [newValue] : [];
if (ids.length === 0) {
pointActivityList.value = [];
return;
}
// 只有活动发生变化之后,才会查询活动
// 只有活动发生变化时才重新查询
if (
pointActivityList.value.length === 0 ||
pointActivityList.value.some(
(pointActivity) => !ids.includes(pointActivity.id!),
)
pointActivityList.value.some((activity) => !ids.includes(activity.id!))
) {
pointActivityList.value = await getPointActivityListByIds(ids);
}
},
{ immediate: true },
);
/** 打开活动选择对话框 */
function handleOpenActivitySelect() {
pointTableSelectRef.value?.open(pointActivityList.value);
}
/** 选择活动后触发 */
function handleActivitySelected(
activities:
| MallPointActivityApi.PointActivity
| MallPointActivityApi.PointActivity[],
) {
pointActivityList.value = Array.isArray(activities)
? activities
: [activities];
emitActivityChange();
}
/** 删除活动 */
function handleRemoveActivity(index: number) {
pointActivityList.value.splice(index, 1);
emitActivityChange();
}
/** 触发变更事件 */
function emitActivityChange() {
if (props.limit === 1) {
const activity =
pointActivityList.value.length > 0 ? pointActivityList.value[0] : null;
emit('update:modelValue', activity?.id || 0);
emit('change', activity);
} else {
emit(
'update:modelValue',
pointActivityList.value.map((activity) => activity.id!),
);
emit('change', pointActivityList.value);
}
}
</script>
<template>
<div class="flex flex-wrap items-center gap-2">
<!-- 活动图片列表 -->
<!-- 已选活动列表 -->
<div
v-for="(pointActivity, index) in pointActivityList"
:key="pointActivity.id"
class="relative flex h-[60px] w-[60px] cursor-pointer items-center justify-center rounded-lg border border-dashed border-gray-300"
v-for="(activity, index) in pointActivityList"
:key="activity.id"
class="relative h-[60px] w-[60px] overflow-hidden rounded-lg border border-dashed border-gray-300"
>
<Tooltip :title="pointActivity.spuName">
<Tooltip :title="activity.spuName">
<div class="relative h-full w-full">
<Image
:preview="true"
:src="pointActivity.picUrl"
:src="activity.picUrl"
class="h-full w-full rounded-lg object-cover"
/>
<!-- 删除按钮 -->
<IconifyIcon
v-show="!disabled"
v-if="!disabled"
icon="lucide:x"
class="absolute -right-2 -top-2 z-10 h-5 w-5 cursor-pointer text-red-500 hover:text-red-600"
@click="handleRemoveActivity(index)"
@@ -145,21 +128,21 @@ watch(
</Tooltip>
</div>
<!-- 添加按钮 -->
<!-- 添加活动按钮 -->
<Tooltip v-if="canAdd" title="选择活动">
<div
class="flex h-14 w-14 cursor-pointer items-center justify-center rounded-lg border border-dashed border-gray-300 hover:border-blue-400"
@click="openPointActivityTableSelect"
class="flex h-[60px] w-[60px] cursor-pointer items-center justify-center rounded-lg border border-dashed border-gray-300 hover:border-blue-400"
@click="handleOpenActivitySelect"
>
<IconifyIcon icon="lucide:plus" class="text-lg text-gray-400" />
<IconifyIcon icon="lucide:plus" class="text-xl text-gray-400" />
</div>
</Tooltip>
</div>
<!-- 积分活动选择对话框 -->
<!-- 活动选择对话框 -->
<PointTableSelect
ref="pointActivityTableSelectRef"
:multiple="limit !== 1"
ref="pointTableSelectRef"
:multiple="isMultiple"
@change="handleActivitySelected"
/>
</template>

View File

@@ -1,23 +1,21 @@
<!-- 积分活动表格选择器 -->
<!-- 积分商城活动选择弹窗组件 -->
<script lang="ts" setup>
// TODO @puhui999看看是不是整体优化下代码风格参考别的模块
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { MallPointActivityApi } from '#/api/mall/promotion/point';
import { computed, ref } from 'vue';
import { computed } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { Checkbox, Radio } from 'ant-design-vue';
import { dateFormatter, fenToYuanFormat } from '@vben/utils';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getPointActivityPage } from '#/api/mall/promotion/point';
interface PointTableSelectProps {
multiple?: boolean;
multiple?: boolean; // 是否单选true - checkboxfalse - radio
}
const props = withDefaults(defineProps<PointTableSelectProps>(), {
@@ -26,90 +24,75 @@ const props = withDefaults(defineProps<PointTableSelectProps>(), {
const emit = defineEmits<{
change: [
value:
activity:
| MallPointActivityApi.PointActivity
| MallPointActivityApi.PointActivity[],
];
}>();
// 单选:选中的活动 ID
const selectedActivityId = ref<number>();
// 多选:选中状态映射
const checkedStatus = ref<Record<number, boolean>>({});
// 多选:选中的活动列表
const checkedActivities = ref<MallPointActivityApi.PointActivity[]>([]);
/** 单选:处理选中变化 */
function handleRadioChange() {
const selectedRow =
gridApi.grid.getRadioRecord() as MallPointActivityApi.PointActivity;
if (selectedRow) {
emit('change', selectedRow);
modalApi.close();
}
}
// 全选状态
const isCheckAll = ref(false);
const isIndeterminate = ref(false);
/** 计算已兑换数量 */
const getRedeemedQuantity = (row: MallPointActivityApi.PointActivity) =>
(row.totalStock || 0) - (row.stock || 0);
// 搜索表单配置
const formSchema = computed<VbenFormSchema[]>(() => {
return [
{
fieldName: 'status',
label: '活动状态',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
placeholder: '请选择活动状态',
allowClear: true,
},
/** 搜索表单 Schema */
const formSchema = computed<VbenFormSchema[]>(() => [
{
fieldName: 'status',
label: '活动状态',
component: 'Select',
componentProps: {
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
placeholder: '请选择活动状态',
clearable: true,
},
];
});
},
]);
// 列配置
/** 表格列配置 */
const gridColumns = computed<VxeGridProps['columns']>(() => {
const columns: VxeGridProps['columns'] = [];
// 多选模式
if (props.multiple) {
columns.push({
field: 'checkbox',
title: '',
width: 55,
align: 'center',
slots: { default: 'checkbox-column', header: 'checkbox-header' },
});
columns.push({ type: 'checkbox', width: 55 });
} else {
// 单选模式
columns.push({
field: 'radio',
title: '#',
width: 55,
align: 'center',
slots: { default: 'radio-column' },
});
columns.push({ type: 'radio', width: 55 });
}
columns.push(
{
field: 'id',
title: '活动编号',
minWidth: 80,
minWidth: 100,
align: 'center',
},
{
field: 'picUrl',
title: '商品图片',
minWidth: 80,
width: 100,
align: 'center',
cellRender: {
name: 'CellImage',
props: {
height: 40,
},
},
},
{
field: 'spuName',
title: '商品标题',
minWidth: 300,
minWidth: 200,
},
{
field: 'marketPrice',
title: '原价',
minWidth: 100,
formatter: 'formatAmount2',
align: 'center',
formatter: ({ cellValue }) => fenToYuanFormat(cellValue),
},
{
field: 'status',
@@ -118,9 +101,7 @@ const gridColumns = computed<VxeGridProps['columns']>(() => {
align: 'center',
cellRender: {
name: 'CellDict',
props: {
type: DICT_TYPE.COMMON_STATUS,
},
props: { type: DICT_TYPE.COMMON_STATUS },
},
},
{
@@ -140,216 +121,119 @@ const gridColumns = computed<VxeGridProps['columns']>(() => {
title: '已兑换数量',
minWidth: 100,
align: 'center',
formatter: ({ row }) => (row.totalStock || 0) - (row.stock || 0),
formatter: ({ row }) => getRedeemedQuantity(row),
},
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
width: 180,
align: 'center',
formatter: 'formatDateTime',
formatter: ({ cellValue }) => dateFormatter(cellValue),
},
);
return columns;
});
// 初始化表格
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: formSchema.value,
layout: 'horizontal',
collapsed: false,
},
gridOptions: {
columns: gridColumns.value,
height: 500,
border: true,
showOverflow: true,
checkboxConfig: {
reserve: true,
},
radioConfig: {
reserve: true,
},
rowConfig: {
keyField: 'id',
isHover: true,
},
proxyConfig: {
ajax: {
async query({ page }: any, formValues: any) {
try {
const params: any = {
pageNo: page.currentPage,
pageSize: page.pageSize,
};
if (formValues.status !== undefined) {
params.status = formValues.status;
}
const data = await getPointActivityPage(params);
const list = data.list || [];
// 初始化 checkbox 绑定
list.forEach(
(activityVO) =>
(checkedStatus.value[activityVO.id] =
checkedStatus.value[activityVO.id] || false),
);
// 计算全选框状态
calculateIsCheckAll(list);
return {
items: list,
total: data.total || 0,
};
} catch (error) {
console.error('加载积分活动数据失败:', error);
return { items: [], total: 0 };
}
return await getPointActivityPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
},
gridEvents: {
radioChange: handleRadioChange,
},
});
/**
* 单选:处理选中
*/
function handleSingleSelected(row: MallPointActivityApi.PointActivity) {
selectedActivityId.value = row.id;
emit('change', row);
modalApi.close();
}
/**
* 多选:全选/全不选
*/
function handleCheckAll(e: any) {
const checked = e.target.checked;
isCheckAll.value = checked;
isIndeterminate.value = false;
const list = gridApi.grid.getData();
list.forEach((pointActivity) =>
handleCheckOne(checked, pointActivity, false),
);
}
/**
* 多选:选中一行
*/
function handleCheckOne(
checked: boolean,
pointActivity: MallPointActivityApi.PointActivity,
isCalcCheckAll: boolean,
) {
if (checked) {
checkedActivities.value.push(pointActivity);
checkedStatus.value[pointActivity.id] = true;
} else {
const index = findCheckedIndex(pointActivity);
if (index > -1) {
checkedActivities.value.splice(index, 1);
checkedStatus.value[pointActivity.id] = false;
isCheckAll.value = false;
}
}
// 计算全选框状态
if (isCalcCheckAll) {
const list = gridApi.grid.getData();
calculateIsCheckAll(list);
}
}
/**
* 查找活动在已选中列表中的索引
*/
function findCheckedIndex(activityVO: MallPointActivityApi.PointActivity) {
return checkedActivities.value.findIndex((item) => item.id === activityVO.id);
}
/**
* 计算全选框状态
*/
function calculateIsCheckAll(list: MallPointActivityApi.PointActivity[]) {
isCheckAll.value = list.every(
(activityVO) => checkedStatus.value[activityVO.id],
);
isIndeterminate.value =
!isCheckAll.value &&
list.some((activityVO) => checkedStatus.value[activityVO.id]);
}
/**
* 多选:确认选择
*/
function handleConfirm() {
emit('change', [...checkedActivities.value]);
modalApi.close();
}
/**
* 打开对话框
*/
function open(pointList?: MallPointActivityApi.PointActivity[]) {
// 重置
checkedActivities.value = [];
checkedStatus.value = {};
isCheckAll.value = false;
isIndeterminate.value = false;
// 处理已选中
if (pointList && pointList.length > 0) {
checkedActivities.value = [...pointList];
checkedStatus.value = Object.fromEntries(
pointList.map((activityVO) => [activityVO.id, true]),
);
}
modalApi.open();
}
// 暴露 open 方法
defineExpose({ open });
// 初始化弹窗
const [Modal, modalApi] = useVbenModal({
onConfirm: props.multiple ? handleConfirm : undefined,
destroyOnClose: true,
showConfirmButton: props.multiple, // 特殊radio 单选情况下,走 handleRadioChange 处理。
onConfirm: () => {
const selectedRows =
gridApi.grid.getCheckboxRecords() as MallPointActivityApi.PointActivity[];
emit('change', selectedRows);
modalApi.close();
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
// 关闭时清理状态
if (!props.multiple) {
selectedActivityId.value = undefined;
}
await gridApi.grid.clearCheckboxRow();
await gridApi.grid.clearRadioRow();
return;
}
// 打开时触发查询
// 1. 先查询数据
await gridApi.query();
// 2. 设置已选中行
const data = modalApi.getData<
MallPointActivityApi.PointActivity | MallPointActivityApi.PointActivity[]
>();
if (props.multiple && Array.isArray(data) && data.length > 0) {
setTimeout(() => {
const tableData = gridApi.grid.getTableData().fullData;
data.forEach((activity) => {
const row = tableData.find(
(item: MallPointActivityApi.PointActivity) =>
item.id === activity.id,
);
if (row) {
gridApi.grid.setCheckboxRow(row, true);
}
});
}, 300);
} else if (!props.multiple && data && !Array.isArray(data)) {
setTimeout(() => {
const tableData = gridApi.grid.getTableData().fullData;
const row = tableData.find(
(item: MallPointActivityApi.PointActivity) => item.id === data.id,
);
if (row) {
gridApi.grid.setRadioRow(row);
}
}, 300);
}
},
});
/** 对外暴露的方法 */
defineExpose({
open: (
data?:
| MallPointActivityApi.PointActivity
| MallPointActivityApi.PointActivity[],
) => {
modalApi.setData(data).open();
},
});
</script>
<template>
<Modal class="w-[70%]" title="选择活动">
<Grid>
<!-- 多选表头 checkbox -->
<template v-if="props.multiple" #checkbox-header>
<Checkbox
v-model:checked="isCheckAll"
:indeterminate="isIndeterminate"
@change="handleCheckAll"
/>
</template>
<!-- 多选 checkbox -->
<template v-if="props.multiple" #checkbox-column="{ row }">
<Checkbox
v-model:checked="checkedStatus[row.id]"
@change="(e: any) => handleCheckOne(e.target.checked, row, true)"
/>
</template>
<!-- 单选 radio -->
<template v-if="!props.multiple" #radio-column="{ row }">
<Radio
:checked="selectedActivityId === row.id"
:value="row.id"
class="cursor-pointer"
@click="handleSingleSelected(row)"
/>
</template>
</Grid>
<Modal title="选择活动" class="w-[950px]">
<Grid />
</Modal>
</template>

View File

@@ -0,0 +1 @@
export { default as SeckillShowcase } from './showcase.vue';

View File

@@ -0,0 +1,148 @@
<!-- 秒杀活动橱窗组件用于展示和选择秒杀活动 -->
<script lang="ts" setup>
import type { MallSeckillActivityApi } from '#/api/mall/promotion/seckill/seckillActivity';
import { computed, ref, watch } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { Image, Tooltip } from 'ant-design-vue';
import { getSeckillActivityListByIds } from '#/api/mall/promotion/seckill/seckillActivity';
import SeckillTableSelect from './table-select.vue';
interface SeckillShowcaseProps {
modelValue?: number | number[];
limit?: number;
disabled?: boolean;
}
const props = withDefaults(defineProps<SeckillShowcaseProps>(), {
modelValue: undefined,
limit: Number.MAX_VALUE,
disabled: false,
});
const emit = defineEmits(['update:modelValue', 'change']);
const activityList = ref<MallSeckillActivityApi.SeckillActivity[]>([]); // 已选择的活动列表
const seckillTableSelectRef = ref<InstanceType<typeof SeckillTableSelect>>(); // 活动选择表格组件引用
const isMultiple = computed(() => props.limit !== 1); // 是否为多选模式
/** 计算是否可以添加 */
const canAdd = computed(() => {
if (props.disabled) {
return false;
}
if (!props.limit) {
return true;
}
return activityList.value.length < props.limit;
});
/** 监听 modelValue 变化,加载活动详情 */
watch(
() => props.modelValue,
async (newValue) => {
// eslint-disable-next-line unicorn/no-nested-ternary
const ids = Array.isArray(newValue) ? newValue : newValue ? [newValue] : [];
if (ids.length === 0) {
activityList.value = [];
return;
}
// 只有活动发生变化时才重新查询
if (
activityList.value.length === 0 ||
activityList.value.some((activity) => !ids.includes(activity.id!))
) {
activityList.value = await getSeckillActivityListByIds(ids as number[]);
}
},
{ immediate: true },
);
/** 打开活动选择对话框 */
function handleOpenActivitySelect() {
seckillTableSelectRef.value?.open(activityList.value);
}
/** 选择活动后触发 */
function handleActivitySelected(
activities:
| MallSeckillActivityApi.SeckillActivity
| MallSeckillActivityApi.SeckillActivity[],
) {
activityList.value = Array.isArray(activities) ? activities : [activities];
emitActivityChange();
}
/** 删除活动 */
function handleRemoveActivity(index: number) {
activityList.value.splice(index, 1);
emitActivityChange();
}
/** 触发变更事件 */
function emitActivityChange() {
if (props.limit === 1) {
const activity =
activityList.value.length > 0 ? activityList.value[0] : null;
emit('update:modelValue', activity?.id || 0);
emit('change', activity);
} else {
emit(
'update:modelValue',
activityList.value.map((activity) => activity.id!),
);
emit('change', activityList.value);
}
}
</script>
<template>
<div class="flex flex-wrap items-center gap-2">
<!-- 已选活动列表 -->
<div
v-for="(activity, index) in activityList"
:key="activity.id"
class="relative h-[60px] w-[60px] overflow-hidden rounded-lg border border-dashed border-gray-300"
>
<Tooltip :title="activity.name">
<div class="relative h-full w-full">
<Image
:preview="true"
:src="activity.picUrl"
class="h-full w-full rounded-lg object-cover"
/>
<!-- 删除按钮 -->
<!-- TODO @芋艿等待和 /Users/yunai/Java/yudao-ui-admin-vben-v5/apps/web-antd/src/views/mall/product/spu/components/spu-showcase.vue 进一步统一 -->
<IconifyIcon
v-if="!disabled"
icon="lucide:x"
class="absolute -right-2 -top-2 z-10 h-5 w-5 cursor-pointer text-red-500 hover:text-red-600"
@click="handleRemoveActivity(index)"
/>
</div>
</Tooltip>
</div>
<!-- 添加活动按钮 -->
<Tooltip v-if="canAdd" title="选择活动">
<div
class="flex h-[60px] w-[60px] cursor-pointer items-center justify-center rounded-lg border border-dashed border-gray-300 hover:border-blue-400"
@click="handleOpenActivitySelect"
>
<!-- TODO @芋艿等待和 /Users/yunai/Java/yudao-ui-admin-vben-v5/apps/web-antd/src/views/mall/product/spu/components/spu-showcase.vue 进一步统一 -->
<IconifyIcon icon="lucide:plus" class="text-xl text-gray-400" />
</div>
</Tooltip>
</div>
<!-- 活动选择对话框 -->
<SeckillTableSelect
ref="seckillTableSelectRef"
:multiple="isMultiple"
@change="handleActivitySelected"
/>
</template>

View File

@@ -0,0 +1,277 @@
<!-- 秒杀活动选择弹窗组件 -->
<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { MallCategoryApi } from '#/api/mall/product/category';
import type { MallSeckillActivityApi } from '#/api/mall/promotion/seckill/seckillActivity';
import { computed, onMounted, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { fenToYuan, formatDate, handleTree } from '@vben/utils';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getCategoryList } from '#/api/mall/product/category';
import { getSeckillActivityPage } from '#/api/mall/promotion/seckill/seckillActivity';
interface SeckillTableSelectProps {
multiple?: boolean; // 是否多选true - checkboxfalse - radio
}
const props = withDefaults(defineProps<SeckillTableSelectProps>(), {
multiple: false,
});
const emit = defineEmits<{
change: [
activity:
| MallSeckillActivityApi.SeckillActivity
| MallSeckillActivityApi.SeckillActivity[],
];
}>();
const categoryList = ref<MallCategoryApi.Category[]>([]); // 分类列表
const categoryTreeList = ref<any[]>([]); // 分类树
/** 单选:处理选中变化 */
function handleRadioChange() {
const selectedRow =
gridApi.grid.getRadioRecord() as MallSeckillActivityApi.SeckillActivity;
if (selectedRow) {
emit('change', selectedRow);
modalApi.close();
}
}
/**
* 格式化秒杀价格
* @param products
*/
const formatSeckillPrice = (
products: MallSeckillActivityApi.SeckillProduct[],
) => {
if (!products || products.length === 0) return '-';
const seckillPrice = Math.min(
...products.map((item) => item.seckillPrice || 0),
);
return `${fenToYuan(seckillPrice)}`;
};
/** 搜索表单 Schema */
const formSchema = computed<VbenFormSchema[]>(() => [
{
fieldName: 'name',
label: '活动名称',
component: 'Input',
componentProps: {
placeholder: '请输入活动名称',
clearable: true,
},
},
{
fieldName: 'status',
label: '活动状态',
component: 'Select',
componentProps: {
placeholder: '请选择活动状态',
clearable: true,
options: getDictOptions(DICT_TYPE.COMMON_STATUS, 'number'),
},
},
]);
/** 表格列配置 */
const gridColumns = computed<VxeGridProps['columns']>(() => {
const columns: VxeGridProps['columns'] = [];
if (props.multiple) {
columns.push({ type: 'checkbox', width: 55 });
} else {
columns.push({ type: 'radio', width: 55 });
}
columns.push(
{
field: 'id',
title: '活动编号',
minWidth: 80,
align: 'center',
},
{
field: 'name',
title: '活动名称',
minWidth: 140,
},
{
field: 'activityTime',
title: '活动时间',
minWidth: 210,
formatter: ({ row }) => {
return `${formatDate(row.startTime, 'YYYY-MM-DD')} ~ ${formatDate(row.endTime, 'YYYY-MM-DD')}`;
},
},
{
field: 'picUrl',
title: '商品图片',
width: 100,
align: 'center',
cellRender: {
name: 'CellImage',
},
},
{
field: 'spuName',
title: '商品标题',
minWidth: 300,
},
{
field: 'marketPrice',
title: '原价',
minWidth: 100,
align: 'center',
formatter: ({ cellValue }) => {
return cellValue ? `${fenToYuan(cellValue)}` : '-';
},
},
{
field: 'products',
title: '秒杀价',
minWidth: 100,
align: 'center',
formatter: ({ cellValue }) => {
return formatSeckillPrice(cellValue);
},
},
{
field: 'status',
title: '活动状态',
minWidth: 100,
align: 'center',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.COMMON_STATUS },
},
},
{
field: 'createTime',
title: '创建时间',
width: 180,
align: 'center',
cellRender: {
name: 'CellDatetime',
},
},
);
return columns;
});
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: formSchema.value,
layout: 'horizontal',
collapsed: false,
},
gridOptions: {
columns: gridColumns.value,
height: 500,
border: true,
checkboxConfig: {
reserve: true,
},
radioConfig: {
reserve: true,
},
rowConfig: {
keyField: 'id',
isHover: true,
},
proxyConfig: {
ajax: {
async query({ page }: any, formValues: any) {
return await getSeckillActivityPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
...formValues,
});
},
},
},
},
gridEvents: {
radioChange: handleRadioChange,
},
});
const [Modal, modalApi] = useVbenModal({
destroyOnClose: true,
showConfirmButton: props.multiple, // 特殊radio 单选情况下,走 handleRadioChange 处理。
onConfirm: () => {
const selectedRows =
gridApi.grid.getCheckboxRecords() as MallSeckillActivityApi.SeckillActivity[];
emit('change', selectedRows);
modalApi.close();
},
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
await gridApi.grid.clearCheckboxRow();
await gridApi.grid.clearRadioRow();
return;
}
// 1. 先查询数据
await gridApi.query();
// 2. 设置已选中行
const data = modalApi.getData<
| MallSeckillActivityApi.SeckillActivity
| MallSeckillActivityApi.SeckillActivity[]
>();
if (props.multiple && Array.isArray(data) && data.length > 0) {
setTimeout(() => {
const tableData = gridApi.grid.getTableData().fullData;
data.forEach((activity) => {
const row = tableData.find(
(item: MallSeckillActivityApi.SeckillActivity) =>
item.id === activity.id,
);
if (row) {
gridApi.grid.setCheckboxRow(row, true);
}
});
}, 300);
} else if (!props.multiple && data && !Array.isArray(data)) {
setTimeout(() => {
const tableData = gridApi.grid.getTableData().fullData;
const row = tableData.find(
(item: MallSeckillActivityApi.SeckillActivity) => item.id === data.id,
);
if (row) {
gridApi.grid.setRadioRow(row);
}
}, 300);
}
},
});
/** 对外暴露的方法 */
defineExpose({
open: (
data?:
| MallSeckillActivityApi.SeckillActivity
| MallSeckillActivityApi.SeckillActivity[],
) => {
modalApi.setData(data).open();
},
});
/** 初始化分类数据 */
onMounted(async () => {
categoryList.value = await getCategoryList({});
categoryTreeList.value = handleTree(categoryList.value, 'id', 'parentId');
});
</script>
<template>
<Modal title="选择活动" class="w-[950px]">
<Grid />
</Modal>
</template>

View File

@@ -0,0 +1,138 @@
<script lang="ts" setup>
import type { Rule } from 'ant-design-vue/es/form';
import type { Reply } from '#/views/mp/modules/wx-reply';
import { computed, ref } from 'vue';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { Form, FormItem, Input, Select, SelectOption } from 'ant-design-vue';
import { WxReplySelect } from '#/views/mp/modules/wx-reply';
import { MsgType } from './types';
defineOptions({ name: 'ReplyForm' });
const props = defineProps<{
modelValue: any;
msgType: MsgType;
reply: Reply;
}>();
const emit = defineEmits<{
(e: 'update:reply', v: Reply): void;
(e: 'update:modelValue', v: any): void;
}>();
const reply = computed<Reply>({
get: () => props.reply,
set: (val) => emit('update:reply', val),
});
const replyForm = computed<any>({
get: () => props.modelValue,
set: (val) => emit('update:modelValue', val),
});
const formRef = ref(); // 表单 ref
const RequestMessageTypes = [
'text',
'image',
'voice',
'video',
'shortvideo',
'location',
'link',
]; // 允许选择的请求消息类型
// 表单校验规则
const rules = {
requestKeyword: [
{ required: true, message: '请求的关键字不能为空', trigger: 'blur' },
] as Rule[],
requestMatch: [
{ required: true, message: '请求的关键字的匹配不能为空', trigger: 'blur' },
] as Rule[],
} as Record<string, Rule[]>;
defineExpose({
resetFields: () => formRef.value?.resetFields(),
validate: async () => {
await formRef.value?.validate();
},
});
</script>
<template>
<!-- TODO @hw可以使用 <Form class="mx-4" /> 这种组件形式么 融合到 /Users/yunai/Java/yudao-ui-admin-vben-v5/apps/web-antd/src/views/mp/autoReply/modules/form.vue -->
<div>
<Form
ref="formRef"
:model="replyForm"
:rules="rules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
>
<FormItem
label="消息类型"
name="requestMessageType"
v-if="msgType === MsgType.Message"
>
<Select
v-model:value="replyForm.requestMessageType"
placeholder="请选择"
>
<SelectOption
v-for="dict in getDictOptions(DICT_TYPE.MP_MESSAGE_TYPE).filter(
(d) => RequestMessageTypes.includes(d.value as string),
)"
:key="dict.value"
:value="dict.value"
>
{{ dict.label }}
</SelectOption>
</Select>
</FormItem>
<FormItem
label="匹配类型"
name="requestMatch"
v-if="msgType === MsgType.Keyword"
>
<Select
v-model:value="replyForm.requestMatch"
placeholder="请选择匹配类型"
allow-clear
>
<SelectOption
v-for="dict in getDictOptions(
DICT_TYPE.MP_AUTO_REPLY_REQUEST_MATCH,
'number',
)"
:key="String(dict.value)"
:value="dict.value"
>
{{ dict.label }}
</SelectOption>
</Select>
</FormItem>
<FormItem
label="关键词"
name="requestKeyword"
v-if="msgType === MsgType.Keyword"
>
<Input
v-model:value="replyForm.requestKeyword"
placeholder="请输入内容"
allow-clear
/>
</FormItem>
<FormItem label="回复消息">
<WxReplySelect v-model="reply" />
</FormItem>
</Form>
</div>
</template>

View File

@@ -0,0 +1,55 @@
<script lang="ts" setup>
import { WxMusic } from '#/views/mp/modules/wx-music';
import { WxNews } from '#/views/mp/modules/wx-news';
import { WxVideoPlayer } from '#/views/mp/modules/wx-video-play';
import { WxVoicePlayer } from '#/views/mp/modules/wx-voice-play';
// TODO @hw迁移到 /Users/yunai/Java/yudao-ui-admin-vben-v5/apps/web-antd/src/views/mp/autoReply/modules 里;组件名可能要换一个,= = 之前写的不太好;类似 content.vue ?本质是内容~
defineOptions({ name: 'ReplyContentCell' });
const props = defineProps<{
row: any;
}>();
</script>
<template>
<div>
<div v-if="props.row.responseMessageType === 'text'">
{{ props.row.responseContent }}
</div>
<div v-else-if="props.row.responseMessageType === 'voice'">
<WxVoicePlayer
v-if="props.row.responseMediaUrl"
:url="props.row.responseMediaUrl"
/>
</div>
<div v-else-if="props.row.responseMessageType === 'image'">
<a target="_blank" :href="props.row.responseMediaUrl">
<img :src="props.row.responseMediaUrl" style="width: 100px" />
</a>
</div>
<div
v-else-if="
props.row.responseMessageType === 'video' ||
props.row.responseMessageType === 'shortvideo'
"
>
<WxVideoPlayer
v-if="props.row.responseMediaUrl"
:url="props.row.responseMediaUrl"
style="margin-top: 10px"
/>
</div>
<div v-else-if="props.row.responseMessageType === 'news'">
<WxNews :articles="props.row.responseArticles" />
</div>
<div v-else-if="props.row.responseMessageType === 'music'">
<WxMusic
:title="props.row.responseTitle"
:description="props.row.responseDescription"
:thumb-media-url="props.row.responseThumbMediaUrl"
:music-url="props.row.responseMusicUrl"
:hq-music-url="props.row.responseHqMusicUrl"
/>
</div>
</div>
</template>

View File

@@ -0,0 +1,7 @@
// 消息类型Follow: 关注时回复Message: 消息回复Keyword: 关键词回复)
// 作为 tab.nameenum 的数字不能随意修改,与 api 参数相关
export enum MsgType {
Follow = 1,
Keyword = 3,
Message = 2,
}

View File

@@ -0,0 +1,88 @@
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeGridPropTypes } from '#/adapter/vxe-table';
import { markRaw } from 'vue';
import { DICT_TYPE } from '@vben/constants';
import { WxAccountSelect } from '#/views/mp/modules/wx-account-select';
import { MsgType } from './components/types';
/** 获取表格列配置 */
export function useGridColumns(msgType: MsgType): VxeGridPropTypes.Columns {
const columns: VxeGridPropTypes.Columns = [];
// 请求消息类型列(仅消息回复显示)
if (msgType === MsgType.Message) {
columns.push({
field: 'requestMessageType',
title: '请求消息类型',
minWidth: 120,
});
}
// 关键词列(仅关键词回复显示)
if (msgType === MsgType.Keyword) {
columns.push({
field: 'requestKeyword',
title: '关键词',
minWidth: 150,
});
}
// 匹配类型列(仅关键词回复显示)
if (msgType === MsgType.Keyword) {
columns.push({
field: 'requestMatch',
title: '匹配类型',
minWidth: 120,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.MP_AUTO_REPLY_REQUEST_MATCH },
},
});
}
// 回复消息类型列
columns.push(
{
field: 'responseMessageType',
title: '回复消息类型',
minWidth: 120,
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.MP_MESSAGE_TYPE },
},
},
{
field: 'responseContent',
title: '回复内容',
minWidth: 200,
slots: { default: 'replyContent' },
},
{
field: 'createTime',
title: '创建时间',
minWidth: 180,
formatter: 'formatDateTime',
},
{
title: '操作',
width: 140,
fixed: 'right',
slots: { default: 'actions' },
},
);
return columns;
}
/** 列表的搜索表单 */
export function useGridFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'accountId',
label: '公众号',
component: markRaw(WxAccountSelect),
},
];
}

View File

@@ -1,29 +1,261 @@
<script lang="ts" setup>
import { DocAlert, Page } from '@vben/common-ui';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import { Button } from 'ant-design-vue';
import { computed, nextTick, onMounted, ref } from 'vue';
import {
confirm,
ContentWrap,
DocAlert,
Page,
useVbenModal,
} from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
import { message, Row, Tabs } from 'ant-design-vue';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import * as MpAutoReplyApi from '#/api/mp/autoReply';
import { $t } from '#/locales';
import ReplyContentCell from './components/ReplyTable.vue';
import { MsgType } from './components/types';
import { useGridColumns, useGridFormSchema } from './data';
import Form from './modules/form.vue';
defineOptions({ name: 'MpAutoReply' });
const msgType = ref<string>(String(MsgType.Keyword)); // 消息类型
/** 切换回复类型 */
async function onTabChange(tabName: string) {
msgType.value = tabName;
await nextTick();
// 更新 columns
const columns = useGridColumns(Number(msgType.value) as MsgType);
if (columns) {
// 使用 setGridOptions 更新列配置
gridApi.setGridOptions({ columns });
// 等待列配置更新完成
await nextTick();
}
// 查询数据
await gridApi.query();
updateTableDataLength();
}
/** 新增按钮操作 */
async function handleCreate() {
const formValues = await gridApi.formApi.getValues();
formModalApi
.setData({
isCreating: true,
msgType: Number(msgType.value) as MsgType,
accountId: formValues.accountId,
})
.open();
}
/** 修改按钮操作 */
async function handleEdit(row: any) {
const data = (await MpAutoReplyApi.getAutoReply(row.id)) as any;
formModalApi
.setData({
isCreating: false,
msgType: Number(msgType.value) as MsgType,
row: data,
})
.open();
}
/** 删除按钮操作 */
async function handleDelete(row: any) {
await confirm('是否确认删除此数据?');
const hideLoading = message.loading({
content: $t('ui.actionMessage.deleting', ['自动回复']),
duration: 0,
});
try {
await MpAutoReplyApi.deleteAutoReply(row.id);
message.success('删除成功');
await gridApi.query();
// 查询完成后更新数据长度
updateTableDataLength();
} finally {
hideLoading();
}
}
const [FormModal, formModalApi] = useVbenModal({
connectedComponent: Form,
destroyOnClose: true,
});
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: useGridFormSchema(),
submitOnChange: true, // 表单值变化时自动提交,这样 accountId 会被正确传递到查询函数
},
gridOptions: {
columns: useGridColumns(Number(msgType.value) as MsgType),
height: 'calc(100vh - 300px)',
keepSource: true,
proxyConfig: {
ajax: {
query: async ({ page }, formValues) => {
return await MpAutoReplyApi.getAutoReplyPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
type: Number(msgType.value) as MsgType,
...formValues,
});
},
},
autoLoad: false, // 禁用自动加载,等表单初始化完成后再加载
},
rowConfig: {
keyField: 'id',
isHover: true,
},
toolbarConfig: {
refresh: true,
search: true,
},
} as VxeTableGridOptions<any>,
});
// TODO @hw按道理说不太需呀哦这个可以微信讨论下哈
const tableDataLength = ref(0); // 表格数据长度,用于判断是否显示新增按钮
/** 更新表格数据长度(避免在模板中直接调用 getTableData 导致响应式循环) */
function updateTableDataLength() {
try {
if (!gridApi.grid) {
return;
}
const tableData = gridApi.grid.getTableData();
tableDataLength.value = tableData?.tableData?.length || 0;
} catch {
tableDataLength.value = 0;
}
}
// TODO @hw这个要不改成直接 tableaction 那判断;
// 计算是否显示新增按钮:关注时回复类型只有在没有数据时才显示
const showCreateButton = computed(() => {
if (Number(msgType.value) !== MsgType.Follow) {
return true;
}
return tableDataLength.value <= 0;
});
// TODO @hw看看能不能参考 tag/index.vue 简化下
/** 页面挂载后,等待表单初始化完成再加载数据 */
onMounted(async () => {
// 等待 WxAccountSelect 组件加载并设置默认值
await nextTick();
if (!gridApi.formApi) {
return;
}
const formValues = await gridApi.formApi.getValues();
// 如果 accountId 有值,说明已经准备好了
if (formValues.accountId) {
// 设置为最新提交的值
gridApi.formApi.setLatestSubmissionValues(formValues);
// 触发首次查询
await gridApi.query();
updateTableDataLength();
}
});
</script>
<template>
<Page>
<Page auto-content-height>
<DocAlert title="自动回复" url="https://doc.iocoder.cn/mp/auto-reply/" />
<Button
danger
type="link"
target="_blank"
href="https://github.com/yudaocode/yudao-ui-admin-vue3"
>
该功能支持 Vue3 + element-plus 版本
</Button>
<br />
<Button
type="link"
target="_blank"
href="https://github.com/yudaocode/yudao-ui-admin-vue3/blob/master/src/views/mp/autoReply/index"
>
可参考
https://github.com/yudaocode/yudao-ui-admin-vue3/blob/master/src/views/mp/autoReply/index
代码pull request 贡献给我们
</Button>
<!-- tab 切换 -->
<!-- TODO @hw貌似 tabs 里面套 table 的样式在 vben 里有点丑要不我们按照 /Users/yunai/Java/yudao-ui-admin-vben-v5/apps/web-antd/src/views/mall/trade/afterSale/index.vue1第一层是公众号的选择2第二层是 tab3第三层是 table -->
<ContentWrap>
<Tabs
v-model:active-key="msgType"
@change="(activeKey) => onTabChange(activeKey as string)"
>
<!-- tab -->
<Tabs.TabPane :key="String(MsgType.Follow)">
<template #tab>
<Row align="middle">
<IconifyIcon icon="ep:star" class="mr-2px" /> 关注时回复
</Row>
</template>
</Tabs.TabPane>
<Tabs.TabPane :key="String(MsgType.Message)">
<template #tab>
<Row align="middle">
<IconifyIcon icon="ep:chat-line-round" class="mr-2px" /> 消息回复
</Row>
</template>
</Tabs.TabPane>
<Tabs.TabPane :key="String(MsgType.Keyword)">
<template #tab>
<Row align="middle">
<IconifyIcon icon="fa:newspaper-o" class="mr-2px" /> 关键词回复
</Row>
</template>
</Tabs.TabPane>
</Tabs>
<!-- 列表 -->
<FormModal
@success="
() => {
gridApi.query().then(() => {
updateTableDataLength();
});
}
"
/>
<Grid table-title="自动回复列表">
<template #toolbar-tools>
<TableAction
v-if="showCreateButton"
:actions="[
{
label: $t('ui.actionTitle.create', ['自动回复']),
type: 'primary',
icon: ACTION_ICON.ADD,
auth: ['mp:auto-reply:create'],
onClick: handleCreate,
},
]"
/>
</template>
<template #replyContent="{ row }">
<ReplyContentCell :row="row" />
</template>
<template #actions="{ row }">
<TableAction
:actions="[
{
label: $t('common.edit'),
type: 'link',
icon: ACTION_ICON.EDIT,
auth: ['mp:auto-reply:update'],
onClick: handleEdit.bind(null, row),
},
{
label: $t('common.delete'),
type: 'link',
danger: true,
icon: ACTION_ICON.DELETE,
auth: ['mp:auto-reply:delete'],
popConfirm: {
title: '是否确认删除此数据?',
confirm: handleDelete.bind(null, row),
},
},
]"
/>
</template>
</Grid>
</ContentWrap>
</Page>
</template>

Some files were not shown because too many files have changed in this diff Show More