538 lines
15 KiB
Vue
538 lines
15 KiB
Vue
<template>
|
|
<div class="tui-page-layout tui-navbar product-list">
|
|
<t-navbar
|
|
fixed
|
|
:z-index="20"
|
|
title="产品库"
|
|
left-arrow
|
|
@left-click="$router.back()"
|
|
>
|
|
<template #right>
|
|
<t-button
|
|
v-if="route.name === 'ProductList' && canCreate"
|
|
theme="primary"
|
|
variant="text"
|
|
size="small"
|
|
content="新增"
|
|
@click="toCreate"
|
|
/>
|
|
</template>
|
|
</t-navbar>
|
|
<master-detail-page
|
|
ref="productListRef"
|
|
v-can="permissionCodes.product.read"
|
|
class="list"
|
|
:split="isWide"
|
|
:selected="!!selectedId"
|
|
:direction="paneTransitionDirection"
|
|
>
|
|
<template #master>
|
|
<t-pull-down-refresh
|
|
class="pull-refresh"
|
|
v-model="isRefreshing"
|
|
:refresh-timeout="30000"
|
|
@refresh="refresh"
|
|
@scrolltolower="loadMore"
|
|
>
|
|
<div class="filters glass">
|
|
<t-input
|
|
v-model="keyword"
|
|
class="keyword"
|
|
type="search"
|
|
borderless
|
|
placeholder="搜索产品名称(拼音)或编码"
|
|
/>
|
|
<t-dropdown-menu class="menus">
|
|
<t-dropdown-item
|
|
v-model="status"
|
|
label="状态"
|
|
:options="statusOptions"
|
|
@change="selectStatus"
|
|
/>
|
|
<t-dropdown-item
|
|
v-model="productType"
|
|
label="类型"
|
|
:options="productTypeOptions"
|
|
@change="selectProductType"
|
|
/>
|
|
<t-dropdown-item
|
|
:model-value="categoryIdList"
|
|
label="分类"
|
|
:options="categoryOptions"
|
|
multiple
|
|
:options-columns="2"
|
|
@change="selectCategory"
|
|
@confirm="confirmCategory"
|
|
@reset="resetCategory"
|
|
@update:model-value="updateCategory"
|
|
/>
|
|
</t-dropdown-menu>
|
|
</div>
|
|
<t-cell-group
|
|
v-if="productList.length"
|
|
class="list fix-last-cell-line empty-cell-title-margin"
|
|
theme="card"
|
|
>
|
|
<t-cell v-for="item in productList" :key="item.id" class="item" arrow hover v-entrance-transition="{ step: 30 }" @click="toDetail(item)">
|
|
<template #leftIcon>
|
|
<t-image
|
|
v-if="getProductPhotoURL(item)"
|
|
:src="getProductPhotoURL(item)"
|
|
:alt="item.name || '产品图片'"
|
|
fit="cover"
|
|
class="avatar"
|
|
/>
|
|
<div
|
|
v-else
|
|
class="avatar fallback"
|
|
v-text="(item.name || '产').slice(0, 1)"
|
|
/>
|
|
</template>
|
|
<template #title>
|
|
<div class="text-bold" v-text="item.name || '未命名产品'" />
|
|
</template>
|
|
<template #note>
|
|
<t-tag
|
|
size="small"
|
|
variant="outline"
|
|
:theme="getProductStatusTheme(item.status)"
|
|
:content="getProductStatusText(item.status)"
|
|
/>
|
|
</template>
|
|
<template #description>
|
|
<div class="description">
|
|
<t-tag
|
|
size="small"
|
|
variant="outline"
|
|
:content="getProductTypeText(item.productType)"
|
|
/>
|
|
</div>
|
|
</template>
|
|
</t-cell>
|
|
</t-cell-group>
|
|
<center-tips v-else :content="emptyText" />
|
|
<center-tips v-if="productList.length" :content="isLoading ? '正在加载更多' : isNoMore ? '已经到底了' : '上拉加载更多'" />
|
|
</t-pull-down-refresh>
|
|
</template>
|
|
<template #detail>
|
|
<product-sku-detail
|
|
v-if="showingSkuDetail"
|
|
:key="`${skuDetailProductId}-${skuDetailId}`"
|
|
:product-id="skuDetailProductId"
|
|
:sku-id="skuDetailId"
|
|
/>
|
|
<product-edit v-else-if="selectedId === createPaneId" :key="createPaneId" />
|
|
<product-edit
|
|
v-else-if="editing"
|
|
:key="`edit-${selectedId}`"
|
|
:product-id="selectedId"
|
|
/>
|
|
<product-detail
|
|
v-else
|
|
:key="`detail-${selectedId}-${detailVersion}`"
|
|
:product-id="selectedId"
|
|
@edit="openEdit"
|
|
/>
|
|
</template>
|
|
</master-detail-page>
|
|
|
|
</div>
|
|
</template>
|
|
|
|
<script setup lang="ts">
|
|
import { type DropdownValue } from "tdesign-mobile-vue";
|
|
import { MasterDetailPage, useMasterDetailPane, type PaneDirection } from "timi-tdesign-mobile";
|
|
import ProductDetail from "@/pages/product/ProductDetail.vue";
|
|
import ProductEdit from "@/pages/product/ProductEdit.vue";
|
|
import ProductSkuDetail from "@/pages/product/ProductSkuDetail.vue";
|
|
import { useUserStore } from "timi-web-api";
|
|
import { onBeforeRouteLeave } from "vue-router";
|
|
import ProductAPI from "@/api/ProductAPI";
|
|
import type { Product, ProductCategory, ProductStatus, ProductType } from "@/types/Product";
|
|
import { getErrorMessage } from "@/utils/error";
|
|
import { getProductPhotoURL, getProductStatusText, getProductStatusTheme, getProductTypeText } from "@/utils/product";
|
|
import { events, isCurrentStoreEvent, listDataEventKeys, type ListDataChangedPayload } from "@/utils/listDataEvents";
|
|
import { Message } from "@/utils/message";
|
|
import { permissionCodes } from "@/utils/permission";
|
|
|
|
defineOptions({ name: "ProductList" });
|
|
|
|
|
|
const router = useRouter();
|
|
const route = useRoute();
|
|
|
|
// 选中项、编辑态、切换方向、关闭逻辑、转屏、query 同步都在这里
|
|
const createPaneId = "__create__";
|
|
const { selectedId, editing, detailVersion, paneDirection, isWide, openDetail, openEdit } =
|
|
useMasterDetailPane({
|
|
path: "/product/products",
|
|
detail: id => id === createPaneId ? "/product/products/create" : `/product/products/${id}`,
|
|
edit: id => `/product/products/${id}/edit`
|
|
});
|
|
const skuDetailProductId = computed(() => String(route.query.skuProductId || ""));
|
|
const skuDetailId = computed(() => String(route.query.skuId || ""));
|
|
const showingSkuDetail = computed(() => !!skuDetailId.value && skuDetailProductId.value === selectedId.value);
|
|
const paneTransitionDirection = ref<PaneDirection>(paneDirection.value || "forward");
|
|
|
|
watch(paneDirection, direction => {
|
|
if (direction) {
|
|
paneTransitionDirection.value = direction;
|
|
}
|
|
});
|
|
|
|
watch([skuDetailProductId, skuDetailId], ([productId, skuId], [previousProductId, previousSkuId]) => {
|
|
const wasSkuDetail = !!previousSkuId && previousProductId === selectedId.value;
|
|
const isSkuDetail = !!skuId && productId === selectedId.value;
|
|
if (!wasSkuDetail && isSkuDetail) {
|
|
paneTransitionDirection.value = "forward";
|
|
} else if (wasSkuDetail && !isSkuDetail) {
|
|
paneTransitionDirection.value = "back";
|
|
} else if (wasSkuDetail && isSkuDetail && previousSkuId !== skuId) {
|
|
paneTransitionDirection.value = "none";
|
|
}
|
|
});
|
|
const productListRef = ref<ComponentPublicInstance | null>(null);
|
|
const userStore = useUserStore();
|
|
const canCreate = computed(() => userStore.hasPermissions(permissionCodes.product.create));
|
|
|
|
const keyword = ref("");
|
|
const status = ref("ALL");
|
|
const productType = ref("ALL");
|
|
const categoryIdList = ref<string[]>(["ALL"]);
|
|
const categoryList = ref<ProductCategory[]>([]);
|
|
const productList = ref<Product[]>([]);
|
|
const pageIndex = ref(0);
|
|
const total = ref(0);
|
|
const isLoading = ref(false);
|
|
const isRefreshing = ref(false);
|
|
const isNoMore = ref(false);
|
|
let keywordTimer: number | undefined;
|
|
let requestToken = 0;
|
|
let savedPageScrollTop: number | undefined;
|
|
let eventRefreshPromise: Promise<void> | undefined;
|
|
let hasPendingEventRefresh = false;
|
|
let unregisterProductListEvent: (() => void) | undefined;
|
|
let isDisposed = false;
|
|
|
|
function getProductListPage(): HTMLElement | null {
|
|
return (productListRef.value?.$el as HTMLElement | undefined)?.querySelector<HTMLElement>(".pull-refresh") || null;
|
|
}
|
|
|
|
function savePageScrollPosition(): void {
|
|
const page = getProductListPage();
|
|
if (!page) {
|
|
return;
|
|
}
|
|
|
|
savedPageScrollTop = page.scrollTop;
|
|
}
|
|
|
|
function restorePageScrollPosition(): void {
|
|
if (savedPageScrollTop === undefined) {
|
|
return;
|
|
}
|
|
|
|
const scrollTop = savedPageScrollTop;
|
|
requestAnimationFrame(() => {
|
|
const page = getProductListPage();
|
|
if (!page) {
|
|
return;
|
|
}
|
|
|
|
page.scrollTop = scrollTop;
|
|
savedPageScrollTop = undefined;
|
|
});
|
|
}
|
|
|
|
function syncNavBar(): void {
|
|
|
|
}
|
|
|
|
const statusOptions = [
|
|
{ label: "全部状态", value: "ALL" },
|
|
{ label: "启用", value: "ACTIVE" },
|
|
{ label: "停用", value: "INACTIVE" }
|
|
];
|
|
const productTypeOptions = [
|
|
{ label: "全部类型", value: "ALL" },
|
|
{ label: "服务", value: "SERVICE" },
|
|
{ label: "实物", value: "GOODS" },
|
|
{ label: "消耗品", value: "CONSUMABLE" }
|
|
];
|
|
const categoryOptions = computed(() => [{ label: "全部分类", value: "ALL" }, ...categoryList.value.map(item => ({
|
|
label: item.name || "未命名分类",
|
|
value: item.id || ""
|
|
}))]);
|
|
const emptyText = computed(() => isLoading.value ? "正在加载产品" : keyword.value ? "未找到匹配产品" : "暂无产品");
|
|
|
|
async function loadCategories(): Promise<void> {
|
|
const result = await ProductAPI.categoryList({ index: 0, size: 1000, status: "ACTIVE" });
|
|
categoryList.value = result.list || [];
|
|
}
|
|
|
|
async function fetch(reset = false, preserveScroll = false): Promise<void> {
|
|
if (!reset && (isLoading.value || isNoMore.value)) {
|
|
return;
|
|
}
|
|
const loadedPageCount = reset && preserveScroll ? Math.max(pageIndex.value, 1) : 1;
|
|
const preserveScrollTop = preserveScroll ? getProductListPage()?.scrollTop : undefined;
|
|
if (reset) {
|
|
pageIndex.value = 0;
|
|
total.value = 0;
|
|
isNoMore.value = false;
|
|
if (!preserveScroll) {
|
|
const page = getProductListPage();
|
|
if (page) {
|
|
page.scrollTop = 0;
|
|
}
|
|
}
|
|
}
|
|
const token = ++requestToken;
|
|
isLoading.value = true;
|
|
try {
|
|
const pageSize = 15;
|
|
if (reset && preserveScroll) {
|
|
const nextList: Product[] = [];
|
|
let nextTotal = 0;
|
|
let nextPageIndex = 0;
|
|
for (let index = 0; index < loadedPageCount; index += 1) {
|
|
const result = await ProductAPI.list({
|
|
index,
|
|
size: pageSize,
|
|
keyword: keyword.value || undefined,
|
|
status: status.value === "ALL" ? undefined : status.value as ProductStatus,
|
|
productType: productType.value === "ALL" ? undefined : productType.value as ProductType,
|
|
categoryIdList: categoryIdList.value.includes("ALL") ? undefined : categoryIdList.value
|
|
});
|
|
if (token !== requestToken) {
|
|
return;
|
|
}
|
|
const list = result.list || [];
|
|
nextList.push(...list);
|
|
nextTotal = result.total || 0;
|
|
nextPageIndex += 1;
|
|
if (list.length < pageSize || nextTotal <= nextList.length) {
|
|
break;
|
|
}
|
|
}
|
|
productList.value = nextList;
|
|
total.value = nextTotal;
|
|
pageIndex.value = nextPageIndex;
|
|
isNoMore.value = nextList.length < pageSize || nextList.length === nextTotal || nextTotal < nextList.length;
|
|
} else {
|
|
const result = await ProductAPI.list({
|
|
index: pageIndex.value,
|
|
size: pageSize,
|
|
keyword: keyword.value || undefined,
|
|
status: status.value === "ALL" ? undefined : status.value as ProductStatus,
|
|
productType: productType.value === "ALL" ? undefined : productType.value as ProductType,
|
|
categoryIdList: categoryIdList.value.includes("ALL") ? undefined : categoryIdList.value
|
|
});
|
|
if (token !== requestToken) {
|
|
return;
|
|
}
|
|
const list = result.list || [];
|
|
productList.value = reset ? list : productList.value.concat(list);
|
|
total.value = result.total || 0;
|
|
pageIndex.value += 1;
|
|
isNoMore.value = list.length < pageSize || productList.value.length === total.value || total.value < productList.value.length;
|
|
}
|
|
if (preserveScrollTop !== undefined) {
|
|
requestAnimationFrame(() => {
|
|
const page = getProductListPage();
|
|
if (page) {
|
|
page.scrollTop = preserveScrollTop;
|
|
}
|
|
});
|
|
}
|
|
} finally {
|
|
if (token === requestToken) {
|
|
isLoading.value = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
function startEventRefresh(): void {
|
|
if (isDisposed) {
|
|
return;
|
|
}
|
|
eventRefreshPromise = fetch(true, true)
|
|
.catch(error => Message.error(getErrorMessage(error, "产品列表加载失败")))
|
|
.finally(() => {
|
|
eventRefreshPromise = undefined;
|
|
if (!isDisposed && hasPendingEventRefresh) {
|
|
hasPendingEventRefresh = false;
|
|
startEventRefresh();
|
|
}
|
|
});
|
|
}
|
|
|
|
function requestEventRefresh(payload?: ListDataChangedPayload): void {
|
|
if (!isCurrentStoreEvent(payload)) {
|
|
return;
|
|
}
|
|
if (eventRefreshPromise) {
|
|
hasPendingEventRefresh = true;
|
|
return;
|
|
}
|
|
startEventRefresh();
|
|
}
|
|
|
|
async function refresh(): Promise<void> {
|
|
try {
|
|
await fetch(true);
|
|
} catch (error) {
|
|
Message.error(getErrorMessage(error, "产品列表加载失败"));
|
|
} finally {
|
|
isRefreshing.value = false;
|
|
}
|
|
}
|
|
|
|
async function loadMore(): Promise<void> {
|
|
try {
|
|
await fetch();
|
|
} catch (error) {
|
|
Message.error(getErrorMessage(error, "产品列表加载失败"));
|
|
}
|
|
}
|
|
|
|
async function selectStatus(value: DropdownValue): Promise<void> {
|
|
if (!Array.isArray(value)) {
|
|
status.value = String(value);
|
|
await fetch(true);
|
|
}
|
|
}
|
|
|
|
async function selectProductType(value: DropdownValue): Promise<void> {
|
|
if (!Array.isArray(value)) {
|
|
productType.value = String(value);
|
|
await fetch(true);
|
|
}
|
|
}
|
|
|
|
function getDropdownStringList(value: DropdownValue): string[] {
|
|
const valueList = Array.isArray(value) ? value : [value];
|
|
return valueList
|
|
.filter((item): item is string | number => !Array.isArray(item))
|
|
.map(item => String(item));
|
|
}
|
|
|
|
function normalizeCategoryIdList(value: DropdownValue): string[] {
|
|
const idList = getDropdownStringList(value).filter(Boolean);
|
|
if (!idList.length) {
|
|
return ["ALL"];
|
|
}
|
|
return idList.includes("ALL") && idList.length > 1 ? idList.filter(item => item !== "ALL") : idList;
|
|
}
|
|
|
|
function selectCategory(value: DropdownValue): void {
|
|
categoryIdList.value = normalizeCategoryIdList(value);
|
|
}
|
|
|
|
async function confirmCategory(value: DropdownValue): Promise<void> {
|
|
categoryIdList.value = normalizeCategoryIdList(value);
|
|
await fetch(true);
|
|
}
|
|
|
|
async function resetCategory(): Promise<void> {
|
|
categoryIdList.value = ["ALL"];
|
|
await fetch(true);
|
|
}
|
|
|
|
function updateCategory(value: DropdownValue): void {
|
|
categoryIdList.value = normalizeCategoryIdList(value);
|
|
}
|
|
|
|
async function toCreate(): Promise<void> {
|
|
if (isWide.value && userStore.hasPermissions(permissionCodes.product.read)) {
|
|
openDetail(createPaneId);
|
|
return;
|
|
}
|
|
await router.push("/product/products/create");
|
|
}
|
|
|
|
async function toDetail(item: Product): Promise<void> {
|
|
if (route.query.skuId || route.query.skuProductId) {
|
|
await router.replace({
|
|
path: route.path,
|
|
query: {
|
|
...route.query,
|
|
skuProductId: undefined,
|
|
skuId: undefined
|
|
}
|
|
});
|
|
}
|
|
openDetail(item.id || "");
|
|
}
|
|
|
|
onMounted(async () => {
|
|
unregisterProductListEvent = events.register(listDataEventKeys.productChanged, (payload: ListDataChangedPayload) => requestEventRefresh(payload));
|
|
syncNavBar();
|
|
try {
|
|
await Promise.all([loadCategories(), fetch(true)]);
|
|
} catch (error) {
|
|
Message.error(getErrorMessage(error, "产品列表加载失败"));
|
|
}
|
|
});
|
|
|
|
onActivated(() => {
|
|
restorePageScrollPosition();
|
|
syncNavBar();
|
|
});
|
|
|
|
onDeactivated(() => {
|
|
if (savedPageScrollTop === undefined) {
|
|
savePageScrollPosition();
|
|
}
|
|
});
|
|
|
|
watch(keyword, () => {
|
|
window.clearTimeout(keywordTimer);
|
|
keywordTimer = window.setTimeout(async () => {
|
|
try {
|
|
await fetch(true);
|
|
} catch (error) {
|
|
Message.error(getErrorMessage(error, "产品列表加载失败"));
|
|
}
|
|
}, 300);
|
|
});
|
|
|
|
onBeforeRouteLeave(() => {
|
|
savePageScrollPosition();
|
|
});
|
|
|
|
onUnmounted(() => {
|
|
isDisposed = true;
|
|
unregisterProductListEvent?.();
|
|
unregisterProductListEvent = undefined;
|
|
window.clearTimeout(keywordTimer);
|
|
requestToken += 1;
|
|
});
|
|
</script>
|
|
|
|
<style scoped lang="less">
|
|
.product-list {
|
|
padding: var(--tui-nav-height) 0 1rem;
|
|
|
|
|
|
.list {
|
|
|
|
.item {
|
|
padding: 10px;
|
|
|
|
.avatar {
|
|
width: 3.5rem;
|
|
height: 3.5rem;
|
|
}
|
|
|
|
.description {
|
|
gap: .5rem;
|
|
display: flex;
|
|
align-items: center;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
</style>
|