Files
JayuCloud/Frontend/src/views/admin/ShopsView.vue
T

1109 lines
34 KiB
Vue
Raw Normal View History

2026-02-25 10:37:16 +08:00
<template>
<div class="shops">
<a-page-header title="店铺管理" sub-title="管理美甲店铺" />
<a-card :bordered="false">
<template #extra>
<a-space>
<a-input-search
v-model:value="searchText"
placeholder="搜索店铺名称"
style="width: 250px"
@search="handleSearch"
/>
2026-02-26 22:51:56 +08:00
<a-button v-if="hasPermission('shop:create')" type="primary" @click="showAddModal">
2026-02-25 10:37:16 +08:00
<template #icon>
<PlusOutlined />
</template>
新增店铺
</a-button>
</a-space>
</template>
<a-table
:columns="columns"
:data-source="shopList"
:loading="loading"
:pagination="pagination"
:scroll="{ x: 1380 }"
2026-02-25 10:37:16 +08:00
@change="handleTableChange"
row-key="id"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'image'">
2026-02-26 14:20:35 +08:00
<div class="shop-images">
<a-image
v-for="(url, index) in getShopImages(record)"
:key="index"
:width="50"
:height="50"
:src="url"
style="object-fit: cover; border-radius: 4px; margin-right: 4px;"
:preview="false"
/>
<a-image
v-if="getShopImages(record).length === 0"
:width="50"
:height="50"
:src="DEFAULT_SHOP_IMAGE"
style="object-fit: cover; border-radius: 4px;"
:preview="false"
/>
</div>
2026-02-25 10:37:16 +08:00
</template>
<template v-else-if="column.key === 'banner'">
<div class="shop-banner">
<a-image
v-for="(url, index) in getShopBannerImages(record)"
:key="index"
:width="80"
:height="40"
:src="url"
style="object-fit: cover; border-radius: 4px; margin-right: 4px;"
:preview="false"
/>
<span v-if="getShopBannerImages(record).length === 0" class="no-banner">暂无Banner</span>
</div>
</template>
<template v-else-if="column.key === 'status'">
<a-switch
:checked="record.status !== 0"
:disabled="!hasPermission('shop:edit') || !isAdmin"
checked-children="启用"
un-checked-children="停用"
@change="(checked: any) => handleStatusChange(record, checked === true)"
/>
</template>
<template v-else-if="column.key === 'shopName'">
<div style="max-width: 180px;">
<TableEllipsisText :text="record.shopName" />
</div>
</template>
<template v-else-if="column.key === 'description'">
<div style="max-width: 280px;">
<TableEllipsisText :text="record.description" :lines="2" />
</div>
</template>
<template v-else-if="column.key === 'address'">
<div style="max-width: 260px;">
<TableEllipsisText :text="record.address" :lines="2" />
</div>
</template>
<template v-else-if="column.key === 'businessHours'">
<div style="max-width: 140px;">
<TableEllipsisText :text="record.businessHours" />
</div>
</template>
2026-02-25 10:37:16 +08:00
<template v-else-if="column.key === 'actions'">
<a-space>
2026-02-28 14:32:28 +08:00
<a-button v-if="hasPermission('shop:view')" type="link" size="small" @click="showViewModal(record)">
查看
</a-button>
2026-02-26 22:51:56 +08:00
<a-button v-if="hasPermission('shop:edit')" type="link" size="small" @click="showEditModal(record)">
2026-02-25 10:37:16 +08:00
编辑
</a-button>
<a-popconfirm
2026-02-26 22:51:56 +08:00
v-if="hasPermission('shop:delete')"
2026-02-25 10:37:16 +08:00
title="确定要删除这个店铺吗?"
@confirm="handleDelete(record)"
>
<a-button type="link" size="small" danger>
删除
</a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</a-table>
</a-card>
<a-modal
v-model:open="modalVisible"
:title="isEdit ? '编辑店铺' : '新增店铺'"
width="700px"
2026-02-25 10:37:16 +08:00
@ok="handleModalOk"
@cancel="handleModalCancel"
:confirmLoading="modalLoading"
2026-03-26 11:41:38 +08:00
:ok-button-props="{ disabled: isUploadPending }"
2026-02-25 10:37:16 +08:00
>
2026-03-26 12:04:02 +08:00
<DraftActions
:saved-at="draftSavedAt"
:disabled="isUploadPending"
@save="handleSaveDraft"
@clear="handleClearDraft"
/>
2026-02-25 10:37:16 +08:00
<a-form
ref="formRef"
:model="formState"
:rules="formRules"
:label-col="{ span: 5 }"
:wrapper-col="{ span: 18 }"
>
2026-02-25 14:44:50 +08:00
<a-form-item label="店铺名称" name="shopName">
<a-input v-model:value="formState.shopName" placeholder="请输入店铺名称" />
2026-02-25 10:37:16 +08:00
</a-form-item>
<a-form-item label="店铺描述" name="description">
<a-textarea
v-model:value="formState.description"
placeholder="请输入店铺描述"
:rows="3"
/>
</a-form-item>
<a-form-item label="店铺地址" name="address">
<a-input v-model:value="formState.address" placeholder="请输入店铺地址" />
</a-form-item>
<a-form-item label="营业时间" name="businessHours">
2026-03-21 13:16:39 +08:00
<div class="business-hours-picker">
<a-date-picker
v-model:value="businessStartTime"
picker="time"
value-format="HH:mm"
format="HH:mm"
placeholder="开始时间"
input-read-only
style="width: calc(50% - 14px)"
@change="handleBusinessHoursChange"
/>
<span class="business-hours-separator">至</span>
<a-date-picker
v-model:value="businessEndTime"
picker="time"
value-format="HH:mm"
format="HH:mm"
placeholder="结束时间"
input-read-only
style="width: calc(50% - 14px)"
@change="handleBusinessHoursChange"
/>
</div>
2026-02-25 10:37:16 +08:00
</a-form-item>
<a-form-item label="Banner图片">
<div class="upload-tip">首页轮播图,建议尺寸 750x300 像素</div>
<a-upload
v-model:file-list="bannerFileList"
list-type="picture-card"
:custom-request="handleUploadBanner"
:before-upload="beforeUpload"
@preview="handleBannerPreview"
@remove="handleBannerRemove"
:max-count="5"
>
<div v-if="bannerFileList.length < 5">
<plus-outlined />
<div style="margin-top: 8px">上传Banner</div>
</div>
</a-upload>
2026-03-26 11:41:38 +08:00
<div v-if="isUploadPending" class="upload-pending-tip">图片正在上传中,上传完成前不可提交。</div>
<a-modal v-model:open="bannerPreviewVisible" :footer="null" @cancel="bannerPreviewVisible = false">
<img alt="预览" style="width: 100%" :src="bannerPreviewImage" />
</a-modal>
</a-form-item>
2026-02-26 14:20:35 +08:00
<a-form-item label="店铺图片">
<div class="upload-tip">店铺详情展示图</div>
2026-02-26 14:20:35 +08:00
<a-upload
v-model:file-list="imageFileList"
list-type="picture-card"
:custom-request="handleUploadImage"
:before-upload="beforeUpload"
@preview="handlePreview"
@remove="handleRemove"
:max-count="5"
>
<div v-if="imageFileList.length < 5">
<plus-outlined />
<div style="margin-top: 8px">上传图片</div>
</div>
</a-upload>
2026-03-26 11:41:38 +08:00
<div v-if="isUploadPending" class="upload-pending-tip">图片正在上传中,上传完成前不可提交。</div>
2026-02-26 14:20:35 +08:00
<a-modal v-model:open="previewVisible" :footer="null" @cancel="previewVisible = false">
<img alt="预览" style="width: 100%" :src="previewImage" />
</a-modal>
2026-02-25 10:37:16 +08:00
</a-form-item>
</a-form>
</a-modal>
2026-02-28 14:32:28 +08:00
<!-- 查看店铺详情模态框 -->
<a-modal
v-model:open="viewModalVisible"
title="查看店铺详情"
width="700px"
2026-02-28 14:32:28 +08:00
@cancel="handleViewModalCancel"
>
<a-form
:model="viewFormState"
:label-col="{ span: 5 }"
:wrapper-col="{ span: 18 }"
>
<a-form-item label="店铺名称">
<a-input v-model:value="viewFormState.shopName" :disabled="true" />
</a-form-item>
<a-form-item label="店铺描述">
<a-textarea
v-model:value="viewFormState.description"
:rows="3"
:disabled="true"
/>
</a-form-item>
<a-form-item label="店铺地址">
<a-input v-model:value="viewFormState.address" :disabled="true" />
</a-form-item>
<a-form-item label="营业时间">
<a-input v-model:value="viewFormState.businessHours" :disabled="true" />
</a-form-item>
<a-form-item label="Banner图片">
<div class="shop-images">
<a-image
v-for="(url, index) in viewBannerUrls"
:key="index"
:width="120"
:height="60"
:src="url"
style="object-fit: cover; border-radius: 4px; margin-right: 8px; margin-bottom: 8px;"
:preview="false"
/>
<span v-if="viewBannerUrls.length === 0" class="no-banner">暂无Banner</span>
</div>
</a-form-item>
2026-02-28 14:32:28 +08:00
<a-form-item label="店铺图片">
<div class="shop-images">
<a-image
v-for="(url, index) in viewImageUrls"
:key="index"
:width="80"
:height="80"
:src="url"
style="object-fit: cover; border-radius: 4px; margin-right: 8px; margin-bottom: 8px;"
:preview="false"
/>
<a-image
v-if="viewImageUrls.length === 0"
:width="80"
:height="80"
:src="DEFAULT_SHOP_IMAGE"
style="object-fit: cover; border-radius: 4px;"
:preview="false"
/>
2026-02-28 14:32:28 +08:00
</div>
</a-form-item>
</a-form>
</a-modal>
2026-02-25 10:37:16 +08:00
</div>
</template>
<script setup lang="ts">
2026-03-26 11:41:38 +08:00
import { computed, ref, reactive, onMounted } from 'vue'
2026-02-25 10:37:16 +08:00
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
2026-03-02 10:13:20 +08:00
import { PlusOutlined } from '@ant-design/icons-vue'
2026-03-26 12:04:02 +08:00
import DraftActions from '@/components/DraftActions.vue'
import TableEllipsisText from '@/components/TableEllipsisText.vue'
2026-02-25 10:37:16 +08:00
import { DEFAULT_SHOP_IMAGE } from '@/constants'
2026-02-26 14:20:35 +08:00
import { adminShopApi, adminFileApi, type Shop } from '@/api/admin'
2026-03-26 11:41:38 +08:00
import { createChunkUploadTask, type ChunkUploadTask } from '@/utils/chunk-upload'
2026-03-26 12:04:02 +08:00
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
2026-02-26 17:54:18 +08:00
import { usePermission } from '@/utils/permission'
2026-02-26 18:44:47 +08:00
const { hasPermission, loadUserPermissions } = usePermission()
2026-02-25 10:37:16 +08:00
const loading = ref(false)
const searchText = ref('')
2026-02-25 14:44:50 +08:00
const shopList = ref<Shop[]>([])
2026-02-25 10:37:16 +08:00
const modalVisible = ref(false)
2026-02-28 14:32:28 +08:00
const viewModalVisible = ref(false)
2026-02-25 10:37:16 +08:00
const modalLoading = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
2026-02-25 14:44:50 +08:00
const currentShop = ref<Shop | null>(null)
2026-02-26 18:44:47 +08:00
const isAdmin = ref(false)
2026-02-25 10:37:16 +08:00
// Banner图片相关
const bannerFileList = ref<any[]>([])
const uploadedBannerIds = ref<string[]>([])
const bannerPreviewVisible = ref(false)
const bannerPreviewImage = ref('')
// 店铺图片相关
2026-02-26 14:20:35 +08:00
const imageFileList = ref<any[]>([])
const uploadedFileIds = ref<string[]>([])
const imageIdCache = ref<Record<string, string>>({})
2026-03-27 14:55:41 +08:00
const shopImageUrls = ref<Record<string, string[]>>({})
const shopBannerUrls = ref<Record<string, string[]>>({})
2026-02-28 14:32:28 +08:00
const viewImageUrls = ref<string[]>([])
const viewBannerUrls = ref<string[]>([])
2026-02-26 14:20:35 +08:00
const previewVisible = ref(false)
const previewImage = ref('')
2026-03-21 13:16:39 +08:00
const businessStartTime = ref('')
const businessEndTime = ref('')
2026-03-26 11:41:38 +08:00
const uploadTaskMap = new Map<string, ChunkUploadTask<any>>()
const activeUploadCount = ref(0)
const isUploadPending = computed(() => activeUploadCount.value > 0)
2026-03-26 12:04:02 +08:00
const draftSavedAt = ref<number | null>(null)
2026-02-26 14:20:35 +08:00
2026-02-28 14:32:28 +08:00
// 查看店铺相关状态
const viewFormState = reactive({
shopName: '',
description: '',
address: '',
businessHours: '',
status: 1,
coverImageFileId: '',
2026-02-28 14:32:28 +08:00
imageFileIds: ''
})
2026-02-25 10:37:16 +08:00
const pagination = reactive({
current: 1,
pageSize: 10,
total: 0,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total: number) => `共 ${total} 条`
})
const formState = reactive({
2026-02-25 14:44:50 +08:00
shopName: '',
2026-02-25 10:37:16 +08:00
description: '',
address: '',
businessHours: '',
status: 1,
coverImageFileId: '',
2026-02-26 14:20:35 +08:00
imageFileIds: ''
2026-02-25 10:37:16 +08:00
})
2026-03-02 10:13:20 +08:00
const formRules: any = {
2026-02-25 14:44:50 +08:00
shopName: [{ required: true, message: '请输入店铺名称', trigger: 'blur' }],
2026-02-25 10:37:16 +08:00
description: [{ required: true, message: '请输入店铺描述', trigger: 'blur' }],
address: [{ required: true, message: '请输入店铺地址', trigger: 'blur' }],
2026-03-21 13:16:39 +08:00
businessHours: [{
validator: async () => {
if (!businessStartTime.value || !businessEndTime.value) {
return Promise.reject('请选择营业开始和结束时间')
}
if (businessStartTime.value >= businessEndTime.value) {
return Promise.reject('营业结束时间必须晚于开始时间')
}
return Promise.resolve()
},
trigger: 'change'
}]
2026-02-25 10:37:16 +08:00
}
const columns = [
2026-02-26 14:20:35 +08:00
{ title: '图片', key: 'image', width: 150 },
{ title: 'Banner', key: 'banner', width: 200 },
2026-02-25 14:44:50 +08:00
{ title: '店铺名称', dataIndex: 'shopName', key: 'shopName' },
{ title: '店铺描述', dataIndex: 'description', key: 'description' },
2026-02-25 10:37:16 +08:00
{ title: '店铺地址', dataIndex: 'address', key: 'address' },
{ title: '营业时间', dataIndex: 'businessHours', key: 'businessHours' },
{ title: '状态', key: 'status', width: 120 },
2026-02-25 10:37:16 +08:00
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
]
const getCurrentUserInfo = () => {
try {
const userInfoStr = localStorage.getItem('adminUserInfo')
if (userInfoStr) {
2026-02-26 18:44:47 +08:00
const userInfo = JSON.parse(userInfoStr)
// 判断用户是否为管理员(类型为4)
isAdmin.value = userInfo.type === 4
return userInfo
}
} catch (error) {
console.error('获取当前用户信息失败', error)
}
return null
}
2026-02-26 14:20:35 +08:00
const loadImageUrls = async (shops: Shop[]) => {
for (const shop of shops) {
// 加载店铺图片
2026-02-26 14:20:35 +08:00
if (shop.imageFileIds) {
const ids = shop.imageFileIds.split(',')
const urls: string[] = []
for (const id of ids) {
if (id) {
try {
// 检查缓存
if (!imageIdCache.value[id]) {
2026-03-27 14:55:41 +08:00
const response = await adminFileApi.getSignedUrl(id.trim()) as any
2026-03-02 10:13:20 +08:00
imageIdCache.value[id] = response
2026-02-26 14:20:35 +08:00
}
2026-03-10 23:23:15 +08:00
urls.push(imageIdCache.value[id]!)
2026-02-26 14:20:35 +08:00
} catch (error) {
console.error('获取签名链接失败:', error)
urls.push(DEFAULT_SHOP_IMAGE)
}
}
}
2026-03-10 23:23:15 +08:00
if (shop.id !== undefined) {
2026-03-27 14:55:41 +08:00
shopImageUrls.value[String(shop.id)] = urls
2026-03-10 23:23:15 +08:00
}
2026-02-26 14:20:35 +08:00
} else {
2026-03-10 23:23:15 +08:00
if (shop.id !== undefined) {
2026-03-27 14:55:41 +08:00
shopImageUrls.value[String(shop.id)] = []
2026-03-10 23:23:15 +08:00
}
}
// 加载Banner图片
if (shop.coverImageFileId) {
const ids = shop.coverImageFileId.split(',')
const urls: string[] = []
for (const id of ids) {
if (id) {
try {
// 检查缓存
if (!imageIdCache.value[id]) {
2026-03-27 14:55:41 +08:00
const response = await adminFileApi.getSignedUrl(id.trim()) as any
imageIdCache.value[id] = response
}
2026-03-10 23:23:15 +08:00
urls.push(imageIdCache.value[id]!)
} catch (error) {
console.error('获取签名链接失败:', error)
urls.push(DEFAULT_SHOP_IMAGE)
}
}
}
2026-03-10 23:23:15 +08:00
if (shop.id !== undefined) {
2026-03-27 14:55:41 +08:00
shopBannerUrls.value[String(shop.id)] = urls
2026-03-10 23:23:15 +08:00
}
} else {
2026-03-10 23:23:15 +08:00
if (shop.id !== undefined) {
2026-03-27 14:55:41 +08:00
shopBannerUrls.value[String(shop.id)] = []
2026-03-10 23:23:15 +08:00
}
2026-02-26 14:20:35 +08:00
}
}
}
2026-03-02 10:13:20 +08:00
const getShopImages = (shop: Shop | Record<string, any>): string[] => {
const shopId = 'id' in shop ? shop.id : (shop as any).id
2026-03-10 23:23:15 +08:00
if (shopId !== undefined) {
2026-03-27 14:55:41 +08:00
return shopImageUrls.value[String(shopId)] || []
2026-03-10 23:23:15 +08:00
}
return []
}
const getShopBannerImages = (shop: Shop | Record<string, any>): string[] => {
const shopId = 'id' in shop ? shop.id : (shop as any).id
2026-03-10 23:23:15 +08:00
if (shopId !== undefined) {
2026-03-27 14:55:41 +08:00
return shopBannerUrls.value[String(shopId)] || []
2026-03-10 23:23:15 +08:00
}
return []
2026-02-26 14:20:35 +08:00
}
2026-02-25 10:37:16 +08:00
const fetchShopList = async () => {
loading.value = true
try {
const currentUser = getCurrentUserInfo()
const params: any = {
2026-02-25 10:37:16 +08:00
page: pagination.current,
size: pagination.pageSize,
keyword: searchText.value
}
if (currentUser && currentUser.type !== 4 && currentUser.shopId) {
params.shopId = currentUser.shopId
}
2026-03-02 10:13:20 +08:00
const response = await adminShopApi.listShops(params)
const res = typeof response === 'object' && 'list' in response ? response : (response as any).data
2026-02-25 10:37:16 +08:00
shopList.value = res.list || []
pagination.total = res.total || 0
2026-02-26 14:20:35 +08:00
// 预加载所有图片签名链接
await loadImageUrls(res.list || [])
2026-02-25 10:37:16 +08:00
} catch (error) {
message.error('获取店铺列表失败')
} finally {
loading.value = false
}
}
const handleSearch = () => {
pagination.current = 1
fetchShopList()
}
const handleTableChange = (pag: any) => {
pagination.current = pag.current
pagination.pageSize = pag.pageSize
fetchShopList()
}
2026-02-26 14:20:35 +08:00
const beforeUpload = (file: File) => {
const isImage = file.type.startsWith('image/')
if (!isImage) {
message.error('只能上传图片文件!')
}
const isLt2M = file.size / 1024 / 1024 < 2
if (!isLt2M) {
message.error('图片大小不能超过 2MB!')
}
return isImage && isLt2M
}
2026-03-27 15:04:58 +08:00
// Banner 与门店环境图分开维护上传任务,便于表单回显和删除时分别同步 fileId 列表。
const handleUploadBanner = async (options: any) => {
2026-03-26 11:41:38 +08:00
const { file, onSuccess, onError, onProgress } = options
const taskKey = `banner:${String(file.uid)}`
const task = createChunkUploadTask({
file: file as File,
scene: 'admin-shop-banner',
api: {
initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk,
completeUpload: adminFileApi.completeChunkUpload,
cancelUpload: adminFileApi.cancelChunkUpload
},
onProgress: (percent) => {
onProgress?.({ percent })
}
})
uploadTaskMap.set(taskKey, task)
activeUploadCount.value += 1
try {
2026-03-26 11:41:38 +08:00
const { response } = await task.promise
const fileId = String((response as any).id)
syncUploadedBannerIds([...uploadedBannerIds.value, fileId])
onSuccess?.({ id: fileId, fileId })
message.success('Banner上传成功')
} catch (error) {
2026-03-26 11:41:38 +08:00
const errorMessage = (error as Error)?.message || 'Banner上传失败'
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('Banner上传失败:', error)
message.error(errorMessage)
onError?.(error)
}
} finally {
uploadTaskMap.delete(taskKey)
activeUploadCount.value = Math.max(0, activeUploadCount.value - 1)
}
}
const handleBannerPreview = async (file: any) => {
try {
2026-03-26 11:41:38 +08:00
const cachedPreviewUrl = getPreviewUrlFromFile(file)
if (cachedPreviewUrl) {
bannerPreviewImage.value = cachedPreviewUrl
bannerPreviewVisible.value = true
return
}
2026-03-26 11:41:38 +08:00
const fileId = resolveUploadedFileId(file)
if (!fileId) {
throw new Error('未找到图片文件标识')
}
if (!imageIdCache.value[fileId]) {
2026-03-27 14:55:41 +08:00
const response = await adminFileApi.getSignedUrl(fileId) as any
2026-03-26 11:41:38 +08:00
imageIdCache.value[fileId] = response
}
bannerPreviewImage.value = imageIdCache.value[fileId] || ''
bannerPreviewVisible.value = true
} catch (error) {
console.error('获取预览链接失败:', error)
2026-03-26 11:41:38 +08:00
message.error((error as Error)?.message || '获取预览链接失败')
}
}
const handleBannerRemove = (file: any) => {
2026-03-26 11:41:38 +08:00
const task = uploadTaskMap.get(`banner:${String(file.uid)}`)
if (task) {
task.cancel()
return true
}
2026-03-26 11:41:38 +08:00
const fileId = resolveUploadedFileId(file)
if (fileId) {
syncUploadedBannerIds(uploadedBannerIds.value.filter(id => id !== fileId))
}
return true
}
2026-03-27 15:04:58 +08:00
// 店铺环境图与 Banner 走同一套分片上传协议,但写入不同业务字段。
2026-02-26 14:20:35 +08:00
const handleUploadImage = async (options: any) => {
2026-03-26 11:41:38 +08:00
const { file, onSuccess, onError, onProgress } = options
const taskKey = `image:${String(file.uid)}`
const task = createChunkUploadTask({
file: file as File,
scene: 'admin-shop-image',
api: {
initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk,
completeUpload: adminFileApi.completeChunkUpload,
cancelUpload: adminFileApi.cancelChunkUpload
},
onProgress: (percent) => {
onProgress?.({ percent })
}
})
uploadTaskMap.set(taskKey, task)
activeUploadCount.value += 1
2026-02-26 14:20:35 +08:00
try {
2026-03-26 11:41:38 +08:00
const { response } = await task.promise
const fileId = String((response as any).id)
syncUploadedFileIds([...uploadedFileIds.value, fileId])
onSuccess?.({ id: fileId, fileId })
2026-02-26 14:20:35 +08:00
message.success('图片上传成功')
} catch (error) {
2026-03-26 11:41:38 +08:00
const errorMessage = (error as Error)?.message || '图片上传失败'
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('图片上传失败:', error)
message.error(errorMessage)
onError?.(error)
}
} finally {
uploadTaskMap.delete(taskKey)
activeUploadCount.value = Math.max(0, activeUploadCount.value - 1)
2026-02-26 14:20:35 +08:00
}
}
2026-03-27 15:04:58 +08:00
// 编辑态下 Upload 里的文件可能只剩 fileId,所以预览时需要兼容本地 URL 与远端签名地址两种来源。
2026-02-26 14:20:35 +08:00
const handlePreview = async (file: any) => {
try {
2026-03-26 11:41:38 +08:00
const cachedPreviewUrl = getPreviewUrlFromFile(file)
if (cachedPreviewUrl) {
previewImage.value = cachedPreviewUrl
previewVisible.value = true
return
2026-02-26 14:20:35 +08:00
}
2026-03-26 11:41:38 +08:00
const fileId = resolveUploadedFileId(file)
if (!fileId) {
throw new Error('未找到图片文件标识')
}
if (!imageIdCache.value[fileId]) {
2026-03-27 14:55:41 +08:00
const response = await adminFileApi.getSignedUrl(fileId) as any
2026-03-26 11:41:38 +08:00
imageIdCache.value[fileId] = response
}
previewImage.value = imageIdCache.value[fileId] || ''
2026-02-26 14:20:35 +08:00
previewVisible.value = true
} catch (error) {
console.error('获取预览链接失败:', error)
2026-03-26 11:41:38 +08:00
message.error((error as Error)?.message || '获取预览链接失败')
2026-02-26 14:20:35 +08:00
}
}
const handleRemove = (file: any) => {
2026-03-26 11:41:38 +08:00
const task = uploadTaskMap.get(`image:${String(file.uid)}`)
if (task) {
task.cancel()
return true
2026-02-26 14:20:35 +08:00
}
2026-03-26 11:41:38 +08:00
const fileId = resolveUploadedFileId(file)
if (fileId) {
syncUploadedFileIds(uploadedFileIds.value.filter(id => id !== fileId))
}
return true
2026-02-26 14:20:35 +08:00
}
2026-03-21 13:16:39 +08:00
const syncBusinessHoursValue = () => {
formState.businessHours = businessStartTime.value && businessEndTime.value
? `${businessStartTime.value}-${businessEndTime.value}`
: ''
}
const setBusinessHoursValue = (value?: string) => {
const matched = (value || '').match(/(\d{2}:\d{2})\s*-\s*(\d{2}:\d{2})/)
businessStartTime.value = matched?.[1] || ''
businessEndTime.value = matched?.[2] || ''
syncBusinessHoursValue()
}
const handleBusinessHoursChange = async () => {
syncBusinessHoursValue()
await formRef.value?.validateFields?.(['businessHours']).catch(() => undefined)
}
2026-03-26 12:04:02 +08:00
const showAddModal = async () => {
2026-02-25 10:37:16 +08:00
isEdit.value = false
2026-03-26 12:04:02 +08:00
currentShop.value = null
2026-02-25 10:37:16 +08:00
Object.assign(formState, {
2026-02-25 14:44:50 +08:00
shopName: '',
2026-02-25 10:37:16 +08:00
description: '',
address: '',
businessHours: '',
status: 1,
coverImageFileId: '',
2026-02-26 14:20:35 +08:00
imageFileIds: ''
2026-02-25 10:37:16 +08:00
})
2026-03-21 13:16:39 +08:00
setBusinessHoursValue('')
bannerFileList.value = []
2026-03-26 11:41:38 +08:00
syncUploadedBannerIds([])
2026-02-26 14:20:35 +08:00
imageFileList.value = []
2026-03-26 11:41:38 +08:00
syncUploadedFileIds([])
2026-03-26 12:04:02 +08:00
await restoreDraft()
2026-02-25 10:37:16 +08:00
modalVisible.value = true
}
2026-03-02 10:13:20 +08:00
const showEditModal = async (record: Shop | Record<string, any>) => {
2026-02-25 10:37:16 +08:00
isEdit.value = true
2026-03-02 10:13:20 +08:00
currentShop.value = record as Shop
2026-02-25 10:37:16 +08:00
Object.assign(formState, {
2026-03-02 10:13:20 +08:00
shopName: 'shopName' in record ? record.shopName : (record as any).shopName,
description: 'description' in record ? record.description : (record as any).description,
address: 'address' in record ? record.address : (record as any).address,
businessHours: 'businessHours' in record ? record.businessHours : (record as any).businessHours,
status: 'status' in record ? (record.status ?? 1) : ((record as any).status ?? 1),
coverImageFileId: 'coverImageFileId' in record ? record.coverImageFileId : (record as any).coverImageFileId,
2026-03-02 10:13:20 +08:00
imageFileIds: 'imageFileIds' in record ? record.imageFileIds : (record as any).imageFileIds
2026-02-25 10:37:16 +08:00
})
2026-03-21 13:16:39 +08:00
setBusinessHoursValue(formState.businessHours)
2026-02-26 14:20:35 +08:00
// 加载Banner图片
const coverImageFileId = 'coverImageFileId' in record ? record.coverImageFileId : (record as any).coverImageFileId
if (coverImageFileId) {
2026-03-26 11:41:38 +08:00
const ids = coverImageFileId.split(',').filter((id: string) => id)
syncUploadedBannerIds(ids)
2026-03-26 12:04:02 +08:00
bannerFileList.value = await buildShopUploadFileList(ids, 'Banner')
} else {
bannerFileList.value = []
2026-03-26 11:41:38 +08:00
syncUploadedBannerIds([])
}
// 加载店铺图片
2026-03-02 10:13:20 +08:00
const imageFileIds = 'imageFileIds' in record ? record.imageFileIds : (record as any).imageFileIds
if (imageFileIds) {
2026-03-26 11:41:38 +08:00
const ids = imageFileIds.split(',').filter((id: string) => id)
syncUploadedFileIds(ids)
2026-03-26 12:04:02 +08:00
imageFileList.value = await buildShopUploadFileList(ids, '图片')
2026-02-26 14:20:35 +08:00
} else {
imageFileList.value = []
2026-03-26 11:41:38 +08:00
syncUploadedFileIds([])
2026-02-26 14:20:35 +08:00
}
2026-03-26 12:04:02 +08:00
await restoreDraft()
2026-02-25 10:37:16 +08:00
modalVisible.value = true
}
2026-03-02 10:13:20 +08:00
const showViewModal = async (record: Shop | Record<string, any>) => {
2026-02-28 14:32:28 +08:00
Object.assign(viewFormState, {
2026-03-02 10:13:20 +08:00
shopName: 'shopName' in record ? record.shopName : (record as any).shopName,
description: 'description' in record ? record.description : (record as any).description,
address: 'address' in record ? record.address : (record as any).address,
businessHours: 'businessHours' in record ? record.businessHours : (record as any).businessHours,
status: 'status' in record ? (record.status ?? 1) : ((record as any).status ?? 1),
coverImageFileId: 'coverImageFileId' in record ? record.coverImageFileId : (record as any).coverImageFileId,
2026-03-02 10:13:20 +08:00
imageFileIds: 'imageFileIds' in record ? record.imageFileIds : (record as any).imageFileIds
2026-02-28 14:32:28 +08:00
})
// 加载Banner图片URL
const coverImageFileId = 'coverImageFileId' in record ? record.coverImageFileId : (record as any).coverImageFileId
if (coverImageFileId) {
2026-03-26 11:41:38 +08:00
const ids = coverImageFileId.split(',').filter((id: string) => id)
const urls: string[] = []
for (const id of ids) {
try {
// 检查缓存
if (!imageIdCache.value[id]) {
2026-03-27 14:55:41 +08:00
const response = await adminFileApi.getSignedUrl(id.trim()) as any
imageIdCache.value[id] = response
}
2026-03-10 23:23:15 +08:00
urls.push(imageIdCache.value[id]!)
} catch (error) {
console.error('获取签名链接失败:', error)
urls.push(DEFAULT_SHOP_IMAGE)
}
}
viewBannerUrls.value = urls
} else {
viewBannerUrls.value = []
}
// 加载店铺图片URL
2026-03-02 10:13:20 +08:00
const imageFileIds = 'imageFileIds' in record ? record.imageFileIds : (record as any).imageFileIds
if (imageFileIds) {
2026-03-26 11:41:38 +08:00
const ids = imageFileIds.split(',').filter((id: string) => id)
2026-02-28 14:32:28 +08:00
const urls: string[] = []
for (const id of ids) {
try {
// 检查缓存
if (!imageIdCache.value[id]) {
2026-03-27 14:55:41 +08:00
const response = await adminFileApi.getSignedUrl(id.trim()) as any
2026-03-02 10:13:20 +08:00
imageIdCache.value[id] = response
2026-02-28 14:32:28 +08:00
}
2026-03-10 23:23:15 +08:00
urls.push(imageIdCache.value[id]!)
2026-02-28 14:32:28 +08:00
} catch (error) {
console.error('获取签名链接失败:', error)
urls.push(DEFAULT_SHOP_IMAGE)
}
}
viewImageUrls.value = urls
} else {
viewImageUrls.value = []
2026-02-28 14:32:28 +08:00
}
viewModalVisible.value = true
}
const handleViewModalCancel = () => {
viewModalVisible.value = false
viewImageUrls.value = []
viewBannerUrls.value = []
2026-02-28 14:32:28 +08:00
}
2026-03-26 11:41:38 +08:00
const cancelAllPendingUploads = () => {
uploadTaskMap.forEach(task => task.cancel())
}
2026-03-26 12:04:02 +08:00
const getDraftKey = () => buildDraftStorageKey('admin-shops', isEdit.value ? 'edit' : 'create', currentShop.value?.id ?? 'new')
const buildDraftPayload = () => ({
formState: {
shopName: formState.shopName,
description: formState.description,
address: formState.address,
businessHours: formState.businessHours,
status: formState.status,
coverImageFileId: formState.coverImageFileId,
imageFileIds: formState.imageFileIds
},
businessStartTime: businessStartTime.value,
businessEndTime: businessEndTime.value,
uploadedBannerIds: [...uploadedBannerIds.value],
uploadedFileIds: [...uploadedFileIds.value]
})
const buildShopUploadFileList = async (ids: string[], fileNamePrefix: string) => {
const fileList = []
for (const [index, id] of ids.entries()) {
try {
if (!imageIdCache.value[id]) {
2026-03-27 14:55:41 +08:00
const response = await adminFileApi.getSignedUrl(id.trim()) as any
2026-03-26 12:04:02 +08:00
imageIdCache.value[id] = response
}
fileList.push({
uid: id,
fileId: id,
name: `${fileNamePrefix}${index + 1}`,
status: 'done',
url: imageIdCache.value[id]
})
} catch (error) {
console.error('获取签名链接失败:', error)
fileList.push({
uid: id,
fileId: id,
name: `${fileNamePrefix}${index + 1}`,
status: 'done',
url: ''
})
}
}
return fileList
}
const restoreDraft = async () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
draftSavedAt.value = null
return
}
Object.assign(formState, draft.payload.formState)
businessStartTime.value = draft.payload.businessStartTime || ''
businessEndTime.value = draft.payload.businessEndTime || ''
syncUploadedBannerIds(draft.payload.uploadedBannerIds || [])
syncUploadedFileIds(draft.payload.uploadedFileIds || [])
bannerFileList.value = await buildShopUploadFileList(uploadedBannerIds.value, 'Banner')
imageFileList.value = await buildShopUploadFileList(uploadedFileIds.value, '图片')
draftSavedAt.value = draft.savedAt
message.success('已恢复暂存内容')
}
const handleSaveDraft = () => {
if (isUploadPending.value) {
message.warning('图片上传完成后才能暂存')
return
}
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
draftSavedAt.value = draft.savedAt
message.success('已暂存到本地')
}
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
2026-03-26 11:41:38 +08:00
const syncUploadedBannerIds = (fileIds: string[]) => {
uploadedBannerIds.value = Array.from(new Set(fileIds.filter(id => Boolean(id))))
formState.coverImageFileId = uploadedBannerIds.value.join(',')
}
const syncUploadedFileIds = (fileIds: string[]) => {
uploadedFileIds.value = Array.from(new Set(fileIds.filter(id => Boolean(id))))
formState.imageFileIds = uploadedFileIds.value.join(',')
}
const getUploadResponse = (file: any) => {
if (!file || typeof file !== 'object') {
return null
}
return file.response || null
}
const resolveUploadedFileId = (file: any) => {
const response = getUploadResponse(file)
const responseId = response?.id ?? response?.data?.id ?? file?.fileId
if (responseId !== undefined && responseId !== null && responseId !== '') {
return String(responseId)
}
const fileUid = String(file?.uid || '')
if (/^\d+$/.test(fileUid)) {
return fileUid
}
const fileUrl = String(file?.url || '')
if (/^\d+$/.test(fileUrl)) {
return fileUrl
}
return ''
}
const getPreviewUrlFromFile = (file: any) => {
const fileUrl = typeof file?.url === 'string' ? file.url : ''
if (fileUrl && !/^\d+$/.test(fileUrl)) {
return fileUrl
}
const thumbUrl = typeof file?.thumbUrl === 'string' ? file.thumbUrl : ''
if (thumbUrl) {
return thumbUrl
}
return ''
}
2026-02-25 10:37:16 +08:00
const handleModalOk = async () => {
try {
2026-03-26 11:41:38 +08:00
if (isUploadPending.value) {
message.warning('图片上传完成前不可提交')
return
}
2026-03-21 13:16:39 +08:00
syncBusinessHoursValue()
2026-02-25 10:37:16 +08:00
await formRef.value?.validate()
modalLoading.value = true
if (isEdit.value && currentShop.value) {
2026-02-25 14:44:50 +08:00
await adminShopApi.updateShop(currentShop.value.id, formState)
2026-02-25 10:37:16 +08:00
message.success('更新成功')
} else {
2026-02-25 14:44:50 +08:00
await adminShopApi.createShop(formState)
2026-02-25 10:37:16 +08:00
message.success('创建成功')
}
2026-03-26 12:04:02 +08:00
handleClearDraft(false)
2026-02-25 10:37:16 +08:00
modalVisible.value = false
fetchShopList()
} catch (error) {
console.error(error)
} finally {
modalLoading.value = false
}
}
const handleModalCancel = () => {
2026-03-26 11:41:38 +08:00
cancelAllPendingUploads()
2026-02-25 10:37:16 +08:00
modalVisible.value = false
formRef.value?.resetFields()
2026-03-21 13:16:39 +08:00
setBusinessHoursValue('')
bannerFileList.value = []
2026-03-26 11:41:38 +08:00
syncUploadedBannerIds([])
2026-02-26 14:20:35 +08:00
imageFileList.value = []
2026-03-26 11:41:38 +08:00
syncUploadedFileIds([])
2026-02-25 10:37:16 +08:00
}
2026-03-02 10:13:20 +08:00
const handleDelete = async (record: Shop | Record<string, any>) => {
2026-02-25 10:37:16 +08:00
try {
2026-03-02 10:13:20 +08:00
const shopId = 'id' in record ? record.id : (record as any).id
await adminShopApi.deleteShop(shopId)
2026-02-25 10:37:16 +08:00
message.success('删除成功')
fetchShopList()
} catch (error) {
message.error('删除失败')
}
}
const handleStatusChange = async (record: Shop | Record<string, any>, enabled: boolean) => {
try {
const shopId = 'id' in record ? record.id : (record as any).id
await adminShopApi.updateShopStatus(shopId, enabled ? 1 : 0)
;(record as any).status = enabled ? 1 : 0
message.success(`店铺已${enabled ? '启用' : '停用'}`)
} catch (error) {
message.error('店铺状态更新失败')
}
}
2026-02-26 18:44:47 +08:00
onMounted(async () => {
await loadUserPermissions()
2026-02-25 10:37:16 +08:00
fetchShopList()
})
</script>
<style scoped>
.shops {
padding: 0;
}
2026-02-26 14:20:35 +08:00
.shop-images {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 4px;
}
.shop-banner {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 4px;
2026-02-26 14:20:35 +08:00
}
.no-banner {
color: #999;
font-size: 12px;
}
.upload-tip {
color: #999;
font-size: 12px;
margin-bottom: 8px;
2026-02-26 14:20:35 +08:00
}
2026-03-21 13:16:39 +08:00
2026-03-26 11:41:38 +08:00
.upload-pending-tip {
color: #fa8c16;
font-size: 12px;
margin-top: 8px;
}
2026-03-21 13:16:39 +08:00
.business-hours-picker {
display: flex;
align-items: center;
gap: 12px;
width: 100%;
}
.business-hours-separator {
color: #666;
flex: 0 0 auto;
}
2026-02-25 10:37:16 +08:00
</style>