This commit is contained in:
2026-05-31 12:09:14 +08:00
commit e4f9eedb80
1121 changed files with 209380 additions and 0 deletions

View File

@@ -0,0 +1,388 @@
<!-- 编辑弹窗 -->
<template>
<ele-modal
:width="800"
:visible="visible"
:maskClosable="false"
:maxable="maxable"
title="生成礼品卡"
:body-style="{ paddingBottom: '28px' }"
@update:visible="updateVisible"
@ok="save"
>
<a-form
ref="formRef"
:model="form"
:rules="rules"
:label-col="styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }"
:wrapper-col="
styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
"
>
<a-form-item label="礼品劵" name="name">
<a-input
allow-clear
placeholder="请输入礼品卡名称"
v-model:value="form.name"
/>
</a-form-item>
<a-form-item label="关联商品" name="goodsId">
<a-select
v-model:value="form.goodsId"
placeholder="请选择关联商品"
show-search
:filter-option="false"
:loading="goodsLoading"
@search="searchGoods"
@change="onGoodsChange"
@dropdown-visible-change="onDropdownVisibleChange"
>
<a-select-option
v-for="goods in goodsList"
:key="goods.goodsId"
:value="goods.goodsId"
>
<div class="goods-option">
<span>{{ goods.name }}</span>
<a-tag color="blue" style="margin-left: 8px"
>¥{{ goods.price || 0 }}</a-tag
>
</div>
</a-select-option>
<a-select-option v-if="goodsList.length === 0" disabled>
<div style="text-align: center; color: #999">
{{ goodsLoading ? '加载中...' : '暂无商品数据' }}
</div>
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="生成数量" name="num">
<a-input-number v-model:value="form.num" :min="0" />
</a-form-item>
<a-form-item label="使用地址" name="useLocation">
<a-input
placeholder="请输入使用的门店地址"
v-model:value="form.useLocation"
/>
</a-form-item>
<a-form-item label="备注信息" name="comments">
<a-textarea
v-model:value="form.comments"
placeholder="请输入备注信息"
:rows="3"
:maxlength="200"
show-count
/>
</a-form-item>
</a-form>
<!-- 礼品卡预览 -->
<div class="gift-card-preview" v-if="form.name">
<a-divider orientation="left">
<span style="color: #1890ff; font-weight: 600">礼品卡预览</span>
</a-divider>
<div class="gift-card">
<div class="gift-card-header">
<div class="gift-card-title">{{ form.name }}</div>
<div class="gift-card-status">
<a-tag>
<span v-if="form.takeTime"
>领取时间{{ formatTime(form.takeTime) }}</span
>
<span v-else>未领取</span>
</a-tag>
</div>
</div>
<div class="gift-card-body">
<div class="gift-card-code">
<span class="code-label text-gray-50">卡密</span>
<span class="code-value">{{ form.code || '自动生成' }}</span>
</div>
<div class="gift-card-goods" v-if="selectedGoods">
<span class="goods-label text-gray-50">关联商品</span>
<span class="goods-name">{{ selectedGoods.name }}</span>
<a-tag color="blue" style="margin-left: 8px"
>¥{{ selectedGoods.price }}</a-tag
>
</div>
<div class="gift-card-goods py-2" v-if="selectedGoods">
<span class="goods-label">使用地址</span>
<span class="goods-name">{{ form.useLocation }}</span>
</div>
</div>
<div class="gift-card-footer">
<div class="gift-card-info text-gray-50">
备注: {{ form.comments }}
</div>
</div>
</div>
</div>
</ele-modal>
</template>
<script lang="ts" setup>
import { ref, reactive, watch } from 'vue';
import { Form, message } from 'ant-design-vue';
import { makeShopGift } from '@/api/shop/shopGift';
import { ShopGift } from '@/api/shop/shopGift/model';
import { useThemeStore } from '@/store/modules/theme';
import { storeToRefs } from 'pinia';
import { FormInstance } from 'ant-design-vue/es/form';
import { listShopGoods } from '@/api/shop/shopGoods';
import { ShopGoods } from '@/api/shop/shopGoods/model';
// 是否开启响应式布局
const themeStore = useThemeStore();
const { styleResponsive } = storeToRefs(themeStore);
const props = defineProps<{
// 弹窗是否打开
visible: boolean;
}>();
const emit = defineEmits<{
(e: 'done'): void;
(e: 'update:visible', visible: boolean): void;
}>();
// 提交状态
const loading = ref(false);
// 是否显示最大化切换按钮
const maxable = ref(true);
// 表格选中数据
const formRef = ref<FormInstance | null>(null);
// 商品列表
const goodsList = ref<ShopGoods[]>([]);
// 商品加载状态
const goodsLoading = ref(false);
// 选中的商品
const selectedGoods = ref<ShopGoods | null>(null);
const rules = reactive({
name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
goodsId: [{ required: true, message: '请选择商品', trigger: 'change' }],
num: [{ required: true, message: '请输入数量', trigger: 'blur' }]
});
// 用户信息
const form = reactive<ShopGift>({
id: undefined,
name: undefined,
code: undefined,
goodsId: undefined,
takeTime: undefined,
operatorUserId: undefined,
isShow: undefined,
status: undefined,
useLocation: undefined,
comments: undefined,
sortNumber: undefined,
userId: undefined,
deleted: undefined,
tenantId: undefined,
createTime: undefined,
updateTime: undefined,
num: 1000
});
/* 更新visible */
const updateVisible = (value: boolean) => {
emit('update:visible', value);
};
const getGoodsList = async () => {
goodsList.value = await listShopGoods();
};
getGoodsList();
/* 搜索商品 */
const searchGoods = async (value: string) => {
if (value && value.trim()) {
goodsLoading.value = true;
try {
const res = await listShopGoods({ keywords: value.trim() });
goodsList.value = res || [];
console.log('搜索到的商品:', goodsList.value);
} catch (e) {
console.error('搜索商品失败:', e);
goodsList.value = [];
} finally {
goodsLoading.value = false;
}
}
};
/* 下拉框显示状态改变 */
const onDropdownVisibleChange = (open: boolean) => {
if (open && goodsList.value.length === 0) {
// 当下拉框打开且没有数据时,加载默认商品列表
getGoodsList();
}
};
/* 商品选择改变 */
const onGoodsChange = (goodsId: number) => {
selectedGoods.value =
goodsList.value.find((goods) => goods.goodsId === goodsId) || null;
console.log('选中的商品:', selectedGoods.value);
};
/* 保存编辑 */
const save = () => {
if (!formRef.value) {
return;
}
formRef.value
.validate()
.then(() => {
loading.value = true;
const formData = {
...form
};
makeShopGift(formData)
.then((msg) => {
loading.value = false;
message.success(msg);
updateVisible(false);
emit('done');
})
.catch((e) => {
loading.value = false;
message.error(e.message);
});
})
.catch(() => {});
};
watch(() => props.visible, { immediate: true });
</script>
<style lang="less" scoped>
.goods-option,
.status-option {
display: flex;
align-items: center;
justify-content: space-between;
.ant-tag {
margin-left: 8px;
}
span {
color: #666;
font-size: 12px;
}
}
.gift-card-preview {
margin-top: 24px;
.gift-card {
background: linear-gradient(
135deg,
#667eea 0%,
#764ba2 50%,
#f093fb 100%
);
border-radius: 12px;
padding: 20px;
color: #333;
position: relative;
overflow: hidden;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
&::before {
content: '';
position: absolute;
top: -50px;
right: -50px;
width: 100px;
height: 100px;
background: rgba(255, 255, 255, 0.2);
border-radius: 50%;
}
.gift-card-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
.gift-card-title {
font-size: 20px;
font-weight: bold;
color: #f3f3f3;
}
}
.gift-card-body {
margin-bottom: 16px;
.gift-card-code {
margin-bottom: 12px;
.code-label {
font-weight: 600;
color: #f3f3f3;
}
.code-value {
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
background: rgba(255, 255, 255, 0.8);
padding: 4px 8px;
border-radius: 4px;
margin-left: 8px;
}
}
.gift-card-goods {
.goods-label {
font-weight: 600;
color: #f3f3f3;
}
.goods-name {
margin-left: 8px;
color: #f3f3f3;
}
}
}
.gift-card-footer {
padding-top: 16px;
border-top: 1px solid rgba(255, 255, 255, 0.3);
.gift-card-info {
font-size: 12px;
color: #f3f3f3;
}
}
}
}
:deep(.ant-divider-horizontal.ant-divider-with-text-left) {
margin: 24px 0 16px 0;
.ant-divider-inner-text {
padding: 0 16px 0 0;
}
}
:deep(.ant-form-item) {
margin-bottom: 16px;
}
:deep(.ant-select-selection-item) {
display: flex;
align-items: center;
}
:deep(.ant-input-number) {
width: 100%;
}
:deep(.ant-alert) {
.ant-alert-message {
font-weight: 600;
}
}
</style>

View File

@@ -0,0 +1,621 @@
<!-- 搜索表单 -->
<template>
<a-space :size="10" style="flex-wrap: wrap">
<!-- <a-button type="primary" class="ele-btn-icon" @click="add">-->
<!-- <template #icon>-->
<!-- <PlusOutlined />-->
<!-- </template>-->
<!-- <span>添加</span>-->
<!-- </a-button>-->
<a-button type="primary" class="ele-btn-icon" @click="openMultiAdd">
<template #icon>
<PlusOutlined />
</template>
<span>批量生成</span>
</a-button>
<a-input-search
allow-clear
v-model:value="where.keywords"
placeholder="名称|秘钥|用户ID"
style="width: 240px"
@search="reload"
@pressEnter="reload"
/>
<a-button
type="text"
:icon="h(QrcodeOutlined)"
@click="handleExport"
:loading="exportLoading"
>导出二维码
</a-button>
<a-button type="text" @click="handlePrint">打印 </a-button>
<MakeCard v-model:visible="showMultiAdd" @done="done" />
</a-space>
</template>
<script lang="ts" setup>
import { PlusOutlined, QrcodeOutlined } from '@ant-design/icons-vue';
import { watch, ref, h } from 'vue';
import { ShopGift, ShopGiftParam } from '@/api/shop/shopGift/model';
import MakeCard from '@/views/shop/shopGift/components/makeCard.vue';
import { listShopGift } from '@/api/shop/shopGift';
import { message } from 'ant-design-vue';
import {
Document,
Packer,
Paragraph,
ImageRun,
AlignmentType,
Table,
TableRow,
TableCell,
WidthType
} from 'docx';
import { saveAs } from 'file-saver';
import QRCode from 'qrcode';
import useSearch from '@/utils/use-search';
const props = withDefaults(
defineProps<{
// 选中的角色
selection?: ShopGift[];
}>(),
{}
);
const emit = defineEmits<{
(e: 'search', where?: ShopGiftParam): void;
(e: 'add'): void;
(e: 'remove'): void;
(e: 'batchMove'): void;
(e: 'done'): void;
}>();
// 表单数据
const { where } = useSearch<ShopGiftParam>({
keywords: ''
});
// 新增
// const add = () => {
// emit('add');
// };
const reload = () => {
emit('search', { ...where });
};
const done = () => {
emit('done');
};
const showMultiAdd = ref(false);
const exportLoading = ref(false);
const openMultiAdd = () => {
showMultiAdd.value = true;
};
// 批量导出二维码到Word文档
const handleExport = async () => {
try {
exportLoading.value = true;
message.loading('正在生成二维码文档,请稍候...', 0);
// 获取所有礼品卡数据
let giftList: ShopGift[] = [];
if (props.selection && props.selection.length > 0) {
// 如果有选中的数据,只导出选中的
giftList = props.selection;
} else {
// 如果没有选中,导出所有数据
giftList = await listShopGift();
}
if (!giftList || giftList.length === 0) {
message.error('没有礼品卡数据可导出');
return;
}
// 生成二维码图片
const qrCodeImages: { dataUrl: string; giftInfo: ShopGift }[] = [];
for (const gift of giftList) {
try {
// 生成二维码使用礼品卡code作为内容
const qrCodeDataUrl = await QRCode.toDataURL(String(gift.code), {
width: 200,
margin: 2,
color: {
dark: '#000000',
light: '#FFFFFF'
}
});
qrCodeImages.push({ dataUrl: qrCodeDataUrl, giftInfo: gift });
} catch (error) {
console.error(`生成礼品卡 ${gift.code} 的二维码失败:`, error);
}
}
if (qrCodeImages.length === 0) {
message.error('二维码生成失败');
return;
}
// 尝试创建Word文档如果失败则使用HTML方式
try {
await createWordDocument(qrCodeImages);
message.destroy();
message.success(`成功导出 ${qrCodeImages.length} 个礼品卡二维码`);
} catch (docError) {
console.warn('Word文档生成失败使用HTML方式:', docError);
createHtmlDocument(qrCodeImages);
message.destroy();
message.success(
`成功生成 ${qrCodeImages.length} 个礼品卡二维码HTML格式可直接打印`
);
}
} catch (error) {
console.error('导出失败:', error);
message.destroy();
message.error('导出失败,请重试');
} finally {
exportLoading.value = false;
}
};
// 创建Word文档
const createWordDocument = async (
qrCodeImages: { dataUrl: string; giftInfo: ShopGift }[]
) => {
const children: (Paragraph | Table)[] = [];
// 添加标题
children.push(
new Paragraph({
text: '礼品卡二维码清单',
alignment: AlignmentType.CENTER,
spacing: { after: 400 }
})
);
// 每行放置3个二维码保持适当间距
const itemsPerRow = 3;
const rows = Math.ceil(qrCodeImages.length / itemsPerRow);
for (let row = 0; row < rows; row++) {
const startIndex = row * itemsPerRow;
const endIndex = Math.min(startIndex + itemsPerRow, qrCodeImages.length);
const rowItems = qrCodeImages.slice(startIndex, endIndex);
// 创建表格行来放置二维码
const qrCodeCells: TableCell[] = [];
const infoCells: TableCell[] = [];
for (let i = 0; i < itemsPerRow; i++) {
if (i < rowItems.length) {
const item = rowItems[i];
// 将DataURL转换为Buffer
const base64Data = item.dataUrl.split(',')[1];
const binaryData = atob(base64Data);
const bytes = new Uint8Array(binaryData.length);
for (let j = 0; j < binaryData.length; j++) {
bytes[j] = binaryData.charCodeAt(j);
}
qrCodeCells.push(
new TableCell({
children: [
new Paragraph({
children: [
// @ts-ignore
new ImageRun({
data: bytes,
transformation: {
width: 150,
height: 150
}
})
],
alignment: AlignmentType.CENTER
})
],
width: { size: 33, type: WidthType.PERCENTAGE }
})
);
infoCells.push(
new TableCell({
children: [
new Paragraph({
text: `${item.giftInfo.code || '未设置'}`,
alignment: AlignmentType.CENTER
}),
new Paragraph({
text: `${item.giftInfo.name || ''}`,
alignment: AlignmentType.CENTER
})
],
width: { size: 33, type: WidthType.PERCENTAGE }
})
);
} else {
// 空单元格
qrCodeCells.push(
new TableCell({
children: [new Paragraph({ text: '' })],
width: { size: 33, type: WidthType.PERCENTAGE }
})
);
infoCells.push(
new TableCell({
children: [new Paragraph({ text: '' })],
width: { size: 33, type: WidthType.PERCENTAGE }
})
);
}
}
// 添加表格
children.push(
new Table({
rows: [
new TableRow({
children: qrCodeCells
}),
new TableRow({
children: infoCells
})
],
width: { size: 100, type: WidthType.PERCENTAGE }
})
);
// 添加行间距
children.push(
new Paragraph({
text: '',
spacing: { after: 400 }
})
);
}
// 创建文档
const doc = new Document({
sections: [
{
properties: {
page: {
size: {
orientation: 'portrait',
width: 11906, // A4宽度 (210mm)
height: 16838 // A4高度 (297mm)
},
margin: {
top: 1134, // 2cm
right: 1134, // 2cm
bottom: 1134, // 2cm
left: 1134 // 2cm
}
}
},
children
}
]
});
// 生成并下载文档
try {
const buffer = await Packer.toBlob(doc);
const fileName = `礼品卡二维码清单_${new Date()
.toISOString()
.slice(0, 10)}.docx`;
saveAs(buffer, fileName);
} catch (error) {
console.error('文档生成失败:', error);
// 如果Packer.toBlob失败尝试使用toBuffer
const buffer = await Packer.toBuffer(doc);
const blob = new Blob([buffer], {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
});
const fileName = `礼品卡二维码清单_${new Date()
.toISOString()
.slice(0, 10)}.docx`;
saveAs(blob, fileName);
}
};
// 创建HTML文档备用方案
const createHtmlDocument = (
qrCodeImages: { dataUrl: string; giftInfo: ShopGift }[]
) => {
const itemsPerRow = 3;
let htmlContent = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>礼品卡二维码清单</title>
<style>
@page {
size: A4;
margin: 2cm;
}
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
.title {
text-align: center;
font-size: 24px;
font-weight: bold;
margin-bottom: 30px;
}
.qr-grid {
display: grid;
grid-template-columns: repeat(${itemsPerRow}, 1fr);
gap: 20px;
margin-bottom: 30px;
}
.qr-item {
text-align: center;
page-break-inside: avoid;
}
.qr-code {
width: 150px;
height: 150px;
margin: 0 auto 10px;
}
.qr-info {
font-size: 12px;
line-height: 1.4;
}
@media print {
.no-print { display: none; }
}
</style>
</head>
<body>
<div class="title">礼品卡二维码清单</div>
<div class="qr-grid">
`;
qrCodeImages.forEach((item) => {
htmlContent += `
<div class="qr-item">
<img src="${item.dataUrl}" alt="QR Code" class="qr-code">
<div class="qr-info">
<div>礼品卡编号: ${item.giftInfo.code || '未设置'}</div>
<div>礼品卡名称: ${item.giftInfo.name || ''}</div>
<div>ID: ${item.giftInfo.id}</div>
</div>
</div>
`;
});
htmlContent += `
</div>
<div class="no-print" style="text-align: center; margin-top: 30px;">
<button onclick="window.print()" style="padding: 10px 20px; font-size: 16px;">打印文档</button>
<button onclick="window.close()" style="padding: 10px 20px; font-size: 16px; margin-left: 10px;">关闭</button>
</div>
</body>
</html>
`;
// 在新窗口中打开HTML文档
const newWindow = window.open('', '_blank');
if (newWindow) {
newWindow.document.write(htmlContent);
newWindow.document.close();
} else {
// 如果弹窗被阻止,创建下载链接
const blob = new Blob([htmlContent], { type: 'text/html;charset=utf-8' });
const fileName = `礼品卡二维码清单_${new Date()
.toISOString()
.slice(0, 10)}.html`;
saveAs(blob, fileName);
}
};
// 使用原生 window.print() 的打印功能
const handlePrint = async () => {
try {
message.loading('正在准备打印数据...', 0);
// 获取打印数据
let printData: ShopGift[] = [];
if (props.selection && props.selection.length > 0) {
printData = props.selection;
} else {
printData = await listShopGift();
}
if (!printData || printData.length === 0) {
message.destroy();
message.warning('没有数据可以打印');
return;
}
message.destroy();
// 创建打印窗口
const printWindow = window.open('', '_blank');
if (!printWindow) {
message.error('无法打开打印窗口,请检查浏览器弹窗设置');
return;
}
// 生成完整的HTML文档
const printHtml = createPrintHtml(printData);
// 写入HTML内容
printWindow.document.write(printHtml);
printWindow.document.close();
// 等待内容加载完成后打印
printWindow.onload = () => {
printWindow.print();
// 打印完成后关闭窗口
printWindow.onafterprint = () => {
printWindow.close();
};
};
} catch (error) {
message.destroy();
console.error('打印失败:', error);
message.error('打印失败,请重试');
}
};
// 创建完整的打印HTML文档
const createPrintHtml = (data: ShopGift[]) => {
const getStatusText = (record: ShopGift) => {
if (record.userId == 0) return '未领取';
if (record.userId > 0 && record.status === 0) return '已领取';
if (record.status === 1) return '已使用';
if (record.status === 2) return '已失效';
return '未知';
};
// 安全地处理数据,避免 undefined 或 null 值
const safeValue = (value: any) => {
if (value === null || value === undefined) return '';
return String(value).replace(/</g, '&lt;').replace(/>/g, '&gt;');
};
let tableRows = '';
data.forEach((record) => {
tableRows += `
<tr>
<td>${safeValue(record.id)}</td>
<td>${safeValue(record.name)}</td>
<td>${safeValue(record.code)}</td>
<td>${safeValue(record.goodsName)}</td>
<td>${safeValue(getStatusText(record))}</td>
<td>${safeValue(record.createTime)}</td>
</tr>`;
});
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>礼品卡清单</title>
<style>
@page {
margin: 15mm;
size: A4;
}
body {
font-family: Arial, "Microsoft YaHei", sans-serif;
margin: 0;
padding: 20px;
font-size: 14px;
}
.header {
text-align: center;
font-size: 20px;
font-weight: bold;
margin-bottom: 20px;
padding-bottom: 10px;
border-bottom: 2px solid #333;
}
.info {
margin-bottom: 15px;
font-size: 12px;
color: #666;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 10px;
}
th, td {
border: 1px solid #333;
padding: 8px;
text-align: center;
font-size: 12px;
}
th {
background-color: #f5f5f5;
font-weight: bold;
height: 35px;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
.footer {
margin-top: 20px;
text-align: right;
font-size: 12px;
color: #666;
}
@media print {
.no-print {
display: none !important;
}
body {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
}
</style>
</head>
<body>
<div class="header">礼品卡清单</div>
<div class="info">
<div>打印时间:${new Date().toLocaleString()}</div>
<div>数据条数:${data.length} 条</div>
</div>
<table>
<thead>
<tr>
<th>ID</th>
<th>名称</th>
<th>秘钥</th>
<th>商品</th>
<th>状态</th>
<th>创建时间</th>
</tr>
</thead>
<tbody>
${tableRows}
</tbody>
</table>
<div class="footer">
<div>共 ${data.length} 条记录</div>
</div>
<div class="no-print" style="text-align: center; margin-top: 20px;">
<button onclick="window.print()" style="padding: 10px 20px; font-size: 14px;">重新打印</button>
<button onclick="window.close()" style="padding: 10px 20px; font-size: 14px; margin-left: 10px;">关闭</button>
</div>
</body>
</html>
`;
};
watch(
() => props.selection,
() => {}
);
</script>

View File

@@ -0,0 +1,728 @@
<!-- 编辑弹窗 -->
<template>
<ele-modal
width="65%"
:visible="visible"
:maskClosable="false"
:maxable="maxable"
:title="isUpdate ? '礼品卡详情' : '礼品卡详情'"
:body-style="{ paddingBottom: '28px' }"
@update:visible="updateVisible"
@ok="save"
>
<a-form
ref="formRef"
:model="form"
:rules="rules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
>
<!-- 基本信息 -->
<a-divider orientation="left">
<span style="color: #1890ff; font-weight: 600">基本信息</span>
</a-divider>
<a-row :gutter="16">
<a-col :span="12">
<a-form-item label="礼品卡名称" name="name">
<a-input
placeholder="请输入礼品卡名称"
:disabled="isUpdate"
v-model:value="form.name"
/>
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item label="礼品卡密钥" name="code">
<a-input
placeholder="请输入礼品卡密钥"
v-model:value="form.code"
:disabled="isUpdate"
>
<template #suffix>
<a-button
v-if="!isUpdate"
type="link"
size="small"
@click="generateCode"
>
生成
</a-button>
</template>
</a-input>
</a-form-item>
</a-col>
</a-row>
<a-row :gutter="16">
<a-col :span="12">
<a-form-item label="关联商品" name="goodsId">
<a-select
v-model:value="form.goodsId"
placeholder="请选择关联商品"
show-search
:filter-option="false"
:loading="goodsLoading"
@search="searchGoods"
:disabled="isUpdate"
@change="onGoodsChange"
@dropdown-visible-change="onDropdownVisibleChange"
>
<a-select-option
v-for="goods in goodsList"
:key="goods.goodsId"
:value="goods.goodsId"
>
<div class="goods-option">
<span>{{ goods.name }}</span>
<a-tag color="blue" style="margin-left: 8px"
>¥{{ goods.price || 0 }}</a-tag
>
</div>
</a-select-option>
<a-select-option v-if="goodsList.length === 0" disabled>
<div style="text-align: center; color: #999">
{{ goodsLoading ? '加载中...' : '暂无商品数据' }}
</div>
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :span="12" v-if="!isUpdate">
<a-form-item label="生成数量" name="num">
<a-input-number
:min="1"
:max="1000"
placeholder="请输入生成数量"
v-model:value="form.num"
style="width: 100%"
>
<template #addonAfter></template>
</a-input-number>
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item label="使用地址" name="useLocation">
<a-input
placeholder="请输入使用的门店地址"
v-model:value="form.useLocation"
:disabled="isUpdate"
/>
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item label="备注信息" name="comments">
<a-textarea
v-model:value="form.comments"
:disabled="isUpdate"
placeholder="请输入备注信息"
:rows="3"
:maxlength="200"
show-count
/>
</a-form-item>
</a-col>
</a-row>
<!-- 状态设置 -->
<!-- <a-divider orientation="left">-->
<!-- <span style="color: #1890ff; font-weight: 600;">状态设置</span>-->
<!-- </a-divider>-->
<!-- <a-row :gutter="16">-->
<!-- <a-col :span="8">-->
<!-- <a-form-item label="上架状态" name="status">-->
<!-- <a-select v-model:value="form.status" placeholder="请选择上架状态">-->
<!-- <a-select-option :value="0">-->
<!-- <div class="status-option">-->
<!-- <a-tag color="success">已上架</a-tag>-->
<!-- <span>正常销售</span>-->
<!-- </div>-->
<!-- </a-select-option>-->
<!-- <a-select-option :value="1">-->
<!-- <div class="status-option">-->
<!-- <a-tag color="warning">待上架</a-tag>-->
<!-- <span>准备上架</span>-->
<!-- </div>-->
<!-- </a-select-option>-->
<!-- <a-select-option :value="2">-->
<!-- <div class="status-option">-->
<!-- <a-tag color="processing">待审核</a-tag>-->
<!-- <span>等待审核</span>-->
<!-- </div>-->
<!-- </a-select-option>-->
<!-- <a-select-option :value="3">-->
<!-- <div class="status-option">-->
<!-- <a-tag color="error">审核不通过</a-tag>-->
<!-- <span>审核失败</span>-->
<!-- </div>-->
<!-- </a-select-option>-->
<!-- </a-select>-->
<!-- </a-form-item>-->
<!-- </a-col>-->
<!-- <a-col :span="8">-->
<!-- <a-form-item label="展示状态" name="isShow">-->
<!-- <a-switch-->
<!-- v-model:checked="form.isShow"-->
<!-- checked-children="展示"-->
<!-- un-checked-children="隐藏"-->
<!-- />-->
<!-- </a-form-item>-->
<!-- </a-col>-->
<!-- <a-col :span="8">-->
<!-- <a-form-item label="排序" name="sortNumber">-->
<!-- <a-input-number-->
<!-- :min="0"-->
<!-- placeholder="数字越小越靠前"-->
<!-- v-model:value="form.sortNumber"-->
<!-- style="width: 100%"-->
<!-- />-->
<!-- </a-form-item>-->
<!-- </a-col>-->
<!-- </a-row>-->
<!-- 使用信息 -->
<a-divider orientation="left">
<span style="color: #1890ff; font-weight: 600">使用信息</span>
</a-divider>
<a-row :gutter="16">
<a-col :span="12">
<a-form-item label="领取时间" name="takeTime">
<a-date-picker
v-model:value="form.takeTime"
placeholder="请选择领取时间"
:disabled="isUpdate"
show-time
style="width: 100%"
/>
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item label="领取用户ID" name="userId">
<a-input-number
:min="1"
placeholder="请输入领取用户ID"
v-model:value="form.userId"
:disabled="isUpdate"
style="width: 100%"
/>
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item label="操作人ID" name="operatorUserId">
<a-input-number
:min="1"
placeholder="请输入操作人用户ID"
v-model:value="form.operatorUserId"
:disabled="isUpdate"
style="width: 300px"
/>
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item label="操作员备注" name="userId">
<a-textarea
v-model:value="form.operatorRemarks"
:disabled="isUpdate"
placeholder="请输入备注信息"
:rows="3"
:maxlength="200"
show-count
/>
</a-form-item>
</a-col>
</a-row>
<!-- 礼品卡预览 -->
<div class="gift-card-preview" v-if="form.name">
<a-divider orientation="left">
<span style="color: #1890ff; font-weight: 600">礼品卡预览</span>
</a-divider>
<div class="gift-card">
<div class="gift-card-header">
<div class="gift-card-title">{{ form.name }}</div>
<div class="gift-card-status">
<a-tag>
<span v-if="form.takeTime"
>领取时间{{ formatTime(form.takeTime) }}</span
>
<span v-else>未领取</span>
</a-tag>
</div>
</div>
<div class="gift-card-body">
<div class="gift-card-code">
<span class="code-label text-gray-50">卡密</span>
<span class="code-value">{{ form.code || '未设置' }}</span>
</div>
<div class="gift-card-goods" v-if="selectedGoods">
<span class="goods-label text-gray-50">关联商品</span>
<span class="goods-name">{{ selectedGoods.name }}</span>
<a-tag color="blue" style="margin-left: 8px"
>¥{{ selectedGoods.price }}</a-tag
>
</div>
<div class="gift-card-goods py-2" v-if="selectedGoods">
<span class="goods-label">使用地址</span>
<span class="goods-name">{{ form.useLocation }}</span>
</div>
</div>
<div class="gift-card-footer">
<div class="gift-card-info text-gray-50">
备注: {{ form.comments }}
</div>
</div>
</div>
</div>
</a-form>
</ele-modal>
</template>
<script lang="ts" setup>
import { ref, reactive, watch } from 'vue';
import { Form, message } from 'ant-design-vue';
import { assignObject } from 'ele-admin-pro';
import { addShopGift, updateShopGift } from '@/api/shop/shopGift';
import { ShopGift } from '@/api/shop/shopGift/model';
import { FormInstance } from 'ant-design-vue/es/form';
import { listShopGoods } from '@/api/shop/shopGoods';
import { ShopGoods } from '@/api/shop/shopGoods/model';
import dayjs from 'dayjs';
// 是否是修改
const isUpdate = ref(false);
const useForm = Form.useForm;
const props = defineProps<{
// 弹窗是否打开
visible: boolean;
// 修改回显的数据
data?: ShopGift | null;
}>();
const emit = defineEmits<{
(e: 'done'): void;
(e: 'update:visible', visible: boolean): void;
}>();
// 提交状态
const loading = ref(false);
// 是否显示最大化切换按钮
const maxable = ref(true);
// 表格选中数据
const formRef = ref<FormInstance | null>(null);
// 表单数据
const form = reactive<ShopGift>({
id: undefined,
name: '',
code: '',
goodsId: undefined,
takeTime: undefined,
operatorUserId: undefined,
operatorUserName: undefined,
operatorRemarks: undefined,
isShow: true,
status: 0,
useLocation: '',
comments: '',
sortNumber: 100,
userId: undefined,
deleted: 0,
tenantId: undefined,
createTime: undefined,
updateTime: undefined,
num: 1000
});
// 商品列表
const goodsList = ref<ShopGoods[]>([]);
// 商品加载状态
const goodsLoading = ref(false);
// 选中的商品
const selectedGoods = ref<ShopGoods | null>(null);
/* 更新visible */
const updateVisible = (value: boolean) => {
emit('update:visible', value);
};
// 表单验证规则
const rules = reactive({
name: [
{
required: true,
message: '请输入礼品卡名称',
trigger: 'blur'
},
{
min: 2,
max: 50,
message: '礼品卡名称长度应在2-50个字符之间',
trigger: 'blur'
}
],
code: [
{
required: true,
message: '请输入礼品卡密钥',
trigger: 'blur'
},
{
min: 6,
max: 32,
message: '密钥长度应在6-32个字符之间',
trigger: 'blur'
}
],
goodsId: [
{
required: true,
message: '请选择关联商品',
trigger: 'change'
}
],
num: [
{
required: true,
message: '请输入生成数量',
trigger: 'blur'
},
{
validator: (rule: any, value: any) => {
if (value && (value < 1 || value > 1000)) {
return Promise.reject('生成数量必须在1-1000之间');
}
return Promise.resolve();
},
trigger: 'blur'
}
],
status: [
{
required: true,
message: '请选择上架状态',
trigger: 'change'
}
]
});
/* 生成密钥 */
const generateCode = () => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let result = '';
for (let i = 0; i < 8; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
form.code = result;
};
/* 搜索商品 */
const searchGoods = async (value: string) => {
if (value && value.trim()) {
goodsLoading.value = true;
try {
const res = await listShopGoods({ keywords: value.trim() });
goodsList.value = res || [];
console.log('搜索到的商品:', goodsList.value);
} catch (e) {
console.error('搜索商品失败:', e);
goodsList.value = [];
} finally {
goodsLoading.value = false;
}
}
};
/* 下拉框显示状态改变 */
const onDropdownVisibleChange = (open: boolean) => {
if (open && goodsList.value.length === 0) {
// 当下拉框打开且没有数据时,加载默认商品列表
getGoodsList();
}
};
/* 商品选择改变 */
const onGoodsChange = (goodsId: number) => {
selectedGoods.value =
goodsList.value.find((goods) => goods.goodsId === goodsId) || null;
console.log('选中的商品:', selectedGoods.value);
};
/* 获取状态颜色 */
const getStatusColor = () => {
const colorMap = {
0: 'success',
1: 'warning',
2: 'processing',
3: 'error'
};
return colorMap[form.status] || 'default';
};
/* 获取状态文本 */
const getStatusText = () => {
const textMap = {
0: '已上架',
1: '待上架',
2: '待审核',
3: '审核不通过'
};
return textMap[form.status] || '未知状态';
};
/* 格式化时间 */
const formatTime = (time: any) => {
if (!time) return '';
return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
};
const { resetFields } = useForm(form, rules);
/* 保存编辑 */
const save = () => {
if (!formRef.value) {
return;
}
formRef.value
.validate()
.then(() => {
loading.value = true;
const formData = {
...form
};
// 处理时间字段转换
if (formData.takeTime && dayjs.isDayjs(formData.takeTime)) {
formData.takeTime = formData.takeTime.format('YYYY-MM-DD HH:mm:ss');
}
// 处理数据类型转换
if (formData.isShow !== undefined) {
formData.isShow = formData.isShow === '1' || formData.isShow === true;
}
console.log('提交的礼品卡数据:', formData);
const saveOrUpdate = isUpdate.value ? updateShopGift : addShopGift;
saveOrUpdate(formData)
.then((msg) => {
loading.value = false;
message.success(msg);
updateVisible(false);
emit('done');
})
.catch((e) => {
loading.value = false;
message.error(e.message);
console.error('保存失败:', e);
});
})
.catch((errors) => {
console.error('表单验证失败:', errors);
});
};
/* 获取商品列表 */
const getGoodsList = async () => {
if (goodsLoading.value) return; // 防止重复加载
goodsLoading.value = true;
try {
const res = await listShopGoods({ pageSize: 50 }); // 限制返回数量
goodsList.value = res || [];
console.log('获取到的商品列表:', goodsList.value);
} catch (e) {
console.error('获取商品列表失败:', e);
goodsList.value = [];
} finally {
goodsLoading.value = false;
}
};
watch(
() => props.visible,
async (visible) => {
if (visible) {
await getGoodsList();
if (props.data) {
assignObject(form, props.data);
// 处理时间字段转换
if (props.data.takeTime) {
form.takeTime = dayjs(props.data.takeTime);
}
// 设置选中的商品
if (props.data.goodsId) {
selectedGoods.value =
goodsList.value.find(
(goods) => goods.goodsId === props.data.goodsId
) || null;
}
isUpdate.value = true;
} else {
// 重置为默认值
Object.assign(form, {
id: undefined,
name: '',
code: '',
goodsId: undefined,
takeTime: undefined,
operatorUserId: undefined,
isShow: true,
status: 0,
comments: '',
sortNumber: 100,
userId: undefined,
deleted: 0,
tenantId: undefined,
createTime: undefined,
updateTime: undefined,
num: 1000
});
selectedGoods.value = null;
isUpdate.value = false;
}
} else {
resetFields();
}
},
{ immediate: true }
);
</script>
<style lang="less" scoped>
.goods-option,
.status-option {
display: flex;
align-items: center;
justify-content: space-between;
.ant-tag {
margin-left: 8px;
}
span {
color: #666;
font-size: 12px;
}
}
.gift-card-preview {
margin-top: 24px;
.gift-card {
background: linear-gradient(
135deg,
#667eea 0%,
#764ba2 50%,
#f093fb 100%
);
border-radius: 12px;
padding: 20px;
color: #333;
position: relative;
overflow: hidden;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
&::before {
content: '';
position: absolute;
top: -50px;
right: -50px;
width: 100px;
height: 100px;
background: rgba(255, 255, 255, 0.2);
border-radius: 50%;
}
.gift-card-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
.gift-card-title {
font-size: 20px;
font-weight: bold;
color: #f3f3f3;
}
}
.gift-card-body {
margin-bottom: 16px;
.gift-card-code {
margin-bottom: 12px;
.code-label {
font-weight: 600;
color: #f3f3f3;
}
.code-value {
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
background: rgba(255, 255, 255, 0.8);
padding: 4px 8px;
border-radius: 4px;
margin-left: 8px;
}
}
.gift-card-goods {
.goods-label {
font-weight: 600;
color: #f3f3f3;
}
.goods-name {
margin-left: 8px;
color: #f3f3f3;
}
}
}
.gift-card-footer {
padding-top: 16px;
border-top: 1px solid rgba(255, 255, 255, 0.3);
.gift-card-info {
font-size: 12px;
color: #f3f3f3;
}
}
}
}
:deep(.ant-divider-horizontal.ant-divider-with-text-left) {
margin: 24px 0 16px 0;
.ant-divider-inner-text {
padding: 0 16px 0 0;
}
}
:deep(.ant-form-item) {
margin-bottom: 16px;
}
:deep(.ant-select-selection-item) {
display: flex;
align-items: center;
}
:deep(.ant-input-number) {
width: 100%;
}
:deep(.ant-alert) {
.ant-alert-message {
font-weight: 600;
}
}
</style>