Files
gao-customer-h5/src/pages/recycle/RecycleRuleEdit.vue
T
2026-11-12 16:51:57 +08:00

486 lines
14 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="tui-page-layout tui-navbar">
<t-navbar
fixed
:z-index="20"
:title="isCreate ? '新增兑换模板' : '编辑兑换模板'"
left-arrow
@left-click="exit()"
>
<template #right>
<t-button
:loading="saving"
theme="primary"
variant="text"
size="small"
content="保存"
@click="save()"
/>
</template>
</t-navbar>
<main class="tui-page-content scroll column">
<div v-can="permissionCodes.recycleExchange.configManage" class="recycle-rule-edit">
<t-form class="form card" label-width="7rem" v-entrance-transition>
<t-form-item label="回收物" required-mark arrow content-align="right" @click="itemPickerVisible = true">
<span v-text="recycleItemName || '请选择'" />
</t-form-item>
<t-form-item label="单份回收数量" required-mark>
<div class="quantity">
<t-input
v-model.trim="recycleQuantityText"
type="number"
align="right"
borderless
:placeholder="`按${recycleUnitName || '回收单位'}填写`"
/>
<span class="unit" v-text="recycleUnitName" />
</div>
</t-form-item>
<t-form-item v-if="itemRows.length" class="detail" label-width="0">
<t-form class="items" label-width="0">
<t-form-item v-for="(row, index) in itemRows" :key="row.key" class="item">
<div class="item-content">
<div class="photo">
<t-image v-if="row.sku && getProductPhotoURL(row.sku)" :src="getProductPhotoURL(row.sku)" :alt="row.productName || '产品图片'" fit="cover" class="avatar" />
<div v-else class="avatar fallback" v-text="(row.productName || '产').slice(0, 1)" />
</div>
<div class="main">
<div class="head">
<div class="title">
<strong class="name clip-text" v-text="row.productName || '未命名产品'" />
<product-sku-tags :product-name="row.productName" :fallback="row.skuText" />
</div>
<t-button
size="extra-small"
theme="danger"
variant="text"
content="移除"
@click="removeItem(index)"
/>
</div>
<div class="quantity">
<t-stepper
:model-value="Number(row.exchangeQuantityText) || 0"
size="large"
theme="outline"
:min="0"
:max="Number.MAX_SAFE_INTEGER"
:step="getProductQuantityStep({ allowDecimalQuantity: row.allowDecimalQuantity })"
:integer="!row.allowDecimalQuantity"
@update:model-value="row.exchangeQuantityText = String($event)"
/>
<t-tag :content="row.unitName || '单位'" />
</div>
</div>
</div>
</t-form-item>
</t-form>
</t-form-item>
<t-form-item arrow content-align="right" @click="openProductPicker">
<span>添加商品</span>
</t-form-item>
<t-form-item label="状态" content-align="right">
<t-switch v-model="form.status" size="small" :custom-value="['ACTIVE', 'INACTIVE']" />
</t-form-item>
<t-form-item label="备注">
<t-textarea v-model="form.remark" borderless autosize maxlength="500" placeholder="选填" />
</t-form-item>
<t-form-item label-width="0">
<span class="tips" v-text="footerTipText" />
</t-form-item>
</t-form>
</div>
</main>
<recycle-item-picker-popup
v-model:visible="itemPickerVisible"
:items="itemList"
:loading="itemLoading"
:selected-id="form.recycleItemId"
empty-text="暂无回收物,可点击右上角新建"
manage
show-status
@select="selectItem"
@saved="reloadItems"
/>
<product-select-popup
v-model="selection"
v-model:visible="productPopupVisible"
@select="handleProductSelection"
/>
</div>
</template>
<script setup lang="ts">
import { useExpandToMaster, usePane } from "timi-tdesign-mobile";
import ProductAPI from "@/api/ProductAPI";
import RecycleAPI from "@/api/RecycleAPI";
import ProductSkuTags from "@/components/ProductSkuTags.vue";
import ProductSelectPopup from "@/components/productSelector/ProductSelectPopup.vue";
import RecycleItemPickerPopup from "@/pages/recycle/components/RecycleItemPickerPopup.vue";
import type { ProductSelection, ProductSku } from "@/types/Product";
import type { ProductSkuSelectionValue } from "@/types/ProductSkuSelection";
import type { RecycleExchangeRule, RecycleItem, RecycleRuleItem, RecycleStatus } from "@/types/Recycle";
import { getErrorMessage } from "@/utils/error";
import { Message } from "@/utils/message";
import { normalizePackageQuantity } from "@/utils/package";
import { permissionCodes } from "@/utils/permission";
import { getProductPhotoURL, getProductQuantityStep, getProductSkuSnapshotText } from "@/utils/product";
defineOptions({ name: "RecycleRuleEdit" });
const props = withDefaults(defineProps<{
/** 指定规则 ID 时忽略路由参数,用于平板主从分栏的内联渲染。 */
ruleId?: string;
}>(), {
ruleId: ""
});
const emit = defineEmits<{
saved: [];
}>();
const route = useRoute();
const router = useRouter();
const currentId = computed(() => props.ruleId || String(route.params.id || ""));
const isCreate = computed(() => !currentId.value);
useExpandToMaster({
path: "/product/recycle-rules",
id: () => currentId.value || "__create__",
query: currentId.value ? { view: "edit" } : {}
});
/** 非空说明当前被内联在主从分栏的右栏里 */
const pane = usePane();
function exit(saved = false): void {
if (pane) {
pane.close(saved);
return;
}
void router.back();
}
// ---------- 表单 ----------
const form = reactive({
id: "",
recycleItemId: "",
status: "ACTIVE" as RecycleStatus,
sort: undefined as number | undefined,
remark: ""
});
const recycleQuantityText = ref("");
const selection = ref<ProductSkuSelectionValue>();
const productPopupVisible = ref(false);
const itemPickerVisible = ref(false);
const itemList = ref<RecycleItem[]>([]);
const itemLoading = ref(false);
const selectedItem = ref<RecycleItem>();
const saving = ref(false);
const recycleItemName = computed(() => selectedItem.value?.name || "");
const recycleUnitName = computed(() => selectedItem.value?.unitName || "");
const footerTipText = "启用模板要求回收物、产品和 SKU 均已启用,且所选业务单位允许销售。模板只是开单快捷配置,修改或删除都不影响已创建的兑换单。";
// ---------- 商品明细 ----------
/** 明细行的编辑态。key 用于 v-for 稳定,不提交给服务端。 */
type ItemRow = {
key: number;
skuId: string;
skuUnitId: string;
productName: string;
skuText: string;
unitName: string;
sku?: ProductSku;
allowDecimalQuantity: boolean;
exchangeQuantityText: string;
};
const itemRows = ref<ItemRow[]>([]);
let rowSeed = 0;
function createRow(source: Partial<RecycleRuleItem> & { productName?: string | null; unitName?: string | null }): ItemRow {
rowSeed += 1;
return {
key: rowSeed,
skuId: source.skuId || "",
skuUnitId: source.skuUnitId || "",
productName: source.productName || "",
skuText: getProductSkuSnapshotText(source.productName, source.skuName, source.specSummary),
unitName: source.unitName || "",
allowDecimalQuantity: source.allowDecimalQuantity ?? false,
exchangeQuantityText: source.exchangeQuantity === undefined || source.exchangeQuantity === null ? "" : String(source.exchangeQuantity)
};
}
/** 同款 SKU 换单位是允许的,只有「同 SKU + 同单位」才算重复。 */
function isDuplicate(skuId: string, skuUnitId: string, ignoreIndex = -1): boolean {
return itemRows.value.some((row, index) => index !== ignoreIndex && row.skuId === skuId && row.skuUnitId === skuUnitId);
}
function openProductPicker(): void {
productPopupVisible.value = true;
}
function handleProductSelection(value: ProductSelection): void {
const skuId = value.sku.id || "";
const skuUnitId = value.unit.id || "";
if (isDuplicate(skuId, skuUnitId)) {
Message.warning("该商品的这个单位已在模板中");
return;
}
const row = createRow({
skuId,
skuUnitId,
productName: value.product.name,
skuName: value.sku.name,
specSummary: value.sku.specSummary,
unitName: value.unit.name,
allowDecimalQuantity: value.sku.allowDecimalQuantity,
exchangeQuantity: ""
});
row.sku = value.sku;
itemRows.value.push(row);
}
function removeItem(index: number): void {
itemRows.value.splice(index, 1);
}
/** 补充详情接口未返回的 SKU 图片,同一 SKU 只请求一次。 */
async function loadRowSkus(rows: ItemRow[]): Promise<void> {
const ids = [...new Set(rows.map(row => row.skuId).filter(Boolean))];
const results = await Promise.allSettled(ids.map(async id => await ProductAPI.skuDetail(id)));
results.forEach((result, index) => {
if (result.status !== "fulfilled") {
return;
}
for (const row of rows) {
if (row.skuId === ids[index]) {
row.sku = result.value;
row.allowDecimalQuantity = result.value.allowDecimalQuantity;
}
}
});
}
// ---------- 回收物 ----------
function selectItem(item: RecycleItem): void {
form.recycleItemId = item.id || "";
selectedItem.value = item;
itemPickerVisible.value = false;
}
/** 回收物新建或改名后重新取列表,已选中的回收物同步最新名称 */
async function reloadItems(): Promise<void> {
await loadItems();
selectedItem.value = itemList.value.find(item => item.id === form.recycleItemId);
}
// ---------- 数据 ----------
/** 回收物数量不多,一次取完供选择;超过一页时继续翻页。 */
async function loadItems(): Promise<void> {
itemLoading.value = true;
const loadedList: RecycleItem[] = [];
let offset = 0;
const limit = 100;
let total = 0;
try {
do {
const page = await RecycleAPI.itemList({ offset, limit });
const rows = page.list || [];
loadedList.push(...rows);
total = page.total || 0;
offset += rows.length;
if (!rows.length) {
break;
}
} while (offset < total);
itemList.value = loadedList;
} finally {
itemLoading.value = false;
}
}
function applyRule(rule: RecycleExchangeRule): void {
form.id = rule.id || "";
form.recycleItemId = rule.recycleItemId || "";
recycleQuantityText.value = String(rule.recycleQuantity ?? "");
form.status = rule.status || "ACTIVE";
form.sort = rule.sort ?? undefined;
form.remark = rule.remark || "";
selectedItem.value = itemList.value.find(item => item.id === rule.recycleItemId);
itemRows.value = (rule.itemList || []).map(source => createRow(source));
}
async function load(): Promise<void> {
const id = currentId.value;
try {
await loadItems();
if (!id) {
return;
}
applyRule(await RecycleAPI.ruleDetail(id));
await loadRowSkus(itemRows.value);
} catch (error) {
Message.error(getErrorMessage(error, "兑换模板加载失败"));
}
}
// ---------- 保存 ----------
async function save(): Promise<void> {
if (saving.value) {
return;
}
const recycleQuantity = normalizePackageQuantity(recycleQuantityText.value);
if (!form.recycleItemId) {
Message.warning("请选择回收物");
return;
}
if (!recycleQuantity || recycleQuantity === "0") {
Message.warning("单份回收数量必须为大于 0 的数字,最多 3 位小数");
return;
}
if (!itemRows.value.length) {
Message.warning("请至少添加一个兑换商品");
return;
}
const itemList: RecycleRuleItem[] = [];
const seen = new Set<string>();
for (const row of itemRows.value) {
const quantity = normalizePackageQuantity(row.exchangeQuantityText);
if (!row.skuId || !row.skuUnitId || !quantity || quantity === "0") {
Message.warning(`请填写「${row.productName || "未命名产品"}」的兑换数量`);
return;
}
const uniqueKey = `${row.skuId}|${row.skuUnitId}`;
if (seen.has(uniqueKey)) {
Message.warning("同一商品和单位不能重复");
return;
}
seen.add(uniqueKey);
itemList.push({ skuId: row.skuId, skuUnitId: row.skuUnitId, exchangeQuantity: quantity });
}
saving.value = true;
try {
await RecycleAPI.ruleSave({
id: form.id || undefined,
recycleItemId: form.recycleItemId,
recycleQuantity,
itemList,
status: form.status,
sort: form.sort,
remark: form.remark || null
});
Message.success("兑换模板已保存");
emit("saved");
exit(true);
} catch (error) {
Message.error(getErrorMessage(error, "兑换模板保存失败"));
} finally {
saving.value = false;
}
}
onMounted(load);
watch(() => [props.ruleId, route.params.id], load);
</script>
<style scoped lang="less">
.recycle-rule-edit {
.form {
.quantity {
gap: .5rem;
width: 100%;
display: flex;
min-width: 0;
align-items: center;
.t-input {
flex: 1;
min-width: 0;
}
.unit {
color: var(--td-text-color-secondary);
flex: 0 0 auto;
font-size: .875rem;
}
}
.detail {
padding: 0;
.items {
--td-button-extra-small-height: 24px;
width: 100%;
margin: 0;
.item-content {
gap: .5rem;
width: 100%;
display: flex;
min-width: 0;
}
.photo .avatar {
width: 3.5rem;
height: 3.5rem;
}
.main {
flex: 1;
display: flex;
min-width: 0;
flex-direction: column;
justify-content: space-between;
}
.quantity {
justify-content: end;
}
.head {
gap: .5rem;
display: flex;
align-items: center;
justify-content: space-between;
}
.title {
gap: .25rem;
display: flex;
min-width: 0;
overflow: hidden;
align-items: center;
.name {
flex: 0 1 auto;
min-width: 0;
}
:deep(.tags) {
flex: 0 0 auto;
flex-wrap: nowrap;
}
}
}
}
.tips {
color: var(--td-text-color-secondary);
font-size: .875rem;
line-height: 1.6;
}
}
}
</style>