Files
shanxia2.0/web-admin/src/views/crm/product/index.vue
T
2026-08-21 16:50:47 +08:00

949 lines
28 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.
<!-- 产品管理 -->
<!-- eslint-disable vue/no-v-model-argument -->
<template>
<div class="page-container">
<section class="panel">
<!-- 筛选区 -->
<div class="filter-block">
<el-form :model="searchForm" class="filter-form" @submit.prevent>
<div class="filter-grid">
<el-form-item label="产品名称">
<el-input
v-model="searchForm.keyword"
placeholder="产品名称/编号/拼音首字母"
clearable
@keyup.enter="handleSearch"
/>
</el-form-item>
<el-form-item label="产品分类">
<el-tree-select
v-model="searchForm.categoryId"
:data="categoryOptions"
:props="{ value: 'id', label: 'categoryName', children: 'children' }"
placeholder="全部"
check-strictly
clearable
/>
</el-form-item>
<el-form-item label="产品状态">
<el-select v-model="searchForm.status" placeholder="全部" clearable>
<el-option
v-for="opt in dictStore.getOptions('crm_product_status')"
:key="opt.value"
:label="opt.label"
:value="opt.value"
/>
</el-select>
</el-form-item>
</div>
<div class="filter-actions-row">
<span class="filter-hint">按产品名称、编号、拼音首字母模糊查询。</span>
<div class="filter-actions-end">
<el-button class="btn-ghost" :loading="loading" @click="handleReset">
<el-icon><RefreshLeft /></el-icon>重置
</el-button>
<el-button class="btn-main" type="primary" :loading="loading" @click="handleSearch">
<el-icon><Search /></el-icon>搜索
</el-button>
</div>
</div>
</el-form>
</div>
<!-- 工具栏 -->
<div class="list-toolbar">
<div class="list-toolbar-row">
<ListQuickSearchInput
v-model="quickSearchKeyword"
placeholder="产品名称/编号/拼音首字母"
@search="handleQuickSearch"
@clear="handleQuickSearchClear"
/>
<el-button class="btn-main" type="primary" @click="handleAdd">
<el-icon><Plus /></el-icon>
新增产品
</el-button>
<el-button
class="btn-ghost"
:disabled="selectedRows.length !== 1"
@click="handleToolbarEdit"
>
<el-icon><Edit /></el-icon>
编辑
</el-button>
<el-button
class="btn-ghost"
type="danger"
:disabled="selectedRows.length === 0 || !allRowsDeletableByCreator(selectedRows)"
:title="allRowsDeletableByCreator(selectedRows) ? '' : CREATOR_DELETE_TIP"
@click="handleDelete()"
>
<el-icon><Delete /></el-icon>
删除
</el-button>
<el-button
class="btn-ghost"
:disabled="selectedRows.length === 0"
@click="handleBatchStatus('on')"
>
<el-icon><Top /></el-icon>
批量上架
</el-button>
<el-button
class="btn-ghost"
:disabled="selectedRows.length === 0"
@click="handleBatchStatus('off')"
>
<el-icon><Bottom /></el-icon>
批量下架
</el-button>
<el-button class="btn-ghost" @click="handleImport">
<el-icon><Upload /></el-icon>
导入
</el-button>
<el-button class="btn-ghost" @click="handleExport">
<el-icon><Download /></el-icon>
导出
</el-button>
<el-button class="btn-ghost" @click="categoryMaintainVisible = true">
<el-icon><Folder /></el-icon>
产品分类
</el-button>
<ListToolbarEndActions
:loading="loading"
:column-defs="listColumnDefs"
v-model:visible-columns="visibleColumns"
v-model:check-all="checkAll"
:is-indeterminate="isIndeterminate"
@refresh="getList"
@reset-columns="resetToDefault"
/>
</div>
</div>
<!-- 数据表格 -->
<div class="list-body list-wrap">
<ListTable
table-key="crm-product"
class="list-table"
:data="productList"
v-loading="loading"
stripe
row-key="id"
@selection-change="handleSelectionChange"
@row-dblclick="handleView"
>
<el-table-column type="selection" min-width="55" align="center" header-align="center" />
<el-table-column
type="index"
label="序号"
min-width="68"
align="center"
header-align="center"
:index="(index) => (pagination.page - 1) * pagination.pageSize + index + 1"
/>
<el-table-column
v-if="isColumnVisible('productNo')"
prop="productNo"
label="产品编号"
min-width="130"
align="center"
header-align="center"
show-overflow-tooltip
/>
<el-table-column
prop="productName"
label="产品名称"
min-width="240"
align="left"
header-align="left"
class-name="col-name-wrap"
label-class-name="col-name-wrap"
>
<template #default="{ row }">
<div class="product-name-cell">
<el-link type="primary" @click="handleView(row)">{{ row.productName }}</el-link>
<el-tag
v-if="Number(row.isToxic) === 1"
type="danger"
size="small"
class="product-hazard-tag"
>
毒
</el-tag>
<el-tag
v-if="Number(row.isExplosive) === 1"
type="danger"
size="small"
class="product-hazard-tag"
>
爆
</el-tag>
</div>
</template>
</el-table-column>
<el-table-column
v-if="isColumnVisible('categoryName')"
prop="categoryName"
label="产品分类"
min-width="120"
align="center"
header-align="center"
show-overflow-tooltip
/>
<el-table-column
v-if="isColumnVisible('brands')"
label="品牌"
min-width="140"
align="center"
header-align="center"
show-overflow-tooltip
>
<template #default="{ row }">
{{ formatProductBrands(row.brands) }}
</template>
</el-table-column>
<el-table-column
v-if="isColumnVisible('aliases')"
label="别名"
min-width="140"
align="center"
header-align="center"
show-overflow-tooltip
>
<template #default="{ row }">
{{ formatProductAliases(row.aliases) }}
</template>
</el-table-column>
<el-table-column
v-if="isColumnVisible('model')"
prop="model"
label="规格型号"
min-width="120"
align="center"
header-align="center"
show-overflow-tooltip
/>
<el-table-column
v-if="isColumnVisible('price')"
prop="price"
label="标准价(元)"
min-width="120"
align="right"
header-align="right"
>
<template #default="{ row }">
<span class="money-display">{{ formatProductPrice(row.price) }}</span>
</template>
</el-table-column>
<el-table-column
v-if="isColumnVisible('cost')"
prop="cost"
label="成本价(元)"
min-width="120"
align="right"
header-align="right"
>
<template #default="{ row }">
<span class="money-display">{{ formatProductPrice(row.costPrice ?? row.cost) }}</span>
</template>
</el-table-column>
<el-table-column
v-if="isColumnVisible('status')"
prop="status"
label="状态"
min-width="80"
align="center"
header-align="center"
>
<template #default="{ row }">
<el-tag :type="dictStore.getTagType('crm_product_status', row.status)" size="small">
{{ dictStore.getLabel('crm_product_status', row.status) }}
</el-tag>
</template>
</el-table-column>
</ListTable>
</div>
<!-- 分页 -->
<div class="pagination list-pager-bar">
<div class="list-pager-selected">
已选 <span class="sel-num">{{ selectedRows.length }}</span> 项
</div>
<el-pagination
v-model:current-page="pagination.page"
v-model:page-size="pagination.pageSize"
:page-sizes="[10, 20, 100, 500]"
layout="total, sizes, prev, pager, next, jumper"
:total="pagination.total"
@size-change="handlePageSizeChange"
@current-change="handlePageChange"
/>
</div>
<ProductFormDialog
v-model="formDialogVisible"
:product-id="formProductId"
@success="handleFormSuccess"
/>
<ProductCategoryMaintainDialog
v-model="categoryMaintainVisible"
@closed="handleCategoryMaintainClosed"
/>
<!-- 详情弹窗 -->
<SystemViewDialog
v-model:visible="detailDialogVisible"
dialog-class="crm-product-view-dialog"
:title="detailData?.productName || '产品详情'"
:icon="Box"
:code="detailData?.productNo"
code-label="产品编号"
:sections="productViewSections"
dense
width="1040px"
modal-class="order-module-dialog-mask"
append-to-body
>
<template #hero-actions>
<div class="product-view-hero-actions">
<el-button class="btn-main" type="primary" @click="handleDetailEdit">
<el-icon><Edit /></el-icon>编辑
</el-button>
<el-button
class="btn-ghost"
type="danger"
:disabled="!canDeleteByCreator(detailData)"
:title="canDeleteByCreator(detailData) ? '' : CREATOR_DELETE_TIP"
@click="handleDetailDelete"
>
<el-icon><Delete /></el-icon>删除
</el-button>
</div>
</template>
<template #images>
<div v-if="productImageList.length" class="product-images">
<ImagePreview
v-for="(img, index) in productImageList"
:key="`${img}-${index}`"
:src="img"
:width="48"
:height="48"
/>
</div>
<p v-else class="view-empty-hint">暂无图片</p>
</template>
</SystemViewDialog>
<!-- 导入弹窗 -->
<el-dialog
v-model="importDialogVisible"
title="产品导入"
width="500px"
class="dialog-form-layout"
align-center
destroy-on-close
:close-on-click-modal="false"
>
<el-form label-position="right" label-width="100px" class="crm-dialog-form">
<el-form-item label="导入模板">
<el-button type="primary" @click="downloadTemplate">
<el-icon><Download /></el-icon>下载模板
</el-button>
</el-form-item>
<el-form-item label="选择文件">
<el-upload
ref="importUploadRef"
:auto-upload="false"
:limit="1"
accept=".xlsx,.xls"
:on-change="handleImportFileChange"
:file-list="importFileList"
>
<template #trigger>
<el-button
><el-icon><Upload /></el-icon>选择文件</el-button
>
</template>
<template #tip>
<div class="el-upload__tip">只能上传 .xlsx/.xls 文件</div>
</template>
</el-upload>
</el-form-item>
</el-form>
<template #footer>
<el-button class="btn-ghost" @click="importDialogVisible = false">
<el-icon><Close /></el-icon>取消
</el-button>
<el-button class="btn-main" type="primary" :loading="importLoading" @click="submitImport">
<el-icon><Check /></el-icon>确定
</el-button>
</template>
</el-dialog>
</section>
</div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadFile } from 'element-plus'
import {
Plus,
Edit,
Delete,
Close,
Check,
Search,
RefreshLeft,
Download,
Upload,
Top,
Bottom,
Box,
Folder
} from '@element-plus/icons-vue'
import SystemViewDialog, {
type ViewField,
type ViewSection
} from '@/components/business/system-view-dialog/index.vue'
import ProductFormDialog from '@/components/business/product-form-dialog/index.vue'
import ProductCategoryMaintainDialog from '@/components/business/product-category-maintain-dialog/index.vue'
import { crmDictField, crmField, crmLongField, crmTagField } from '@/utils/crm/view-fields'
import { useDictStore } from '@/store/modules/dict'
import { formatMoneyDisplay } from '@/utils/money-format'
import {
canDeleteByCreator,
filterDeletableByCreator,
allRowsDeletableByCreator,
CREATOR_DELETE_TIP
} from '@/utils/creator-delete'
import ListToolbarEndActions from '@/components/business/list-toolbar-end-actions/index.vue'
import ListQuickSearchInput from '@/components/business/list-quick-search-input/index.vue'
import { usePersistedListColumns } from '@/composables/usePersistedListColumns'
import {
fetchCategoryTree,
fetchProductList,
fetchProductDetail,
fetchDeleteProduct,
fetchUpdateProductStatus,
fetchImportProducts,
fetchExportProducts,
fetchImportTemplate,
type ProductBrandItem,
type ProductAliasItem
} from '@/api/crm/product'
const dictStore = useDictStore()
function getHazardFlagTagType(value: unknown) {
if (Number(value) !== 1) return 'info'
return 'danger'
}
function formatProductPrice(value: unknown) {
if (value === null || value === undefined || value === '') return '-'
const num = Number(value)
if (Number.isNaN(num) || num === 0) return '-'
return `¥${formatMoneyDisplay(num)}`
}
function formatProductBrands(brands?: ProductBrandItem[]) {
if (!brands?.length) return '-'
const names = brands.map((b) => b.brandName).filter(Boolean)
return names.length ? names.join('、') : '-'
}
function formatProductAliases(aliases?: ProductAliasItem[]) {
if (!aliases?.length) return '-'
const names = aliases.map((a) => a.aliasName).filter(Boolean)
return names.length ? names.join('、') : '-'
}
const productList = ref<any[]>([])
const categoryOptions = ref<any[]>([])
const loading = ref(false)
const categoryMaintainVisible = ref(false)
const listColumnDefs = [
{ prop: 'productNo', label: '产品编号' },
{ prop: 'categoryName', label: '产品分类' },
{ prop: 'brands', label: '品牌' },
{ prop: 'aliases', label: '别名' },
{ prop: 'model', label: '规格型号' },
{ prop: 'price', label: '标准价(元)' },
{ prop: 'cost', label: '成本价(元)', defaultVisible: false },
{ prop: 'status', label: '状态' }
]
const { visibleColumns, checkAll, isIndeterminate, isColumnVisible, resetToDefault } =
usePersistedListColumns('crm-product-list-columns-v2', listColumnDefs)
const selectedRows = ref<any[]>([])
const pagination = reactive({ page: 1, pageSize: 20, total: 0 })
const searchForm = reactive({
keyword: '',
categoryId: '',
status: 'on'
})
const quickSearchKeyword = ref('')
const formDialogVisible = ref(false)
const formProductId = ref<string | null>(null)
const detailDialogVisible = ref(false)
const detailData = ref<any>(null)
const productImageList = computed(() => {
const images = detailData.value?.images
if (!images) return []
return String(images).split(',').filter(Boolean)
})
const productViewSections = computed<ViewSection[]>(() => {
const d = detailData.value
if (!d) return []
const fields: ViewField[] = [
crmDictField('状态', 'crm_product_status', d.status, dictStore),
crmField('拼音首字母', d.namePinyinAbbr),
crmField('产品分类', d.categoryName),
crmField('品牌', formatProductBrands(d.brands)),
crmField('别名', formatProductAliases(d.aliases)),
crmField('规格型号', d.model),
crmField('条码', d.barcode),
crmField('销售次数', d.saleCount ?? 0),
crmField('税率', `${d.taxRate ?? 13}%`),
crmTagField(
'是否易制毒',
Number(d.isToxic) === 1 ? '毒' : '否',
getHazardFlagTagType(d.isToxic)
),
crmTagField(
'是否易制爆',
Number(d.isExplosive) === 1 ? '爆' : '否',
getHazardFlagTagType(d.isExplosive)
),
crmField('创建时间', d.createTime, { long: false })
]
if (d.description) fields.push(crmLongField('产品描述', d.description, { fullSpan: true }))
if (d.remark) fields.push(crmLongField('备注', d.remark, { fullSpan: true }))
return [
{
title: '基本信息',
hideTitleInDense: true,
fieldLayout: 'table',
tableMode: 'quad',
fields
},
{
title: '产品图片',
titleStyle: 'field',
fields: [],
slot: 'images'
}
]
})
const importDialogVisible = ref(false)
const importLoading = ref(false)
const importUploadRef = ref()
const importFileList = ref<UploadFile[]>([])
async function getList() {
loading.value = true
try {
const params: Record<string, any> = {
page: pagination.page,
pageSize: pagination.pageSize
}
const quickKeyword = quickSearchKeyword.value?.trim()
if (quickKeyword) {
params.keyword = quickKeyword
} else if (searchForm.keyword) {
params.keyword = searchForm.keyword
}
if (searchForm.categoryId) params.categoryId = searchForm.categoryId
if (searchForm.status) params.status = searchForm.status
const res = await fetchProductList(params)
const data = (res as any)?.data || res || {}
productList.value = data.list || data.rows || []
pagination.total = data.total ?? 0
} finally {
loading.value = false
}
}
async function getCategoryOptions() {
const res = await fetchCategoryTree()
categoryOptions.value = (res as any)?.data || res || []
}
function findCategoryNodeById(tree: any[], id: string): any {
for (const node of tree) {
if (node.id === id) return node
if (node.children?.length) {
const found = findCategoryNodeById(node.children, id)
if (found) return found
}
}
return null
}
async function handleCategoryMaintainClosed() {
await getCategoryOptions()
const selectedId = searchForm.categoryId
if (selectedId && !findCategoryNodeById(categoryOptions.value, selectedId)) {
searchForm.categoryId = ''
pagination.page = 1
await getList()
}
}
function handleSearch() {
quickSearchKeyword.value = ''
pagination.page = 1
getList()
}
function handlePageSizeChange() {
pagination.page = 1
getList()
}
function handlePageChange() {
getList()
}
function handleReset() {
searchForm.keyword = ''
searchForm.categoryId = ''
searchForm.status = 'on'
quickSearchKeyword.value = ''
pagination.page = 1
getList()
}
function handleQuickSearch() {
pagination.page = 1
getList()
}
function handleQuickSearchClear() {
quickSearchKeyword.value = ''
pagination.page = 1
getList()
}
function handleSelectionChange(rows: any[]) {
selectedRows.value = rows
}
function handleAdd() {
formProductId.value = null
formDialogVisible.value = true
}
function handleToolbarEdit() {
if (selectedRows.value.length !== 1) {
ElMessage.warning('请选择一条数据进行编辑')
return
}
handleUpdate(selectedRows.value[0])
}
async function handleDetailEdit() {
if (!detailData.value) return
handleUpdate(detailData.value)
}
async function handleDetailDelete() {
if (!detailData.value) return
await handleDelete(detailData.value)
detailDialogVisible.value = false
}
function handleUpdate(row: any) {
formProductId.value = row?.id ? String(row.id) : null
formDialogVisible.value = true
}
async function handleFormSuccess(product: Record<string, any>) {
await getList()
const id = product?.id || formProductId.value
if (detailDialogVisible.value && id) {
const res = await fetchProductDetail({ id: String(id) })
detailData.value = (res as any)?.data || res || null
}
}
async function handleView(row: any) {
const res = await fetchProductDetail({ id: row.id })
detailData.value = (res as any)?.data || res || null
detailDialogVisible.value = true
}
async function handleDelete(row?: any) {
if (!row && selectedRows.value.length === 0) {
ElMessage.warning('请至少选择一条数据进行删除')
return
}
const targets = row ? [row] : selectedRows.value
const deletable = filterDeletableByCreator(targets)
if (!deletable.length) {
ElMessage.warning(CREATOR_DELETE_TIP)
return
}
if (deletable.length < targets.length) {
ElMessage.warning(CREATOR_DELETE_TIP)
return
}
await ElMessageBox.confirm('是否确认删除选中的产品?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
})
if (row?.id) {
await fetchDeleteProduct({ id: row.id })
} else {
await fetchDeleteProduct({ ids: selectedRows.value.map((r) => r.id) })
}
ElMessage.success('删除成功')
await getList()
}
async function handleBatchStatus(status: string) {
if (selectedRows.value.length === 0) {
ElMessage.warning('请至少选择一条数据进行操作')
return
}
const label = status === 'on' ? '上架' : '下架'
await ElMessageBox.confirm(`是否确认批量${label}选中的产品?`, '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
})
await fetchUpdateProductStatus({
ids: selectedRows.value.map((r) => r.id),
status
})
ElMessage.success(`批量${label}成功`)
await getList()
}
function handleImport() {
importFileList.value = []
importDialogVisible.value = true
}
function handleImportFileChange(file: UploadFile) {
importFileList.value = [file]
}
async function submitImport() {
if (importFileList.value.length === 0) {
ElMessage.warning('请选择要导入的文件')
return
}
const file = importFileList.value[0]
if (!file.raw) return
importLoading.value = true
try {
await fetchImportProducts(file.raw)
ElMessage.success('导入成功')
importDialogVisible.value = false
await getList()
} finally {
importLoading.value = false
}
}
async function downloadTemplate() {
try {
const res = await fetchImportTemplate()
const blob = new Blob([res as any], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
})
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = '产品导入模板.xlsx'
link.click()
URL.revokeObjectURL(url)
} catch {
ElMessage.error('下载模板失败')
}
}
async function handleExport() {
try {
const params: Record<string, any> = {}
const quickKeyword = quickSearchKeyword.value?.trim()
if (quickKeyword) {
params.keyword = quickKeyword
} else if (searchForm.keyword) {
params.keyword = searchForm.keyword
}
if (searchForm.categoryId) params.categoryId = searchForm.categoryId
if (searchForm.status) params.status = searchForm.status
const res = await fetchExportProducts(params)
const blob = new Blob([res as any], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
})
const url = URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = url
link.download = `产品列表_${new Date().getTime()}.xlsx`
link.click()
URL.revokeObjectURL(url)
} catch {
ElMessage.error('导出失败')
}
}
watchDebounced(
searchForm,
() => {
quickSearchKeyword.value = ''
pagination.page = 1
getList()
},
{ debounce: 300, deep: true }
)
onMounted(() => {
getCategoryOptions()
getList()
})
</script>
<style scoped lang="scss">
.product-name-cell {
display: inline-flex;
align-items: center;
justify-content: flex-start;
flex-wrap: wrap;
gap: 6px;
max-width: 100%;
}
.product-name-cell .el-link {
max-width: 100%;
white-space: normal;
word-break: break-word;
overflow-wrap: anywhere;
}
.product-hazard-tag {
flex-shrink: 0;
}
.product-images {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.product-view-hero-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: flex-end;
gap: 8px;
}
</style>
<style lang="scss">
/* 产品查看弹窗:顶部栏背景 + 信息区样式(append-to-body 须非 scoped) */
.crm-product-view-dialog.system-view-dialog--dense,
.el-dialog.crm-product-view-dialog.system-view-dialog--dense {
.view-hero {
padding: 14px 16px 12px;
background: linear-gradient(135deg, #ecfdf5 0%, #f0fdf9 50%, #f8fafc 100%) !important;
border-bottom: 1px solid #d9e8e2;
}
.view-hero-main h2 {
font-size: 17px;
font-weight: 700;
color: #0f172a;
letter-spacing: -0.01em;
}
.view-hero-meta {
font-size: 12px;
color: #64748b;
}
.view-dense-body {
padding: 16px 16px 14px;
background: #fff;
}
.view-kv-table-wrap {
border-color: #eef4f1;
border-radius: 8px;
}
.view-kv-table th {
background: #f8fafc;
}
.view-kv-table tr.row-long td {
font-weight: 400;
color: #475569;
line-height: 1.55;
}
.view-dense-body .view-field-label {
margin: 16px 0 10px;
padding-left: 8px;
border-left: 2px solid #10b981;
font-size: 13px;
font-weight: 600;
color: #475569;
line-height: 1.4;
}
.view-dense-body .view-section:first-child .view-field-label {
margin-top: 0;
}
.product-images {
padding: 10px 12px;
gap: 10px;
background: #f8fafc;
border: 1px solid #eef4f1;
border-radius: 8px;
}
.product-images .el-image {
border-radius: 6px;
border: 1px solid #d9e8e2;
overflow: hidden;
transition: box-shadow 0.15s ease;
}
.product-images .el-image:hover {
box-shadow: 0 2px 8px rgba(16, 185, 129, 0.15);
}
.view-section-slot .view-empty-hint {
margin: 0;
padding: 10px 12px;
font-size: 12px;
color: #94a3b8;
background: #f8fafc;
border: 1px dashed #dcefe8;
border-radius: 8px;
text-align: center;
}
}
</style>