feat:【antd】【mall】diy-editor 的 promotion-point 初始化 100%

This commit is contained in:
YunaiV
2025-11-02 17:05:18 +08:00
parent 2683f10bb5
commit 39ddf5a1ea
8 changed files with 468 additions and 642 deletions

View File

@@ -2,64 +2,41 @@ import type { ComponentStyle, DiyComponent } from '../../../util';
/** 积分商城属性 */
export interface PromotionPointProperty {
// 布局类型:单列 | 三列
layoutType: 'oneColBigImg' | 'oneColSmallImg' | 'twoCol';
// 商品字段
layoutType: 'oneColBigImg' | 'oneColSmallImg' | 'twoCol'; // 布局类型:单列 | 三列
fields: {
// 商品简介
introduction: PromotionPointFieldProperty;
// 市场价
marketPrice: PromotionPointFieldProperty;
// 商品名称
name: PromotionPointFieldProperty;
// 商品价格
price: PromotionPointFieldProperty;
// 商品销量
salesCount: PromotionPointFieldProperty;
// 商品库存
stock: PromotionPointFieldProperty;
};
// 角标
introduction: PromotionPointFieldProperty; // 商品简介
marketPrice: PromotionPointFieldProperty; // 市场价
name: PromotionPointFieldProperty; // 商品名称
price: PromotionPointFieldProperty; // 商品价格
salesCount: PromotionPointFieldProperty; // 商品销量
stock: PromotionPointFieldProperty; // 商品库存
}; // 商品字段
badge: {
// 角标图片
imgUrl: string;
// 是否显示
show: boolean;
};
imgUrl: string; // 角标图片
show: boolean; // 是否显示
}; // 角标
// 按钮
btnBuy: {
// 文字按钮:背景渐变起始颜色
bgBeginColor: string;
// 文字按钮:背景渐变结束颜色
bgEndColor: string;
// 图片按钮:图片地址
imgUrl: string;
// 文字
text: string;
// 类型:文字 | 图片
type: 'img' | 'text';
};
// 上圆角
borderRadiusTop: number;
// 下圆角
borderRadiusBottom: number;
// 间距
space: number;
// 秒杀活动编号
activityIds: number[];
// 组件样式
style: ComponentStyle;
bgBeginColor: string; // 文字按钮:背景渐变起始颜色
bgEndColor: string; // 文字按钮:背景渐变结束颜色
imgUrl: string; // 图片按钮:图片地址
text: string; // 文字
type: 'img' | 'text'; // 类型:文字 | 图片
}; // 按钮
borderRadiusTop: number; // 上圆角
borderRadiusBottom: number; // 下圆角
space: number; // 间距
activityIds: number[]; // 积分活动编号
style: ComponentStyle; // 组件样式
}
// 商品字段
/** 商品字段属性 */
export interface PromotionPointFieldProperty {
// 是否显示
show: boolean;
// 颜色
color: string;
show: boolean; // 是否显示
color: string; // 颜色
}
// 定义组件
/** 定义组件 */
export const component = {
id: 'PromotionPoint',
name: '积分商城',

View File

@@ -14,10 +14,10 @@ import * as PointActivityApi 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 =
@@ -66,41 +66,33 @@ 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 = () => {
/** 计算商品的宽度 */
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
ref="containerRef"
class="box-content flex min-h-[30px] w-full flex-row flex-wrap"
ref="containerRef"
>
<div
v-for="(spu, index) in spuList"
:key="index"
class="relative box-content flex flex-row flex-wrap overflow-hidden bg-white"
:style="{
...calculateSpace(index),
...calculateWidth(),
@@ -109,17 +101,18 @@ const calculateWidth = () => {
borderBottomLeftRadius: `${property.borderRadiusBottom}px`,
borderBottomRightRadius: `${property.borderRadiusBottom}px`,
}"
class="relative box-content flex flex-row flex-wrap overflow-hidden bg-white"
v-for="(spu, index) in spuList"
:key="index"
>
<!-- 角标 -->
<div
v-if="property.badge.show"
v-if="property.badge.show && property.badge.imgUrl"
class="absolute left-0 top-0 z-[1] items-center justify-center"
>
<ElImage
fit="cover"
:src="property.badge.imgUrl"
class="h-[26px] w-[38px]"
fit="cover"
/>
</div>
<!-- 商品封面图 -->
@@ -132,10 +125,10 @@ const calculateWidth = () => {
},
]"
>
<ElImage :src="spu.picUrl" class="h-full w-full" fit="cover" />
<ElImage fit="cover" class="h-full w-full" :src="spu.picUrl" />
</div>
<div
class="box-border flex flex-col gap-2 p-2"
class="box-border flex flex-col gap-[8px] p-[8px]"
:class="[
{
'w-full': property.layoutType !== 'oneColSmallImg',
@@ -162,8 +155,8 @@ const calculateWidth = () => {
<!-- 商品简介 -->
<div
v-if="property.fields.introduction.show"
:style="{ color: property.fields.introduction.color }"
class="truncate text-[12px]"
:style="{ color: property.fields.introduction.color }"
>
{{ spu.introduction }}
</div>
@@ -171,8 +164,8 @@ const calculateWidth = () => {
<!-- 积分 -->
<span
v-if="property.fields.price.show"
:style="{ color: property.fields.price.color }"
class="text-[16px]"
:style="{ color: property.fields.price.color }"
>
{{ spu.point }}积分
{{
@@ -184,10 +177,10 @@ const calculateWidth = () => {
<!-- 市场价 -->
<span
v-if="property.fields.marketPrice.show && spu.marketPrice"
:style="{ color: property.fields.marketPrice.color }"
class="ml-[4px] text-[10px] line-through"
:style="{ color: property.fields.marketPrice.color }"
>
{{ fenToYuan(spu.marketPrice) }}
{{ fenToYuan(spu.marketPrice!) }}
</span>
</div>
<div class="text-[12px]">
@@ -212,23 +205,21 @@ const calculateWidth = () => {
<!-- 文字按钮 -->
<span
v-if="property.btnBuy.type === 'text'"
class="rounded-full px-[12px] py-[4px] text-[12px] text-white"
:style="{
background: `linear-gradient(to right, ${property.btnBuy.bgBeginColor}, ${property.btnBuy.bgEndColor}`,
}"
class="rounded-full px-[12px] py-[4px] text-[12px] text-white"
>
{{ property.btnBuy.text }}
</span>
<!-- 图片按钮 -->
<ElImage
v-else
:src="property.btnBuy.imgUrl"
class="h-[28px] w-[28px] rounded-full"
fit="cover"
:src="property.btnBuy.imgUrl"
/>
</div>
</div>
</div>
</template>
<style lang="scss" scoped></style>

View File

@@ -16,10 +16,13 @@ import {
ElTooltip,
} from 'element-plus';
import UploadImg from '#/components/upload/image-upload.vue';
import { ColorInput } from '#/views/mall/promotion/components';
import PointShowcase from '#/views/mall/promotion/point/components/point-showcase.vue';
import { PointShowcase } from '#/views/mall/promotion/point/components';
// 秒杀属性面板
import ComponentContainerProperty from '../../component-container-property.vue';
/** 积分属性面板 */
defineOptions({ name: 'PromotionPointProperty' });
const props = defineProps<{ modelValue: PromotionPointProperty }>();
@@ -29,11 +32,11 @@ const formData = useVModel(props, 'modelValue', emit);
<template>
<ComponentContainerProperty v-model="formData.style">
<ElForm :model="formData" label-width="80px">
<ElCard class="property-group" header="积分商城活动" shadow="never">
<ElForm label-width="80px" :model="formData">
<ElCard header="积分商城活动" class="property-group" shadow="never">
<PointShowcase v-model="formData.activityIds" />
</ElCard>
<ElCard class="property-group" header="商品样式" shadow="never">
<ElCard header="商品样式" class="property-group" shadow="never">
<ElFormItem label="布局" prop="type">
<ElRadioGroup v-model="formData.layoutType">
<ElTooltip class="item" content="单列大图" placement="bottom">
@@ -51,11 +54,11 @@ const formData = useVModel(props, 'modelValue', emit);
<IconifyIcon icon="fluent:text-column-two-24-filled" />
</ElRadioButton>
</ElTooltip>
<!--<el-tooltip class="item" content="三列" placement="bottom">
<el-radio-button value="threeCol">
<!--<ElTooltip class="item" content="三列" placement="bottom">
<ElRadioButton value="threeCol">
<IconifyIcon icon="fluent:text-column-three-24-filled" />
</el-radio-button>
</el-tooltip>-->
</ElRadioButton>
</ElTooltip>-->
</ElRadioGroup>
</ElFormItem>
<ElFormItem label="商品名称" prop="fields.name.show">
@@ -95,22 +98,22 @@ const formData = useVModel(props, 'modelValue', emit);
</div>
</ElFormItem>
</ElCard>
<ElCard class="property-group" header="角标" shadow="never">
<ElCard header="角标" class="property-group" shadow="never">
<ElFormItem label="角标" prop="badge.show">
<ElSwitch v-model="formData.badge.show" />
</ElFormItem>
<ElFormItem v-if="formData.badge.show" label="角标" prop="badge.imgUrl">
<ElFormItem label="角标" prop="badge.imgUrl" v-if="formData.badge.show">
<UploadImg
v-model="formData.badge.imgUrl"
height="44px"
width="72px"
:show-description="false"
>
<template #tip> 建议尺寸36 * 22</template>
<template #tip> 建议尺寸36 * 22 </template>
</UploadImg>
</ElFormItem>
</ElCard>
<ElCard class="property-group" header="按钮" shadow="never">
<ElCard header="按钮" class="property-group" shadow="never">
<ElFormItem label="按钮类型" prop="btnBuy.type">
<ElRadioGroup v-model="formData.btnBuy.type">
<ElRadioButton value="text">文字</ElRadioButton>
@@ -136,20 +139,20 @@ const formData = useVModel(props, 'modelValue', emit);
width="56px"
:show-description="false"
>
<template #tip> 建议尺寸56 * 56</template>
<template #tip> 建议尺寸56 * 56 </template>
</UploadImg>
</ElFormItem>
</template>
</ElCard>
<ElCard class="property-group" header="商品样式" shadow="never">
<ElCard header="商品样式" class="property-group" shadow="never">
<ElFormItem label="上圆角" prop="borderRadiusTop">
<ElSlider
v-model="formData.borderRadiusTop"
:max="100"
:min="0"
:show-input-controls="false"
input-size="small"
show-input
input-size="small"
:show-input-controls="false"
/>
</ElFormItem>
<ElFormItem label="下圆角" prop="borderRadiusBottom">
@@ -157,9 +160,9 @@ const formData = useVModel(props, 'modelValue', emit);
v-model="formData.borderRadiusBottom"
:max="100"
:min="0"
:show-input-controls="false"
input-size="small"
show-input
input-size="small"
:show-input-controls="false"
/>
</ElFormItem>
<ElFormItem label="间隔" prop="space">
@@ -167,14 +170,12 @@ const formData = useVModel(props, 'modelValue', emit);
v-model="formData.space"
:max="100"
:min="0"
:show-input-controls="false"
input-size="small"
show-input
input-size="small"
:show-input-controls="false"
/>
</ElFormItem>
</ElCard>
</ElForm>
</ComponentContainerProperty>
</template>
<style lang="scss" scoped></style>

View File

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

View File

@@ -1,178 +0,0 @@
<script lang="ts" setup>
import type { MallPointActivityApi } from '#/api/mall/promotion/point';
import { computed, ref, watch } from 'vue';
import { ElImage, ElTooltip } from 'element-plus';
import * as PointActivityApi from '#/api/mall/promotion/point';
import PointTableSelect from './point-table-select.vue';
// 活动橱窗,一般用于装修时使用
// 提供功能:展示活动列表、添加活动、删除活动
defineOptions({ name: 'PointShowcase' });
const props = defineProps({
modelValue: {
type: [Number, Array],
required: true,
},
// 限制数量:默认不限制
limit: {
type: Number,
default: Number.MAX_VALUE,
},
disabled: {
type: Boolean,
default: false,
},
});
const emit = defineEmits(['update:modelValue', 'change']);
// 计算是否可以添加
const canAdd = computed(() => {
// 情况一:禁用时不可以添加
if (props.disabled) return false;
// 情况二:未指定限制数量时,可以添加
if (!props.limit) return true;
// 情况三:检查已添加数量是否小于限制数量
return pointActivityList.value.length < props.limit;
});
// 拼团活动列表
const pointActivityList = ref<MallPointActivityApi.PointActivity[]>([]);
watch(
() => props.modelValue,
async () => {
let ids;
if (Array.isArray(props.modelValue)) {
ids = props.modelValue;
} else {
ids = props.modelValue ? [props.modelValue] : [];
}
// 不需要返显
if (ids.length === 0) {
pointActivityList.value = [];
return;
}
// 只有活动发生变化之后,才会查询活动
if (
pointActivityList.value.length === 0 ||
pointActivityList.value.some(
(pointActivity) => !ids.includes(pointActivity.id!),
)
) {
pointActivityList.value =
await PointActivityApi.getPointActivityListByIds(ids as number[]);
}
},
{ immediate: true },
);
/** 活动表格选择对话框 */
const pointActivityTableSelectRef = ref();
// 打开对话框
const openSeckillActivityTableSelect = () => {
pointActivityTableSelectRef.value.open(pointActivityList.value);
};
/**
* 选择活动后触发
* @param activityList 选中的活动列表
*/
const handleActivitySelected = (
activityList:
| MallPointActivityApi.PointActivity
| MallPointActivityApi.PointActivity[],
) => {
pointActivityList.value = Array.isArray(activityList)
? activityList
: [activityList];
emitActivityChange();
};
/**
* 删除活动
* @param index 活动索引
*/
const handleRemoveActivity = (index: number) => {
pointActivityList.value.splice(index, 1);
emitActivityChange();
};
const 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);
}
};
</script>
<template>
<div class="gap-8px flex flex-wrap items-center">
<div
v-for="(pointActivity, index) in pointActivityList"
:key="pointActivity.id"
class="select-box spu-pic"
>
<ElTooltip :content="pointActivity.spuName">
<div class="relative h-full w-full">
<ElImage :src="pointActivity.picUrl" class="h-full w-full" />
<IconifyIcon
v-show="!disabled"
class="del-icon"
icon="ep:circle-close-filled"
@click="handleRemoveActivity(index)"
/>
</div>
</ElTooltip>
</div>
<ElTooltip v-if="canAdd" content="选择活动">
<div class="select-box" @click="openSeckillActivityTableSelect">
<IconifyIcon icon="ep:plus" />
</div>
</ElTooltip>
</div>
<!-- 拼团活动选择对话框表格形式 -->
<PointTableSelect
ref="pointActivityTableSelectRef"
:multiple="limit !== 1"
@change="handleActivitySelected"
/>
</template>
<style lang="scss" scoped>
.select-box {
display: flex;
align-items: center;
justify-content: center;
width: 60px;
height: 60px;
cursor: pointer;
border: 1px dashed var(--el-border-color-darker);
border-radius: 8px;
}
.spu-pic {
position: relative;
}
.del-icon {
position: absolute;
top: -10px;
right: -10px;
z-index: 1;
width: 20px !important;
height: 20px !important;
}
</style>

View File

@@ -1,354 +0,0 @@
<script lang="ts" setup>
import type { MallPointActivityApi } from '#/api/mall/promotion/point';
import { computed, ref } from 'vue';
import { ContentWrap } from '@vben/common-ui';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { IconifyIcon } from '@vben/icons';
import { dateFormatter, fenToYuanFormat } from '@vben/utils';
import { CHANGE_EVENT } from 'element-plus';
import * as PointActivityApi from '#/api/mall/promotion/point';
/**
* 活动表格选择对话框
* 1. 单选模式:
* 1.1 点击表格左侧的单选框时,结束选择,并关闭对话框
* 1.2 再次打开时,保持选中状态
* 2. 多选模式:
* 2.1 点击表格左侧的多选框时,记录选中的活动
* 2.2 切换分页时,保持活动的选中状态
* 2.3 点击右下角的确定按钮时,结束选择,关闭对话框
* 2.4 再次打开时,保持选中状态
*/
defineOptions({ name: 'PointTableSelect' });
defineProps({
// 多选模式
multiple: {
type: Boolean,
default: false,
},
});
/** 确认选择时的触发事件 */
const emits = defineEmits<{
(
e: 'change',
v:
| any
| MallPointActivityApi.PointActivity
| MallPointActivityApi.PointActivity[],
): void;
}>();
// 列表的总页数
const total = ref(0);
// 列表的数据
const list = ref<MallPointActivityApi.PointActivity[]>([]);
// 列表的加载中
const loading = ref(false);
// 弹窗的是否展示
const dialogVisible = ref(false);
// 查询参数
const queryParams = ref({
pageNo: 1,
pageSize: 10,
name: null,
status: undefined,
});
const getRedeemedQuantity = computed(
() => (row: any) => (row.totalStock || 0) - (row.stock || 0),
); // 获得商品已兑换数量
/** 打开弹窗 */
const 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]),
);
}
dialogVisible.value = true;
resetQuery();
};
// 提供 open 方法,用于打开弹窗
defineExpose({ open });
/** 查询列表 */
const getList = async () => {
loading.value = true;
try {
const data = await PointActivityApi.getPointActivityPage(queryParams.value);
list.value = data.list;
total.value = data.total;
// checkbox绑定undefined会有问题需要给一个bool值
list.value.forEach(
(activityVO) =>
(checkedStatus.value[activityVO.id] =
checkedStatus.value[activityVO.id] || false),
);
// 计算全选框状态
calculateIsCheckAll();
} finally {
loading.value = false;
}
};
/** 搜索按钮操作 */
const handleQuery = () => {
queryParams.value.pageNo = 1;
getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
queryParams.value = {
pageNo: 1,
pageSize: 10,
name: null,
status: undefined,
};
getList();
};
// 是否全选
const isCheckAll = ref(false);
// 全选框是否处于中间状态:不是全部选中 && 任意一个选中
const isIndeterminate = ref(false);
// 选中的活动
const checkedActivities = ref<MallPointActivityApi.PointActivity[]>([]);
// 选中状态key为活动IDvalue为是否选中
const checkedStatus = ref<Record<string, boolean>>({});
// 选中的活动 activityId
const selectedActivityId = ref();
/** 单选中时触发 */
const handleSingleSelected = (
pointActivityVO: MallPointActivityApi.PointActivity,
) => {
emits(CHANGE_EVENT, pointActivityVO);
// 关闭弹窗
dialogVisible.value = false;
// 记住上次选择的ID
selectedActivityId.value = pointActivityVO.id;
};
/** 多选完成 */
const handleEmitChange = () => {
// 关闭弹窗
dialogVisible.value = false;
emits(CHANGE_EVENT, [...checkedActivities.value]);
};
/** 全选/全不选 */
const handleCheckAll = (checked: boolean) => {
isCheckAll.value = checked;
isIndeterminate.value = false;
list.value.forEach((pointActivity) =>
handleCheckOne(checked, pointActivity, false),
);
};
/**
* 选中一行
* @param checked 是否选中
* @param pointActivity 活动
* @param isCalcCheckAll 是否计算全选
*/
const 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) {
calculateIsCheckAll();
}
};
// 查找活动在已选中活动列表中的索引
const findCheckedIndex = (activityVO: MallPointActivityApi.PointActivity) =>
checkedActivities.value.findIndex((item) => item.id === activityVO.id);
// 计算全选框状态
const calculateIsCheckAll = () => {
isCheckAll.value = list.value.every(
(activityVO) => checkedStatus.value[activityVO.id],
);
// 计算中间状态:不是全部选中 && 任意一个选中
isIndeterminate.value =
!isCheckAll.value &&
list.value.some((activityVO) => checkedStatus.value[activityVO.id]);
};
</script>
<template>
<Dialog
v-model="dialogVisible"
:append-to-body="true"
title="选择活动"
width="70%"
>
<ContentWrap>
<!-- 搜索工作栏 -->
<el-form
:inline="true"
:model="queryParams"
class="-mb-15px"
label-width="68px"
>
<el-form-item label="活动状态" prop="status">
<el-select
v-model="queryParams.status"
class="!w-240px"
clearable
placeholder="请选择活动状态"
>
<el-option
v-for="dict in getDictOptions(DICT_TYPE.COMMON_STATUS, 'number')"
:key="dict.value"
:label="dict.label"
:value="dict.value"
/>
</el-select>
</el-form-item>
<el-form-item>
<el-button @click="handleQuery">
<IconifyIcon class="mr-5px" icon="ep:search" />
搜索
</el-button>
<el-button @click="resetQuery">
<IconifyIcon class="mr-5px" icon="ep:refresh" />
重置
</el-button>
</el-form-item>
</el-form>
<el-table v-loading="loading" :data="list" show-overflow-tooltip>
<!-- 1. 多选模式不能使用type="selection"Element会忽略Header插槽 -->
<el-table-column v-if="multiple" width="55">
<template #header>
<el-checkbox
v-model="isCheckAll"
:indeterminate="isIndeterminate"
@change="handleCheckAll"
/>
</template>
<template #default="{ row }">
<el-checkbox
v-model="checkedStatus[row.id]"
@change="(checked: boolean) => handleCheckOne(checked, row, true)"
/>
</template>
</el-table-column>
<!-- 2. 单选模式 -->
<el-table-column v-else label="#" width="55">
<template #default="{ row }">
<el-radio
v-model="selectedActivityId"
:value="row.id"
@change="handleSingleSelected(row)"
>
<!-- 空格不能省略是为了让单选框不显示label如果不指定label不会有选中的效果 -->
&nbsp;
</el-radio>
</template>
</el-table-column>
<el-table-column label="活动编号" min-width="80" prop="id" />
<el-table-column label="商品图片" min-width="80" prop="spuName">
<template #default="scope">
<el-image
:preview-src-list="[scope.row.picUrl]"
:src="scope.row.picUrl"
class="h-40px w-40px"
preview-teleported
/>
</template>
</el-table-column>
<el-table-column label="商品标题" min-width="300" prop="spuName" />
<el-table-column
:formatter="fenToYuanFormat"
label="原价"
min-width="100"
prop="marketPrice"
/>
<el-table-column label="原价" min-width="100" prop="marketPrice" />
<el-table-column
align="center"
label="活动状态"
min-width="100"
prop="status"
>
<template #default="scope">
<dict-tag
:type="DICT_TYPE.COMMON_STATUS"
:value="scope.row.status"
/>
</template>
</el-table-column>
<el-table-column
align="center"
label="库存"
min-width="80"
prop="stock"
/>
<el-table-column
align="center"
label="总库存"
min-width="80"
prop="totalStock"
/>
<el-table-column
align="center"
label="已兑换数量"
min-width="100"
prop="redeemedQuantity"
>
<template #default="{ row }">
{{ getRedeemedQuantity(row) }}
</template>
</el-table-column>
<el-table-column
:formatter="dateFormatter"
align="center"
label="创建时间"
prop="createTime"
width="180px"
/>
</el-table>
<!-- 分页 -->
<Pagination
v-model:limit="queryParams.pageSize"
v-model:page="queryParams.pageNo"
:total="total"
@pagination="getList"
/>
</ContentWrap>
<template v-if="multiple" #footer>
<el-button type="primary" @click="handleEmitChange"> </el-button>
<el-button @click="dialogVisible = false"> </el-button>
</template>
</Dialog>
</template>

View File

@@ -0,0 +1,149 @@
<!-- 积分商城活动橱窗组件用于展示和选择积分商城活动 -->
<script lang="ts" setup>
import type { MallPointActivityApi } from '#/api/mall/promotion/point';
import { computed, ref, watch } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { ElImage, ElTooltip } from 'element-plus';
import { getPointActivityListByIds } from '#/api/mall/promotion/point';
import PointTableSelect from './table-select.vue';
interface PointShowcaseProps {
modelValue?: number | number[];
limit?: number;
disabled?: boolean;
}
const props = withDefaults(defineProps<PointShowcaseProps>(), {
modelValue: undefined,
limit: Number.MAX_VALUE,
disabled: false,
});
const emit = defineEmits(['update:modelValue', 'change']);
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;
}
return pointActivityList.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) {
pointActivityList.value = [];
return;
}
// 只有活动发生变化时才重新查询
if (
pointActivityList.value.length === 0 ||
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="(activity, index) in pointActivityList"
:key="activity.id"
class="group relative h-[60px] w-[60px] overflow-hidden rounded-lg"
>
<ElTooltip :content="activity.spuName">
<div class="relative h-full w-full">
<ElImage
:src="activity.picUrl"
class="h-full w-full rounded-lg object-cover"
:preview-src-list="[activity.picUrl!]"
fit="cover"
/>
<!-- 删除按钮 -->
<IconifyIcon
v-if="!disabled"
icon="ep:circle-close-filled"
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>
</ElTooltip>
</div>
<!-- 添加活动按钮 -->
<ElTooltip v-if="canAdd" content="选择活动">
<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"
>
<IconifyIcon icon="ep:plus" class="text-xl text-gray-400" />
</div>
</ElTooltip>
</div>
<!-- 活动选择对话框 -->
<PointTableSelect
ref="pointTableSelectRef"
:multiple="isMultiple"
@change="handleActivitySelected"
/>
</template>

View File

@@ -0,0 +1,239 @@
<!-- 积分商城活动选择弹窗组件 -->
<script lang="ts" setup>
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { MallPointActivityApi } from '#/api/mall/promotion/point';
import { computed } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { dateFormatter, fenToYuanFormat } from '@vben/utils';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getPointActivityPage } from '#/api/mall/promotion/point';
interface PointTableSelectProps {
multiple?: boolean; // 是否单选true - checkboxfalse - radio
}
const props = withDefaults(defineProps<PointTableSelectProps>(), {
multiple: false,
});
const emit = defineEmits<{
change: [
activity:
| MallPointActivityApi.PointActivity
| MallPointActivityApi.PointActivity[],
];
}>();
/** 单选:处理选中变化 */
function handleRadioChange() {
const selectedRow =
gridApi.grid.getRadioRecord() as MallPointActivityApi.PointActivity;
if (selectedRow) {
emit('change', selectedRow);
modalApi.close();
}
}
/** 计算已兑换数量 */
const getRedeemedQuantity = (row: MallPointActivityApi.PointActivity) =>
(row.totalStock || 0) - (row.stock || 0);
/** 搜索表单 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({ type: 'checkbox', width: 55 });
} else {
columns.push({ type: 'radio', width: 55 });
}
columns.push(
{
field: 'id',
title: '活动编号',
minWidth: 100,
align: 'center',
},
{
field: 'picUrl',
title: '商品图片',
width: 100,
align: 'center',
cellRender: {
name: 'CellImage',
},
},
{
field: 'spuName',
title: '商品标题',
minWidth: 200,
},
{
field: 'marketPrice',
title: '原价',
minWidth: 100,
align: 'center',
formatter: ({ cellValue }) => fenToYuanFormat(cellValue),
},
{
field: 'status',
title: '活动状态',
minWidth: 100,
align: 'center',
cellRender: {
name: 'CellDict',
props: { type: DICT_TYPE.COMMON_STATUS },
},
},
{
field: 'stock',
title: '库存',
minWidth: 80,
align: 'center',
},
{
field: 'totalStock',
title: '总库存',
minWidth: 80,
align: 'center',
},
{
field: 'redeemedQuantity',
title: '已兑换数量',
minWidth: 100,
align: 'center',
formatter: ({ row }) => getRedeemedQuantity(row),
},
{
field: 'createTime',
title: '创建时间',
width: 180,
align: 'center',
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,
checkboxConfig: {
reserve: true,
},
radioConfig: {
reserve: true,
},
rowConfig: {
keyField: 'id',
isHover: true,
},
proxyConfig: {
ajax: {
async query({ page }: any, formValues: any) {
return await getPointActivityPage({
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 MallPointActivityApi.PointActivity[];
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<
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 title="选择活动" class="w-[950px]">
<Grid />
</Modal>
</template>