Files
JayuCloud/FD-Frontend/src/views/admin/ProductsView.vue
T

1588 lines
61 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<div class="products">
<a-page-header v-if="!isMobile" title="作品管理" sub-title="管理美甲作品" />
<section v-else class="admin-page-intro">
<span class="admin-page-intro__eyebrow">经营</span>
<h1 class="admin-page-intro__title">作品管理</h1>
<div class="admin-page-intro__meta">
<span class="admin-page-chip">作品 {{ productList.length }}</span>
</div>
</section>
<a-card :bordered="false">
<template #title v-if="isMobile">
作品列表
</template>
<template #extra>
<div class="admin-toolbar" :class="{ 'admin-toolbar--stacked': isMobile }">
<a-input-search
v-model:value="searchText"
placeholder="搜索作品名称"
:style="isMobile ? { width: '100%' } : { width: '250px' }"
@search="handleSearch"
/>
<a-button v-if="!isMobile && hasPermission('product:create')" type="primary" @click="showAddModal">
<template #icon>
<PlusOutlined />
</template>
新增作品
</a-button>
</div>
</template>
<AdminFilterPanel :active-count="activeFilterCount">
<a-select v-model:value="shopFilter" allow-clear placeholder="所属店铺" style="width: 180px" @change="handleSearch">
<a-select-option v-for="shop in shops" :key="shop.id" :value="shop.id">
{{ shop.shopName }}
</a-select-option>
</a-select>
<a-select v-model:value="tagFilter" allow-clear placeholder="标签" style="width: 160px" @change="handleSearch">
<a-select-option v-for="tag in tags" :key="tag.id" :value="tag.id">
{{ tag.tagName }}
</a-select-option>
</a-select>
<a-input-number v-model:value="minPriceFilter" :min="0" placeholder="最低价" style="width: 120px" @pressEnter="handleSearch" />
<a-input-number v-model:value="maxPriceFilter" :min="0" placeholder="最高价" style="width: 120px" @pressEnter="handleSearch" />
<a-range-picker v-model:value="createdRange" value-format="YYYY-MM-DD HH:mm:ss" show-time @change="handleSearch" />
<a-button @click="resetFilters">重置筛选</a-button>
</AdminFilterPanel>
<a-table
v-if="!isMobile"
:columns="columns"
:data-source="productList"
:loading="loading"
:pagination="pagination"
:scroll="{ x: 'max-content' }"
@change="handleTableChange"
row-key="id"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'image'">
<div class="product-images">
<a-image
v-for="(url, index) in getProductImages(record)"
:key="index"
:width="50"
:height="50"
:src="url"
style="object-fit: cover; border-radius: 4px; margin-right: 4px;"
:preview="false"
@error="handleProductImageError(record, index)"
/>
<a-image
v-if="getProductImages(record).length === 0"
:width="50"
:height="50"
:src="DEFAULT_PRODUCT_IMAGE"
style="object-fit: cover; border-radius: 4px;"
:preview="false"
/>
</div>
</template>
<template v-else-if="column.key === 'shop'">
<span>{{ record.shopName || getShopName(record.shopId) }}</span>
</template>
<template v-else-if="column.key === 'title'">
<div style="max-width: 220px;">
<TableEllipsisText :text="record.title" />
</div>
</template>
<template v-else-if="column.key === 'description'">
<div style="max-width: 320px;">
<TableEllipsisText :text="record.description" :lines="2" />
</div>
</template>
<template v-else-if="column.key === 'price'">
<span style="color: #cf1322; font-weight: 600;">
¥{{ record.price }}
</span>
</template>
<template v-else-if="column.key === 'actions'">
<a-space>
<a-button type="link" size="small" @click="showViewModal(record)">
查看
</a-button>
<a-button v-if="hasPermission('product:edit')" type="link" size="small" @click="showEditModal(record)">
编辑
</a-button>
<a-popconfirm
v-if="hasPermission('product:delete')"
title="确定要删除这个作品吗?"
@confirm="handleDelete(record)"
>
<a-button type="link" size="small" danger>
删除
</a-button>
</a-popconfirm>
</a-space>
</template>
</template>
</a-table>
<AdminMobileCardList v-else :items="productList" empty-description="暂无作品数据">
<template #item="{ item }">
<article class="admin-mobile-card">
<a-image
class="admin-mobile-card__cover admin-mobile-card__cover--wide"
:src="getProductImages(item)[0] || DEFAULT_PRODUCT_IMAGE"
:preview="false"
@error="handleProductImageError(item, 0)"
/>
<div class="admin-mobile-card__head" style="margin-top: 14px">
<div class="admin-mobile-card__body">
<div class="admin-mobile-card__title">{{ item.title }}</div>
<div class="admin-mobile-card__subtitle">{{ item.shopName || getShopName(item.shopId) }}</div>
</div>
<span class="admin-mobile-card__badge">¥{{ item.price }}</span>
</div>
<div class="admin-mobile-card__description">{{ item.description || '暂无描述' }}</div>
<div class="admin-mobile-card__rows">
<div class="admin-mobile-card__row">
<span>预计时长</span>
<strong>{{ formatDuration(item.approximateDuration) }}</strong>
</div>
<div class="admin-mobile-card__row">
<span>互动数据</span>
<strong>赞 {{ item.likeCount || 0 }} / 藏 {{ item.collectCount || 0 }}</strong>
</div>
</div>
<div class="admin-mobile-card__actions">
<a-button size="small" @click="showViewModal(item)">查看</a-button>
<a-button v-if="hasPermission('product:edit')" size="small" @click="showEditModal(item)">编辑</a-button>
<a-button v-if="hasPermission('product:delete')" size="small" danger @click="handleDelete(item)">删除</a-button>
</div>
</article>
</template>
</AdminMobileCardList>
</a-card>
<AdminResponsiveModal
v-model:open="modalVisible"
:title="isEdit ? '编辑作品' : '新增作品'"
:desktop-width="700"
@ok="handleModalOk"
@cancel="handleModalCancel"
:confirmLoading="modalLoading"
:ok-button-props="{ disabled: isUploadPending }"
>
<DraftActions
:saved-at="draftSavedAt"
:disabled="isUploadPending"
@save="handleSaveDraft"
@clear="handleClearDraft"
/>
<a-form
ref="formRef"
:model="formState"
:rules="formRules"
:label-col="{ span: 5 }"
:wrapper-col="{ span: 18 }"
>
<a-form-item label="作品名称" name="title">
<a-input v-model:value="formState.title" placeholder="请输入作品名称" />
</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="targetAudience">
<a-textarea
v-model:value="formState.targetAudience"
placeholder="例如:短甲、通勤、婚礼跟妆、敏感肌需提前沟通"
:rows="3"
/>
</a-form-item>
<a-form-item label="注意事项" name="precautions">
<a-textarea
v-model:value="formState.precautions"
placeholder="例如:完成后 24 小时内避免长时间热水浸泡"
:rows="3"
/>
</a-form-item>
<a-form-item label="店铺" name="shopId">
<a-select
v-model:value="formState.shopId"
placeholder="请选择店铺"
style="width: 100%"
:loading="loadingShops"
:disabled="!isAdmin && !!formState.shopId"
>
<a-select-option
v-if="shops.length === 0"
disabled
value=""
>
暂无店铺数据
</a-select-option>
<a-select-option
v-for="shop in shops"
:key="shop.id"
:value="shop.id"
>
{{ shop.shopName }}
</a-select-option>
</a-select>
</a-form-item>
<template v-if="formState.shopId">
<a-form-item label="作品图片">
<a-upload
v-model:file-list="imageFileList"
list-type="picture-card"
multiple
accept="image/*"
:custom-request="handleUploadImage"
:before-upload="beforeUpload"
@preview="handlePreview"
@remove="handleRemove"
>
<div>
<plus-outlined />
<div style="margin-top: 8px">上传图片</div>
</div>
</a-upload>
<div class="upload-tip">支持多选上传,不限制上传张数,大图将自动使用分片并发上传。</div>
<div v-if="isUploadPending" class="upload-pending-tip">图片正在上传中,上传完成前不可提交。</div>
<a-modal v-model:open="previewVisible" :footer="null" :mask-closable="false" @cancel="previewVisible = false">
<img alt="预览" style="width: 100%" :src="previewImage" />
</a-modal>
</a-form-item>
<a-form-item label="价格" name="price">
<a-input-number
v-model:value="formState.price"
:min="0"
:precision="2"
style="width: 100%"
placeholder="请输入价格"
/>
</a-form-item>
<a-form-item label="点赞数" name="likeCount">
<a-input-number
v-model:value="formState.likeCount"
:min="0"
:precision="0"
:step="1"
style="width: 100%"
placeholder="请输入点赞数量"
/>
</a-form-item>
<a-form-item label="收藏数" name="collectCount">
<a-input-number
v-model:value="formState.collectCount"
:min="0"
:precision="0"
:step="1"
style="width: 100%"
placeholder="请输入收藏数量"
/>
</a-form-item>
<a-form-item label="预计时长" name="approximateDuration">
<a-input-number
v-model:value="formState.approximateDuration"
placeholder="请输入分钟数"
:min="1"
style="width: 100%"
/>
</a-form-item>
<a-form-item label="标签" name="tags">
<a-select
v-model:value="formState.tags"
mode="multiple"
placeholder="请选择标签"
style="width: 100%"
:loading="loadingTags"
>
<a-select-option
v-if="tags.length === 0"
disabled
value=""
>
暂无标签数据
</a-select-option>
<a-select-option
v-for="tag in tags"
:key="tag.id"
:value="tag.id.toString()"
>
{{ tag.tagName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="可预约美甲师" name="bookableArtists">
<a-select
v-model:value="formState.bookableArtists"
mode="multiple"
placeholder="请选择美甲师"
style="width: 100%"
:loading="loadingArtists"
>
<a-select-option
v-if="artists.length === 0"
disabled
value=""
>
暂无美甲师数据
</a-select-option>
<a-select-option
v-for="artist in artists"
:key="artist.id"
:value="artist.id.toString()"
>
{{ artist.nickname }}{{ artist.type === 2 ? '(店长 · 参与制作)' : '' }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="可用优惠券" name="availableCoupons">
<a-select
v-model:value="formState.availableCoupons"
mode="multiple"
placeholder="请选择优惠券"
style="width: 100%"
:loading="loadingCoupons"
:disabled="isCouponSelectionDisabled"
>
<a-select-option
v-if="coupons.length === 0"
disabled
value=""
>
暂无优惠券数据
</a-select-option>
<a-select-option
v-for="coupon in coupons"
:key="coupon?.id"
:value="coupon?.id?.toString()"
>
{{ coupon?.couponName || '' }}
</a-select-option>
</a-select>
<a-space class="coupon-actions">
<a-button
type="link"
size="small"
:disabled="isCouponSelectionDisabled || coupons.length === 0"
@click="handleSelectAllCoupons"
>
一键全选
</a-button>
<a-button
type="link"
size="small"
:disabled="isCouponSelectionDisabled || formState.availableCoupons.length === 0"
@click="handleClearAvailableCoupons"
>
清空
</a-button>
</a-space>
</a-form-item>
</template>
</a-form>
</AdminResponsiveModal>
<!-- 查看作品详情模态框 -->
<AdminResponsiveModal
v-model:open="viewModalVisible"
title="查看作品详情"
:desktop-width="700"
@cancel="handleViewModalCancel"
>
<a-form
:model="viewFormState"
:label-col="{ span: 5 }"
:wrapper-col="{ span: 18 }"
>
<a-form-item label="作品名称">
<a-input v-model:value="viewFormState.title" :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-textarea
v-model:value="viewFormState.targetAudience"
:rows="3"
:disabled="true"
/>
</a-form-item>
<a-form-item label="注意事项">
<a-textarea
v-model:value="viewFormState.precautions"
:rows="3"
:disabled="true"
/>
</a-form-item>
<a-form-item label="店铺">
<a-select v-model:value="viewFormState.shopId" :disabled="true">
<a-select-option
v-for="shop in shops"
:key="shop.id"
:value="shop.id"
>
{{ shop.shopName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="作品图片">
<div class="product-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"
/>
</div>
</a-form-item>
<a-form-item label="价格">
<a-input-number
v-model:value="viewFormState.price"
:disabled="true"
style="width: 100%"
/>
</a-form-item>
<a-form-item label="点赞数">
<a-input-number
v-model:value="viewFormState.likeCount"
:disabled="true"
style="width: 100%"
/>
</a-form-item>
<a-form-item label="收藏数">
<a-input-number
v-model:value="viewFormState.collectCount"
:disabled="true"
style="width: 100%"
/>
</a-form-item>
<a-form-item label="预计时长">
<a-input-number
v-model:value="viewFormState.approximateDuration"
:disabled="true"
style="width: 100%"
/>
</a-form-item>
<a-form-item label="标签">
<a-select
v-model:value="viewFormState.tags"
mode="multiple"
:disabled="true"
style="width: 100%"
>
<a-select-option
v-for="tag in tags"
:key="tag.id"
:value="tag.id.toString()"
>
{{ tag.tagName }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="可预约美甲师">
<a-select
v-model:value="viewFormState.bookableArtists"
mode="multiple"
:disabled="true"
style="width: 100%"
>
<a-select-option
v-for="artist in artists"
:key="artist?.id"
:value="artist?.id?.toString()"
>
{{ artist?.nickname || '' }}{{ artist?.type === 2 ? '(店长 · 参与制作)' : '' }}
</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="可用优惠券">
<a-select
v-model:value="viewFormState.availableCoupons"
mode="multiple"
:disabled="true"
style="width: 100%"
>
<a-select-option
v-for="coupon in coupons"
:key="coupon?.id"
:value="coupon?.id?.toString()"
>
{{ coupon?.couponName || '' }}
</a-select-option>
</a-select>
</a-form-item>
</a-form>
</AdminResponsiveModal>
<AdminMobileFab
:visible="isMobile && hasPermission('product:create') && !modalVisible && !viewModalVisible"
label="新增作品"
@click="showAddModal"
/>
</div>
</template>
<script setup lang="ts">
/**
* ProductsView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, ref, reactive, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import type { UploadProps } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import DraftActions from '@/components/DraftActions.vue'
import TableEllipsisText from '@/components/TableEllipsisText.vue'
import { DEFAULT_PRODUCT_IMAGE } from '@/constants'
/**
* Purpose: Product supports ProductsView.vue by holding or executing the product page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
import { adminProductApi, type Product, adminShopApi, type Shop, adminFileApi, adminTagApi, adminArtistApi, adminCouponApi } from '@/api/admin'
/**
* Purpose: ChunkUploadTask supports ProductsView.vue by holding or executing the chunk upload task page or API role.
* Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow.
*/
import { createChunkUploadTask, type ChunkUploadTask } from '@/utils/chunk-upload'
import { buildDraftStorageKey, clearDraftRecord, loadDraftRecord, saveDraftRecord } from '@/utils/form-draft'
import { usePermission } from '@/utils/permission'
import {
buildAdminUploadFileList,
buildSignedImageUrlMap,
getRecordImageUrls,
refreshSignedImageUrl,
resolveSignedImageUrl,
resolveSignedImageUrls
} from '@/utils/admin-image-assets'
import { parseImageFileIds } from '@/utils/signed-image-cache'
import type { IdType } from '@/utils/id'
import { sameId } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading'
import { createAdminPagination, applyAdminTablePaginationChange, type AdminTablePaginationChange } from '@/utils/admin-table'
import { resolveUploadedFileId, type AdminUploadFileLike, type AdminUploadTaskFile } from '@/utils/admin-upload-file'
import { useAdminViewport } from '@/composables/useAdminViewport'
import AdminMobileCardList from '@/components/admin/AdminMobileCardList.vue'
import AdminMobileFab from '@/components/admin/AdminMobileFab.vue'
import AdminFilterPanel from '@/components/admin/AdminFilterPanel.vue'
import AdminResponsiveModal from '@/components/admin/AdminResponsiveModal.vue'
const { hasPermission, loadUserPermissions } = usePermission()
const { isMobile } = useAdminViewport()
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** searchText is a reactive state variable used by the template and event handlers. */
const searchText = ref('')
/**
* Purpose: shopFilter supports ProductsView.vue by holding or executing the shop filter page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const shopFilter = ref<IdType | undefined>()
/**
* Purpose: tagFilter supports ProductsView.vue by holding or executing the tag filter page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const tagFilter = ref<IdType | undefined>()
/**
* Purpose: minPriceFilter supports ProductsView.vue by holding or executing the min price filter page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const minPriceFilter = ref<number | undefined>()
/**
* Purpose: maxPriceFilter supports ProductsView.vue by holding or executing the max price filter page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const maxPriceFilter = ref<number | undefined>()
/**
* Purpose: createdRange supports ProductsView.vue by holding or executing the created range page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const createdRange = ref<[string, string] | undefined>()
const activeFilterCount = computed(() => [
searchText.value,
shopFilter.value,
tagFilter.value,
minPriceFilter.value,
maxPriceFilter.value,
createdRange.value?.length ? 'date' : ''
].filter(value => value !== undefined && value !== null && value !== '').length)
/**
* Purpose: productList supports ProductsView.vue by holding or executing the product list page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const productList = ref<Product[]>([])
/** modalVisible is a reactive state variable used by the template and event handlers. */
const modalVisible = ref(false)
/** viewModalVisible is a reactive state variable used by the template and event handlers. */
const viewModalVisible = ref(false)
/** modalLoading is a reactive state variable used by the template and event handlers. */
const modalLoading = ref(false)
/** isEdit is a reactive state variable used by the template and event handlers. */
const isEdit = ref(false)
/**
* Purpose: currentProduct supports ProductsView.vue by holding or executing the current product page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const currentProduct = ref<Product | null>(null)
/**
* Purpose: shops supports ProductsView.vue by holding or executing the shops page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const shops = ref<Shop[]>([])
/** loadingShops is a reactive state variable used by the template and event handlers. */
const loadingShops = ref(false)
/**
* Purpose: tags supports ProductsView.vue by holding or executing the tags page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const tags = ref<any[]>([])
/** loadingTags is a reactive state variable used by the template and event handlers. */
const loadingTags = ref(false)
/**
* Purpose: artists supports ProductsView.vue by holding or executing the artists page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const artists = ref<any[]>([])
/** loadingArtists is a reactive state variable used by the template and event handlers. */
const loadingArtists = ref(false)
/**
* Purpose: coupons supports ProductsView.vue by holding or executing the coupons page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const coupons = ref<any[]>([])
/** loadingCoupons is a reactive state variable used by the template and event handlers. */
const loadingCoupons = ref(false)
/** previewVisible is a reactive state variable used by the template and event handlers. */
const previewVisible = ref(false)
/** previewImage is a reactive state variable used by the template and event handlers. */
const previewImage = ref('')
/**
* Purpose: imageFileList supports ProductsView.vue by holding or executing the image file list page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const imageFileList = ref<any[]>([])
/**
* Purpose: uploadedFileIds supports ProductsView.vue by holding or executing the uploaded file ids page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const uploadedFileIds = ref<string[]>([])
/**
* Purpose: imageUrls supports ProductsView.vue by holding or executing the image urls page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const imageUrls = ref<Record<string, string[]>>({})
/**
* Purpose: viewImageUrls supports ProductsView.vue by holding or executing the view image urls page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const viewImageUrls = ref<string[]>([])
/** isAdmin is a reactive state variable used by the template and event handlers. */
const isAdmin = ref(false)
/**
* Purpose: formRef supports ProductsView.vue by holding or executing the form ref page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const formRef = ref<any>(null)
/**
* Purpose: uploadTaskMap supports ProductsView.vue by holding or executing the upload task map page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const uploadTaskMap = new Map<string, ChunkUploadTask<any>>()
/** activeUploadCount is a reactive state variable used by the template and event handlers. */
const activeUploadCount = ref(0)
/** isUploadPending is a reactive state variable used by the template and event handlers. */
const isUploadPending = computed(() => activeUploadCount.value > 0)
/**
* Purpose: draftSavedAt supports ProductsView.vue by holding or executing the draft saved at page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const draftSavedAt = ref<number | null>(null)
/**
* Purpose: requestTokens supports ProductsView.vue by holding or executing the request tokens page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const requestTokens = reactive({
shops: 0,
tags: 0,
artists: 0,
coupons: 0,
products: 0
})
/** nextRequestToken is a local helper used by this page script. */
const nextRequestToken = (key: keyof typeof requestTokens) => {
requestTokens[key] += 1
return requestTokens[key]
}
/** isLatestRequestToken is a local helper used by this page script. */
const isLatestRequestToken = (key: keyof typeof requestTokens, token: number) => requestTokens[key] === token
/** formatDuration is a local helper used by this page script. */
const formatDuration = (value?: string | number | null) => {
if (value === undefined || value === null || value === '') {
return '--'
}
const text = String(value).trim()
return text.includes('分钟') ? text : `${text}分钟`
}
/**
* Purpose: viewFormState supports ProductsView.vue by holding or executing the view form state page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const viewFormState = reactive({
shopId: undefined,
title: '',
description: '',
targetAudience: '',
precautions: '',
imageFileIds: '',
price: 0,
likeCount: 0,
collectCount: 0,
tags: [] as string[],
approximateDuration: undefined,
bookableArtists: [] as string[],
availableCoupons: [] as string[]
})
/**
* Purpose: pagination supports ProductsView.vue by holding or executing the pagination page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const pagination = reactive(createAdminPagination())
/**
* Purpose: formState supports ProductsView.vue by holding or executing the form state page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const formState = reactive({
shopId: undefined,
title: '',
description: '',
targetAudience: '',
precautions: '',
imageFileIds: '',
price: 0,
likeCount: 0,
collectCount: 0,
tags: [] as string[],
approximateDuration: undefined,
bookableArtists: [] as string[],
availableCoupons: [] as string[]
})
/** validateInteractionCount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const validateInteractionCount = async (_rule: any, value: number | undefined) => {
if (value === undefined || value === null) {
return Promise.resolve()
}
if (!Number.isInteger(Number(value)) || Number(value) < 0) {
return Promise.reject('请输入大于等于 0 的整数')
}
return Promise.resolve()
}
const formRules: any = {
title: [{ required: true, message: '请输入作品名称', trigger: 'blur' }],
description: [{ required: true, message: '请输入作品描述', trigger: 'blur' }],
price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
likeCount: [{ validator: validateInteractionCount, trigger: 'change' }],
collectCount: [{ validator: validateInteractionCount, trigger: 'change' }],
shopId: [{ required: true, message: '请选择店铺', trigger: 'change' }],
tags: [{ required: true, message: '请选择标签', trigger: 'change' }],
bookableArtists: [{ required: true, message: '请选择美甲师', trigger: 'change' }]
}
/**
* Purpose: columns supports ProductsView.vue by holding or executing the columns page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const columns = [
{ title: '图片', key: 'image', width: 150 },
{ title: '作品名称', dataIndex: 'title', key: 'title' },
{ title: '所属店铺', key: 'shop', width: 150 },
{ title: '描述', dataIndex: 'description', key: 'description' },
{ title: '价格', key: 'price', width: 100 },
{ title: '预计时长', dataIndex: 'approximateDuration', key: 'approximateDuration', width: 120 },
{ title: '点赞', dataIndex: 'likeCount', key: 'likeCount', width: 80 },
{ title: '收藏', dataIndex: 'collectCount', key: 'collectCount', width: 80 },
{ title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
{ title: '操作', key: 'actions', width: 150, fixed: 'right' as const }
]
/** getShopName is a local helper used by this page script. */
const getShopName = (shopId: IdType): string => {
const normalizedShopId = normalizeShopIdValue(shopId)
const shop = shops.value.find(s => normalizeShopIdValue(s.id) === normalizedShopId)
return shop ? shop.shopName : '未知店铺'
}
/** normalizeShopIdValue is a local helper used by this page script. */
const normalizeShopIdValue = (value: string | number | undefined | null) => {
if (value === undefined || value === null || value === '') {
return ''
}
return String(value)
}
/** normalizeInteractionCount is a local helper used by this page script. */
const normalizeInteractionCount = (value: unknown) => {
const numericValue = Number(value)
if (!Number.isFinite(numericValue) || numericValue < 0) {
return 0
}
return Math.floor(numericValue)
}
/** getCurrentUserInfo is a local helper used by this page script. */
const getCurrentUserInfo = () => {
try {
const userInfoStr = localStorage.getItem('adminUserInfo')
if (userInfoStr) {
const userInfo = JSON.parse(userInfoStr)
// 判断用户是否为管理员(类型为4)
isAdmin.value = userInfo.type === 4
return userInfo
}
} catch (error) {
console.error('获取当前用户信息失败', error)
}
return null
}
/** canManageAvailableCoupons is a local helper used by this page script. */
const canManageAvailableCoupons = () => {
const userInfo = getCurrentUserInfo()
return Boolean(userInfo && (userInfo.type === 2 || userInfo.type === 4))
}
/** isCouponSelectionDisabled is a reactive state variable used by the template and event handlers. */
const isCouponSelectionDisabled = computed(() => !canManageAvailableCoupons())
/** fetchShops is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchShops = async () => {
const requestToken = nextRequestToken('shops')
loadingShops.value = true
try {
const currentUser = getCurrentUserInfo()
// 检查用户类型和权限
if (currentUser && currentUser.type === 3 && currentUser.shopId) {
// 美甲师直接使用自己的店铺ID,不需要获取店铺列表
if (isLatestRequestToken('shops', requestToken)) {
shops.value = []
formState.shopId = currentUser.shopId
}
} else {
const response = await adminShopApi.listAllShops() as any
const res = response || []
if (!isLatestRequestToken('shops', requestToken)) {
return
}
// 根据用户权限控制店铺列表的显示
if (currentUser && currentUser.type !== 4 && currentUser.shopId) {
// 如果是店长,只显示用户所属的店铺
shops.value = res?.filter((shop: any) => sameId(shop.id, currentUser.shopId)) || []
// 默认选择用户所属的店铺,并且不可修改
formState.shopId = currentUser.shopId
} else {
// 如果是管理员,显示所有店铺
shops.value = res || []
}
}
} catch (error) {
// 权限不足时不显示错误提示
console.error('获取店铺列表失败:', error)
} finally {
if (isLatestRequestToken('shops', requestToken)) {
loadingShops.value = false
}
}
}
/** fetchTags is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchTags = async (shopId?: IdType) => {
const requestToken = nextRequestToken('tags')
loadingTags.value = true
try {
let response
if (shopId) {
response = await adminTagApi.listTagsByShopId(shopId) as any
} else {
response = await adminTagApi.listAllTags() as any
}
if (!isLatestRequestToken('tags', requestToken)) {
return
}
tags.value = response || []
} catch (error) {
console.error('获取标签列表失败', error)
message.error('获取标签列表失败')
} finally {
if (isLatestRequestToken('tags', requestToken)) {
loadingTags.value = false
}
}
}
/** fetchArtists is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchArtists = async (shopId?: IdType) => {
const requestToken = nextRequestToken('artists')
loadingArtists.value = true
try {
const response = await adminArtistApi.listArtists(shopId) as any
if (!isLatestRequestToken('artists', requestToken)) {
return
}
artists.value = response || []
} catch (error) {
console.error('获取美甲师列表失败', error)
message.error('获取美甲师列表失败')
} finally {
if (isLatestRequestToken('artists', requestToken)) {
loadingArtists.value = false
}
}
}
/** syncAvailableCouponSelection is a local helper used by this page script. */
const syncAvailableCouponSelection = () => {
const availableCouponIdSet = new Set(
coupons.value
.map(coupon => coupon?.id)
.filter((id): id is IdType => id !== undefined && id !== null)
.map(id => String(id))
)
formState.availableCoupons = formState.availableCoupons.filter(couponId => availableCouponIdSet.has(String(couponId)))
}
/** fetchCoupons is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchCoupons = async (shopId?: IdType) => {
if (!shopId) {
nextRequestToken('coupons')
coupons.value = []
formState.availableCoupons = []
return
}
const requestToken = nextRequestToken('coupons')
loadingCoupons.value = true
try {
const response = await adminCouponApi.listAllCoupons(shopId)
const res = typeof response === 'object' && 'data' in response ? response.data : response
if (!isLatestRequestToken('coupons', requestToken)) {
return
}
coupons.value = (res as any[]) || []
syncAvailableCouponSelection()
} catch (error) {
console.error('获取优惠券列表失败', error)
message.error('获取优惠券列表失败')
} finally {
if (isLatestRequestToken('coupons', requestToken)) {
loadingCoupons.value = false
}
}
}
/** fetchProductList is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchProductList = async () => {
const requestToken = nextRequestToken('products')
loading.value = true
try {
const currentUser = getCurrentUserInfo()
const params: any = {
page: pagination.current,
size: pagination.pageSize,
keyword: searchText.value,
shopId: shopFilter.value,
tagId: tagFilter.value,
minPrice: minPriceFilter.value,
maxPrice: maxPriceFilter.value,
createdFrom: createdRange.value?.[0],
createdTo: createdRange.value?.[1]
}
if (currentUser && currentUser.type !== 4 && currentUser.shopId) {
params.shopId = currentUser.shopId
}
const response = await adminProductApi.listProducts(params) as any
if (!isLatestRequestToken('products', requestToken)) {
return
}
const nextProducts = response?.list || []
productList.value = nextProducts
pagination.total = Number(response?.total || 0)
const nextImageUrls = await loadImageUrls(nextProducts, requestToken)
if (nextImageUrls && isLatestRequestToken('products', requestToken)) {
imageUrls.value = nextImageUrls
}
} catch (error) {
message.error('获取作品列表失败')
} finally {
if (isLatestRequestToken('products', requestToken)) {
loading.value = false
}
}
}
/**
* Purpose: resetFilters supports ProductsView.vue by holding or executing the reset filters page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const resetFilters = () => {
searchText.value = ''
shopFilter.value = undefined
tagFilter.value = undefined
minPriceFilter.value = undefined
maxPriceFilter.value = undefined
createdRange.value = undefined
handleSearch()
}
/** loadImageUrls is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadImageUrls = async (products: Product[], requestToken?: number) => {
return buildSignedImageUrlMap(
products,
'imageFileIds',
DEFAULT_PRODUCT_IMAGE,
true,
() => Boolean(requestToken && !isLatestRequestToken('products', requestToken))
)
}
/** getProductImages is a local helper used by this page script. */
const getProductImages = (product: { id?: IdType }): string[] =>
getRecordImageUrls(product, imageUrls.value, [DEFAULT_PRODUCT_IMAGE])
const handleProductImageError = async (product: { id?: IdType; imageFileIds?: string }, imageIndex: number) => {
if (product.id === undefined || product.id === null) return
const fileId = parseImageFileIds(product.imageFileIds)[imageIndex]
if (!fileId) return
const refreshedUrl = await refreshSignedImageUrl(fileId, DEFAULT_PRODUCT_IMAGE)
if (!refreshedUrl || refreshedUrl === DEFAULT_PRODUCT_IMAGE) return
const productKey = String(product.id)
const currentUrls = imageUrls.value[productKey] || []
const nextUrls = [...currentUrls]
nextUrls[imageIndex] = refreshedUrl
imageUrls.value = {
...imageUrls.value,
[productKey]: nextUrls
}
}
/** handleSearch is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleSearch = async () => {
pagination.current = 1
await runWithGlobalLoading(() => fetchProductList())
}
/** handleTableChange is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleTableChange = async (pag: AdminTablePaginationChange) => {
const nextPagination = applyAdminTablePaginationChange(pagination, pag)
pagination.current = nextPagination.current
pagination.pageSize = nextPagination.pageSize
await runWithGlobalLoading(() => fetchProductList())
}
/** showAddModal is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const showAddModal = async () => {
isEdit.value = false
currentProduct.value = null
const currentUser = getCurrentUserInfo()
const shopId = (currentUser && currentUser.type !== 4 && currentUser.shopId) ? currentUser.shopId : undefined
Object.assign(formState, {
shopId: shopId,
title: '',
description: '',
targetAudience: '',
precautions: '',
imageFileIds: '',
price: 0,
likeCount: 0,
collectCount: 0,
tags: [],
approximateDuration: '',
bookableArtists: [],
availableCoupons: []
})
imageFileList.value = []
syncUploadedFileIds([])
// 如果有店铺ID,获取该店铺的美甲师列表
if (shopId) {
fetchArtists(shopId)
fetchCoupons(shopId)
}
await restoreDraft()
modalVisible.value = true
}
/** showEditModal is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const showEditModal = async (record: Product | Record<string, any>) => {
isEdit.value = true
currentProduct.value = record as Product
const recordShopId = 'shopId' in record ? record.shopId : (record as any).shopId
const recordTitle = 'title' in record ? record.title : (record as any).title
const recordDescription = 'description' in record ? record.description : (record as any).description
const recordTargetAudience = 'targetAudience' in record ? record.targetAudience : (record as any).targetAudience
const recordPrecautions = 'precautions' in record ? record.precautions : (record as any).precautions
const recordImageFileIds = 'imageFileIds' in record ? record.imageFileIds : (record as any).imageFileIds
const recordPrice = 'price' in record ? record.price : (record as any).price
const recordLikeCount = 'likeCount' in record ? record.likeCount : (record as any).likeCount
const recordCollectCount = 'collectCount' in record ? record.collectCount : (record as any).collectCount
const recordTags = 'tags' in record ? record.tags : (record as any).tags
const recordApproximateDuration = 'approximateDuration' in record ? record.approximateDuration : (record as any).approximateDuration
const recordBookableArtists = 'bookableArtists' in record ? record.bookableArtists : (record as any).bookableArtists
const recordAvailableCoupons = 'availableCoupons' in record ? record.availableCoupons : (record as any).availableCoupons
// 处理标签
const tagsArray = recordTags ? recordTags.split(';').filter((tag: string) => tag) : []
// 处理美甲师
const artistsArray = recordBookableArtists ? recordBookableArtists.split(',').filter((artist: string) => artist) : []
// 处理优惠券
const couponsArray = recordAvailableCoupons ? recordAvailableCoupons.split(',').filter((coupon: string) => coupon) : []
// 处理预计时长,将字符串转换为数字
const durationNumber = recordApproximateDuration ? parseInt(recordApproximateDuration.replace('分钟', '')) : undefined
Object.assign(formState, {
shopId: recordShopId,
title: recordTitle,
description: recordDescription,
targetAudience: recordTargetAudience || '',
precautions: recordPrecautions || '',
imageFileIds: recordImageFileIds,
price: recordPrice,
likeCount: normalizeInteractionCount(recordLikeCount),
collectCount: normalizeInteractionCount(recordCollectCount),
tags: tagsArray,
approximateDuration: durationNumber,
bookableArtists: artistsArray,
availableCoupons: couponsArray
})
if (recordImageFileIds) {
const ids = recordImageFileIds.split(',').filter((id: string) => id)
syncUploadedFileIds(ids)
imageFileList.value = await buildImageFileListByIds(ids)
} else {
imageFileList.value = []
syncUploadedFileIds([])
}
// 获取该店铺的美甲师列表
if (recordShopId) {
await fetchArtists(recordShopId)
await fetchCoupons(recordShopId)
}
await restoreDraft()
modalVisible.value = true
}
/** showViewModal is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const showViewModal = async (record: Product | Record<string, any>) => {
const recordShopId = 'shopId' in record ? record.shopId : (record as any).shopId
const recordTitle = 'title' in record ? record.title : (record as any).title
const recordDescription = 'description' in record ? record.description : (record as any).description
const recordTargetAudience = 'targetAudience' in record ? record.targetAudience : (record as any).targetAudience
const recordPrecautions = 'precautions' in record ? record.precautions : (record as any).precautions
const recordImageFileIds = 'imageFileIds' in record ? record.imageFileIds : (record as any).imageFileIds
const recordPrice = 'price' in record ? record.price : (record as any).price
const recordLikeCount = 'likeCount' in record ? record.likeCount : (record as any).likeCount
const recordCollectCount = 'collectCount' in record ? record.collectCount : (record as any).collectCount
const recordTags = 'tags' in record ? record.tags : (record as any).tags
const recordApproximateDuration = 'approximateDuration' in record ? record.approximateDuration : (record as any).approximateDuration
const recordBookableArtists = 'bookableArtists' in record ? record.bookableArtists : (record as any).bookableArtists
const recordAvailableCoupons = 'availableCoupons' in record ? record.availableCoupons : (record as any).availableCoupons
// 处理标签
const tagsArray = recordTags ? recordTags.split(';').filter((tag: string) => tag) : []
// 处理美甲师
const artistsArray = recordBookableArtists ? recordBookableArtists.split(',').filter((artist: string) => artist) : []
// 处理优惠券
const couponsArray = recordAvailableCoupons ? recordAvailableCoupons.split(',').filter((coupon: string) => coupon) : []
// 处理预计时长,将字符串转换为数字
const durationNumber = recordApproximateDuration ? parseInt(recordApproximateDuration.replace('分钟', '')) : undefined
Object.assign(viewFormState, {
shopId: recordShopId,
title: recordTitle,
description: recordDescription,
targetAudience: recordTargetAudience || '',
precautions: recordPrecautions || '',
imageFileIds: recordImageFileIds,
price: recordPrice,
likeCount: normalizeInteractionCount(recordLikeCount),
collectCount: normalizeInteractionCount(recordCollectCount),
tags: tagsArray,
approximateDuration: durationNumber,
bookableArtists: artistsArray,
availableCoupons: couponsArray
})
// 加载图片URL
viewImageUrls.value = await resolveSignedImageUrls(recordImageFileIds, DEFAULT_PRODUCT_IMAGE, true)
// 获取该店铺的美甲师列表
if (recordShopId) {
await fetchArtists(recordShopId)
await fetchCoupons(recordShopId)
}
viewModalVisible.value = true
}
/** handleViewModalCancel is a local helper used by this page script. */
const handleViewModalCancel = () => {
viewModalVisible.value = false
viewImageUrls.value = []
}
/** cancelAllPendingUploads is a local helper used by this page script. */
const cancelAllPendingUploads = () => {
uploadTaskMap.forEach(task => task.cancel())
}
/** getDraftKey is a local helper used by this page script. */
const getDraftKey = () => buildDraftStorageKey('admin-products', isEdit.value ? 'edit' : 'create', currentProduct.value?.id ?? 'new')
/** buildDraftPayload is a local helper used by this page script. */
const buildDraftPayload = () => ({
formState: {
shopId: formState.shopId,
title: formState.title,
description: formState.description,
targetAudience: formState.targetAudience,
precautions: formState.precautions,
imageFileIds: formState.imageFileIds,
price: formState.price,
likeCount: formState.likeCount,
collectCount: formState.collectCount,
tags: [...formState.tags],
approximateDuration: formState.approximateDuration,
bookableArtists: [...formState.bookableArtists],
availableCoupons: [...formState.availableCoupons]
},
uploadedFileIds: [...uploadedFileIds.value]
})
/** buildImageFileListByIds is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const buildImageFileListByIds = async (ids: string[]) => {
return buildAdminUploadFileList(ids, '图片', DEFAULT_PRODUCT_IMAGE)
}
/** restoreDraft is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const restoreDraft = async () => {
const draft = loadDraftRecord<ReturnType<typeof buildDraftPayload>>(getDraftKey())
if (!draft) {
draftSavedAt.value = null
return
}
Object.assign(formState, draft.payload.formState)
formState.likeCount = normalizeInteractionCount(formState.likeCount)
formState.collectCount = normalizeInteractionCount(formState.collectCount)
syncUploadedFileIds(draft.payload.uploadedFileIds || [])
imageFileList.value = await buildImageFileListByIds(uploadedFileIds.value)
draftSavedAt.value = draft.savedAt
message.success('已恢复暂存内容')
}
/** handleSaveDraft is a local helper used by this page script. */
const handleSaveDraft = () => {
if (isUploadPending.value) {
message.warning('图片上传完成后才能暂存')
return
}
const draft = saveDraftRecord(getDraftKey(), buildDraftPayload())
draftSavedAt.value = draft.savedAt
message.success('已暂存到本地')
}
/** handleClearDraft is a local helper used by this page script. */
const handleClearDraft = (showMessage = true) => {
clearDraftRecord(getDraftKey())
draftSavedAt.value = null
if (showMessage) {
message.success('已清除暂存')
}
}
/** syncUploadedFileIds is a local helper used by this page script. */
const syncUploadedFileIds = (fileIds: string[]) => {
uploadedFileIds.value = Array.from(new Set(fileIds.filter(id => Boolean(id))))
formState.imageFileIds = uploadedFileIds.value.join(',')
}
/** getPreviewUrlFromFile is a local helper used by this page script. */
const getPreviewUrlFromFile = (file: AdminUploadFileLike) => {
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 ''
}
/** beforeUpload is a local helper used by this page script. */
const beforeUpload = (file: File) => {
const isImage = file.type.startsWith('image/')
if (!isImage) {
message.error('只能上传图片文件')
}
return isImage
}
// 作品图片走分片上传,并在上传前做压缩兜底,保证大图也能稳定进入对象存储。
/** handleUploadImage is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleUploadImage: UploadProps['customRequest'] = async (options) => {
const { file, onSuccess, onError, onProgress } = options
const uploadFile = file as AdminUploadTaskFile
const task = createChunkUploadTask({
file: uploadFile,
scene: 'admin-product-image',
concurrency: 3,
api: {
initUpload: adminFileApi.initChunkUpload,
uploadChunk: adminFileApi.uploadChunk,
completeUpload: adminFileApi.completeChunkUpload,
cancelUpload: adminFileApi.cancelChunkUpload
},
onProgress: (percent) => {
onProgress?.({ percent })
}
})
uploadTaskMap.set(String(uploadFile.uid), task)
activeUploadCount.value += 1
try {
const { response } = await task.promise
const fileId = String((response as any).id)
syncUploadedFileIds([...uploadedFileIds.value, fileId])
onSuccess?.({ id: fileId, fileId })
message.success('图片上传成功')
} catch (error) {
const errorMessage = (error as Error)?.message || '图片上传失败'
if (errorMessage !== '上传已取消' && errorMessage !== 'canceled') {
console.error('图片上传失败:', error)
message.error(errorMessage)
onError?.(error as never)
}
} finally {
uploadTaskMap.delete(String(uploadFile.uid))
activeUploadCount.value = Math.max(0, activeUploadCount.value - 1)
}
}
// Ant Upload 的文件对象来源很多,预览时优先复用已有 URL,缺失时再回源签名地址。
/** handlePreview is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handlePreview: UploadProps['onPreview'] = async (file) => {
try {
const cachedPreviewUrl = getPreviewUrlFromFile(file as AdminUploadFileLike)
if (cachedPreviewUrl) {
previewImage.value = cachedPreviewUrl
previewVisible.value = true
return
}
const fileId = resolveUploadedFileId(file as AdminUploadFileLike)
if (!fileId) {
throw new Error('未找到图片文件标识')
}
previewImage.value = await resolveSignedImageUrl(fileId, '')
previewVisible.value = true
} catch (error) {
console.error('获取预览链接失败:', error)
message.error((error as Error)?.message || '获取预览链接失败')
}
}
/** handleRemove is a local helper used by this page script. */
const handleRemove: UploadProps['onRemove'] = (file) => {
const uploadTask = uploadTaskMap.get(String(file.uid))
if (uploadTask) {
uploadTask.cancel()
return true
}
const fileId = resolveUploadedFileId(file as AdminUploadFileLike)
if (fileId) {
syncUploadedFileIds(uploadedFileIds.value.filter(id => id !== fileId))
}
return true
}
/** handleModalOk is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleModalOk = async () => {
try {
if (isUploadPending.value) {
message.warning('图片上传完成前不可提交')
return
}
await formRef.value?.validate()
modalLoading.value = true
await runWithGlobalLoading(async () => {
// 处理标签,转换为分号分隔的字符串
const tagsString = Array.isArray(formState.tags) ? formState.tags.join(';') : formState.tags
// 处理美甲师,转换为逗号分隔的字符串
const artistsString = Array.isArray(formState.bookableArtists) ? formState.bookableArtists.join(',') : formState.bookableArtists
// 处理优惠券,转换为逗号分隔的字符串
const couponsString = Array.isArray(formState.availableCoupons) ? formState.availableCoupons.join(',') : formState.availableCoupons
// 处理预计时长,转换为字符串并添加"分钟"单位
const durationString = formState.approximateDuration ? `${formState.approximateDuration}分钟` : ''
// 准备请求数据
const requestData = {
...formState,
imageFileIds: uploadedFileIds.value.join(','),
likeCount: normalizeInteractionCount(formState.likeCount),
collectCount: normalizeInteractionCount(formState.collectCount),
tags: tagsString,
bookableArtists: artistsString,
availableCoupons: couponsString,
approximateDuration: durationString,
shopId: formState.shopId || 0
}
if (isEdit.value && currentProduct.value) {
await adminProductApi.updateProduct(currentProduct.value.id, requestData)
message.success('更新成功')
} else {
await adminProductApi.createProduct(requestData)
message.success('创建成功')
}
handleClearDraft(false)
modalVisible.value = false
await fetchProductList()
})
} catch (error: any) {
console.error(error)
message.error(error.message || (isEdit.value ? '更新失败' : '创建失败'))
} finally {
modalLoading.value = false
}
}
/** handleModalCancel is a local helper used by this page script. */
const handleModalCancel = () => {
cancelAllPendingUploads()
modalVisible.value = false
formRef.value?.resetFields()
}
/** handleDelete is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleDelete = async (record: Product | Record<string, any>) => {
try {
await runWithGlobalLoading(async () => {
const recordId = 'id' in record ? record.id : (record as any).id
await adminProductApi.deleteProduct(recordId)
message.success('删除成功')
// 从缓存中移除
delete imageUrls.value[recordId]
await fetchProductList()
})
} catch (error: any) {
console.error('删除失败:', error)
message.error(error.message || '删除失败')
}
}
/** handleSelectAllCoupons is a local helper used by this page script. */
const handleSelectAllCoupons = () => {
if (isCouponSelectionDisabled.value) {
return
}
formState.availableCoupons = coupons.value
.map(coupon => coupon?.id)
.filter((id): id is IdType => id !== undefined && id !== null)
.map(id => String(id))
}
/** handleClearAvailableCoupons is a local helper used by this page script. */
const handleClearAvailableCoupons = () => {
formState.availableCoupons = []
}
onMounted(async () => {
await loadUserPermissions()
fetchShops()
fetchTags()
fetchProductList()
})
// 监听店铺选择变化,获取对应的标签和美甲师列表
watch(() => formState.shopId, (newShopId) => {
if (newShopId) {
fetchTags(newShopId)
fetchArtists(newShopId)
fetchCoupons(newShopId)
} else {
tags.value = []
artists.value = []
coupons.value = []
formState.availableCoupons = []
}
})
</script>
<style scoped>
.products {
padding: 0;
}
.product-images {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 4px;
}
.product-images :deep(.ant-image) {
border-radius: 4px;
}
.upload-tip {
color: var(--text-secondary);
font-size: 12px;
line-height: 1.6;
margin-top: 8px;
}
.upload-pending-tip {
color: #fa8c16;
font-size: 12px;
line-height: 1.6;
margin-top: 6px;
}
.coupon-actions {
margin-top: 6px;
}
</style>