feat:【antd】【mall】 spu 相关公共组件迁移

pull/277/head
puhui999 2025-11-24 15:03:20 +08:00
parent c842592d10
commit 390d9d7ca7
6 changed files with 609 additions and 8 deletions

View File

@ -1,6 +1,8 @@
export * from './property-util';
export { default as SkuList } from './sku-list.vue';
export { default as SkuTableSelect } from './sku-table-select.vue';
export { default as SpuAndSkuList } from './spu-and-sku-list.vue';
export { default as SpuSkuSelect } from './spu-select.vue';
export { default as SpuShowcase } from './spu-showcase.vue';
export { default as SpuTableSelect } from './spu-table-select.vue';
export * from './type';

View File

@ -0,0 +1,177 @@
<script generic="T extends MallSpuApi.Spu" lang="ts" setup>
import type { RuleConfig, SpuProperty } from './type';
import type { MallSpuApi } from '#/api/mall/product/spu';
import { ref, watch } from 'vue';
import { confirm } from '@vben/common-ui';
import { formatToFraction } from '@vben/utils';
import { Button, Image } from 'ant-design-vue';
import { VxeColumn, VxeTable } from '#/adapter/vxe-table';
import SkuList from './sku-list.vue';
defineOptions({ name: 'PromotionSpuAndSkuList' });
const props = withDefaults(
defineProps<{
deletable?: boolean; // SPU
ruleConfig: RuleConfig[];
spuList: T[];
spuPropertyListP: SpuProperty<T>[];
}>(),
{
deletable: false,
},
);
const emit = defineEmits<{
(e: 'delete', spuId: number): void;
}>();
const spuData = ref<MallSpuApi.Spu[]>([]); // spu
const skuListRef = ref<InstanceType<typeof SkuList> | undefined>(); // Ref
const spuPropertyList = ref<SpuProperty<T>[]>([]); // spuId sku
const expandRowKeys = ref<string[]>([]); // row-key 使 keys
/**
* 获取所有 sku 活动配置
*
* @param extendedAttribute sku 上扩展的属性秒杀活动 sku 扩展属性 productConfig 请参考 seckillActivity.ts
*/
function getSkuConfigs(extendedAttribute: string) {
// SKU ref
if (skuListRef.value) {
try {
skuListRef.value.validateSku();
} catch (error) {
//
throw error;
}
}
const seckillProducts: unknown[] = [];
spuPropertyList.value.forEach((item) => {
item.spuDetail.skus?.forEach((sku) => {
const extendedValue = (sku as Record<string, unknown>)[extendedAttribute];
if (extendedValue) {
seckillProducts.push(extendedValue);
}
});
});
return seckillProducts;
}
// 使
defineExpose({ getSkuConfigs });
/** 多选时可以删除 SPU */
async function deleteSpu(spuId: number) {
await confirm(`是否删除商品编号为${spuId}的数据?`);
const index = spuData.value.findIndex((item) => item.id === spuId);
if (index !== -1) {
spuData.value.splice(index, 1);
emit('delete', spuId);
}
}
/**
* 将传进来的值赋值给 spuData
*/
watch(
() => props.spuList,
(data) => {
if (!data) return;
spuData.value = data as MallSpuApi.Spu[];
},
{
deep: true,
immediate: true,
},
);
/**
* 将传进来的值赋值给 spuPropertyList
*/
watch(
() => props.spuPropertyListP,
(data) => {
if (!data) return;
spuPropertyList.value = data as SpuProperty<T>[];
// spu sku SkuList
setTimeout(() => {
expandRowKeys.value = data.map((item) => String(item.spuId));
}, 200);
},
{
deep: true,
immediate: true,
},
);
</script>
<template>
<VxeTable
:data="spuData"
:expand-row-keys="expandRowKeys"
:row-config="{
keyField: 'id',
}"
>
<VxeColumn type="expand" width="30">
<template #content="{ row }">
<SkuList
ref="skuListRef"
:is-activity-component="true"
:prop-form-data="
spuPropertyList.find((item) => item.spuId === row.id)?.spuDetail
"
:property-list="
spuPropertyList.find((item) => item.spuId === row.id)?.propertyList
"
:rule-config="ruleConfig"
>
<template #extension>
<slot></slot>
</template>
</SkuList>
</template>
</VxeColumn>
<VxeColumn field="id" align="center" title="商品编号" />
<VxeColumn title="商品图" min-width="80">
<template #default="{ row }">
<Image
v-if="row.picUrl"
:src="row.picUrl"
class="h-[30px] w-[30px] cursor-pointer"
:preview="true"
/>
</template>
</VxeColumn>
<VxeColumn
field="name"
title="商品名称"
min-width="300"
show-overflow="tooltip"
/>
<VxeColumn align="center" title="商品售价" min-width="90">
<template #default="{ row }">
{{ formatToFraction(row.price) }}
</template>
</VxeColumn>
<VxeColumn field="salesCount" align="center" title="销量" min-width="90" />
<VxeColumn field="stock" align="center" title="库存" min-width="90" />
<VxeColumn
v-if="spuData.length > 1 && deletable"
align="center"
title="操作"
min-width="90"
>
<template #default="{ row }">
<Button type="link" danger @click="deleteSpu(row.id)"> </Button>
</template>
</VxeColumn>
</VxeTable>
</template>

View File

@ -0,0 +1,129 @@
import type { Ref } from 'vue';
import type { VbenFormSchema } from '#/adapter/form';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MallCategoryApi } from '#/api/mall/product/category';
import { computed } from 'vue';
import { formatToFraction } from '@vben/utils';
import { getRangePickerDefaultProps } from '#/utils';
/**
* @description:
*/
export function useGridFormSchema(
categoryTreeList: Ref<MallCategoryApi.Category[]>,
): VbenFormSchema[] {
return [
{
fieldName: 'name',
label: '商品名称',
component: 'Input',
componentProps: {
placeholder: '请输入商品名称',
allowClear: true,
},
},
{
fieldName: 'categoryId',
label: '商品分类',
component: 'TreeSelect',
componentProps: {
treeData: computed(() => categoryTreeList.value),
fieldNames: {
label: 'name',
value: 'id',
},
treeCheckStrictly: true,
placeholder: '请选择商品分类',
allowClear: true,
showSearch: true,
treeNodeFilterProp: 'name',
},
},
{
fieldName: 'createTime',
label: '创建时间',
component: 'RangePicker',
componentProps: {
...getRangePickerDefaultProps(),
allowClear: true,
},
},
];
}
/**
* @description:
*/
export function useGridColumns(
isSelectSku: boolean,
): VxeTableGridOptions['columns'] {
return [
{
type: 'expand',
width: 30,
visible: isSelectSku,
slots: { content: 'expand_content' },
},
{ type: 'checkbox', width: 55 },
{
field: 'id',
title: '商品编号',
minWidth: 100,
align: 'center',
},
{
field: 'picUrl',
title: '商品图',
width: 100,
align: 'center',
cellRender: {
name: 'CellImage',
},
},
{
field: 'name',
title: '商品名称',
minWidth: 300,
showOverflow: 'tooltip',
},
{
field: 'price',
title: '商品售价',
minWidth: 90,
align: 'center',
formatter: ({ cellValue }) => {
// 格式化价格显示(价格以分为单位存储)
return formatToFraction(cellValue);
},
},
{
field: 'salesCount',
title: '销量',
minWidth: 90,
align: 'center',
},
{
field: 'stock',
title: '库存',
minWidth: 90,
align: 'center',
},
{
field: 'sort',
title: '排序',
minWidth: 70,
align: 'center',
},
{
field: 'createTime',
title: '创建时间',
width: 180,
align: 'center',
formatter: 'formatDateTime',
},
] as VxeTableGridOptions['columns'];
}

View File

@ -0,0 +1,285 @@
<script lang="ts" setup>
import type { PropertyAndValues } from './type';
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { MallSpuApi } from '#/api/mall/product/spu';
import { computed, onMounted, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { handleTree } from '@vben/utils';
import { message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getCategoryList } from '#/api/mall/product/category';
import { getSpu, getSpuPage } from '#/api/mall/product/spu';
import { getPropertyList } from './property-util';
import SkuList from './sku-list.vue';
import { useGridColumns, useGridFormSchema } from './spu-select-data';
defineOptions({ name: 'SpuSelect' });
const props = withDefaults(defineProps<SpuSelectProps>(), {
isSelectSku: false,
radio: false,
});
const emit = defineEmits<{
(e: 'confirm', spuId: number, skuIds?: number[]): void;
}>();
interface SpuSelectProps {
// spu spu sku
// :isSelectSku='true'
isSelectSku?: boolean; // sku
radio?: boolean; // sku
}
// ============ ============
const categoryList = ref<Array<{ id: number; name: string; parentId: number }>>(
[],
); //
const categoryTreeList = ref<
Array<{ id: number; name: string; parentId: number }>
>([]); //
const propertyList = ref<PropertyAndValues[]>([]); //
const spuData = ref<MallSpuApi.Spu>(); //
const isExpand = ref(false); // SKU
// ============ ============
const selectedSpuId = ref<number>(0); // spuId
const selectedSkuIds = ref<number[]>([]); // skuIds
const skuListRef = ref<InstanceType<typeof SkuList>>(); // Ref
/** 处理 SKU 选择变化 */
function selectSku(val: MallSpuApi.Sku[]) {
const skuTable = skuListRef.value?.getSkuTableRef();
if (selectedSpuId.value === 0) {
message.warning('请先选择商品再选择相应的规格!!!');
skuTable?.clearSelection();
return;
}
if (val.length === 0) {
selectedSkuIds.value = [];
return;
}
if (props.radio) {
//
selectedSkuIds.value = [val.map((sku) => sku.id!)[0]];
// 1
if (val.length > 1) {
//
skuTable?.clearSelection();
//
skuTable?.toggleRowSelection(val.pop(), true);
}
} else {
selectedSkuIds.value = val.map((sku) => sku.id!);
}
}
/** 处理 SPU 选择变化 */
function selectSpu(val: MallSpuApi.Spu[]) {
if (val.length === 0) {
selectedSpuId.value = 0;
return;
}
//
selectedSpuId.value = val.map((spu) => spu.id!)[0];
// spu sku , sku spu
if (selectedSkuIds.value.length > 0) {
selectedSkuIds.value = [];
}
// 1
if (val.length > 1) {
//
gridApi.grid.clearCheckboxRow();
//
const lastRow = val.pop();
if (lastRow) {
gridApi.grid.setCheckboxRow(lastRow, true);
}
return;
}
// SPU
if (props.isSelectSku && val[0]) {
expandChange(val[0], [val[0]]);
}
}
/** 处理行展开变化 */
async function expandChange(
row: MallSpuApi.Spu,
expandedRows?: MallSpuApi.Spu[],
) {
// spuId === spuId A A skuList A B
// sku
if (selectedSpuId.value !== 0) {
if (row.id !== selectedSpuId.value) {
message.warning('你已选择商品请先取消');
//
await gridApi.grid.setExpandRowKeys([selectedSpuId.value]);
return;
}
// skuList spu skuList
if (isExpand.value && spuData.value?.id === row.id) {
return;
}
}
spuData.value = undefined;
propertyList.value = [];
isExpand.value = false;
if (expandedRows?.length === 0) {
// 0
expandRowKeys.value = [];
return;
}
// SPU
const res = (await getSpu(row.id as number)) as MallSpuApi.Spu;
// API
// API
res.skus?.forEach((item) => {
if (item.price) item.price = Math.round(item.price * 100);
if (item.marketPrice) item.marketPrice = Math.round(item.marketPrice * 100);
if (item.costPrice) item.costPrice = Math.round(item.costPrice * 100);
if (item.firstBrokeragePrice)
item.firstBrokeragePrice = Math.round(item.firstBrokeragePrice * 100);
if (item.secondBrokeragePrice)
item.secondBrokeragePrice = Math.round(item.secondBrokeragePrice * 100);
});
propertyList.value = getPropertyList(res);
spuData.value = res;
isExpand.value = true;
// grid API
await gridApi.grid.setExpandRowKeys([row.id!]);
}
/** 确认选择时的触发事件 */
function confirm() {
if (selectedSpuId.value === 0) {
message.warning('没有选择任何商品');
return;
}
if (props.isSelectSku && selectedSkuIds.value.length === 0) {
message.warning('没有选择任何商品属性');
return;
}
// id
props.isSelectSku
? emit('confirm', selectedSpuId.value, selectedSkuIds.value)
: emit('confirm', selectedSpuId.value);
//
modalApi.close();
selectedSpuId.value = 0;
selectedSkuIds.value = [];
}
/** 搜索表单 Schema */
const formSchema = computed(() => useGridFormSchema(categoryTreeList));
/** 表格列配置 */
const gridColumns = computed<VxeTableGridOptions['columns']>(() =>
useGridColumns(props.isSelectSku),
);
/** 初始化列表 */
const [Grid, gridApi] = useVbenVxeGrid({
formOptions: {
schema: formSchema.value,
layout: 'horizontal',
collapsed: false,
},
gridOptions: {
columns: gridColumns.value,
height: 500,
border: true,
checkboxConfig: {
reserve: true,
},
rowConfig: {
keyField: 'id',
isHover: true,
},
expandConfig: props.isSelectSku
? {
trigger: 'row',
reserve: true,
}
: undefined,
proxyConfig: {
ajax: {
async query({ page }: any, formValues: any) {
return await getSpuPage({
pageNo: page.currentPage,
pageSize: page.pageSize,
tabType: 0,
...formValues,
});
},
},
},
},
gridEvents: {
checkboxChange: ({ records }) => {
selectSpu(records as MallSpuApi.Spu[]);
},
expandChange: ({ row, expandedRows }) => {
expandChange(row as MallSpuApi.Spu, expandedRows as MallSpuApi.Spu[]);
},
},
});
/** 初始化弹窗 */
const [Modal, modalApi] = useVbenModal({
destroyOnClose: true,
onConfirm: confirm,
async onOpenChange(isOpen: boolean) {
if (!isOpen) {
await gridApi.grid.clearCheckboxRow();
await gridApi.grid.setExpandRowKeys([]);
selectedSpuId.value = 0;
selectedSkuIds.value = [];
spuData.value = undefined;
propertyList.value = [];
isExpand.value = false;
return;
}
//
await gridApi.query();
},
});
/** 对外暴露的方法 */
defineExpose({
open: () => {
modalApi.open();
},
});
/** 初始化分类数据 */
onMounted(async () => {
categoryList.value = await getCategoryList({});
categoryTreeList.value = handleTree(categoryList.value, 'id', 'parentId');
});
</script>
<template>
<Modal title="商品选择" class="w-[70%]">
<Grid>
<!-- 展开列内容SKU 列表 -->
<template v-if="isSelectSku" #expand_content="{ row }">
<SkuList
v-if="isExpand && spuData?.id === row.id"
ref="skuListRef"
:is-component="true"
:is-detail="true"
:prop-form-data="spuData"
:property-list="propertyList"
@selection-change="selectSku"
/>
</template>
</Grid>
</Modal>
</template>

View File

@ -20,3 +20,9 @@ export interface RuleConfig {
// 校验不通过时的消息提示
message: string;
}
export interface SpuProperty<T> {
propertyList: PropertyAndValues[];
spuDetail: T;
spuId: number;
}

View File

@ -1,8 +1,9 @@
<script lang="ts" setup>
import type { MallPointActivityApi } from '#/api/mall/promotion/point';
import type { RuleConfig } from '#/views/mall/product/spu/components';
// TODO @puhui999
// import type { SpuProperty } from '#/views/mall/promotion/components/types';
import type {
RuleConfig,
SpuProperty,
} from '#/views/mall/product/spu/components';
import { computed, ref } from 'vue';
@ -20,10 +21,12 @@ import {
updatePointActivity,
} from '#/api/mall/promotion/point';
import { $t } from '#/locales';
import { getPropertyList } from '#/views/mall/product/spu/components';
import {
getPropertyList,
SpuAndSkuList,
SpuSkuSelect,
} from '#/views/mall/product/spu/components';
// TODO @puhui999
// import { SpuAndSkuList, SpuSkuSelect } from '../../../components';
import { useFormSchema } from '../data';
const emit = defineEmits(['success']);
@ -72,8 +75,7 @@ const ruleConfig: RuleConfig[] = [
const spuList = ref<any[]>([]); // SPU
// TODO @puhui999
// const spuPropertyList = ref<SpuProperty<any>[]>([]); // SPU
const spuPropertyList = ref<any[]>([]); // SPU
const spuPropertyList = ref<SpuProperty<any>[]>([]); // SPU
/** 打开商品选择器 */
// TODO @puhui999spuSkuSelectRef.value.open is not a function