front/src/views/channel/salesProducts/index.vue
zzh 29d7cbb226 feat: 渠道预报前与销售产品落库前脚本接入 AI 赋值编辑
对齐下单字段白名单,复用中文赋值 DSL 与 AI 写脚本抽屉,方便改写地址/申报/件重尺。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-24 15:10:12 +08:00

8702 lines
287 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.

<script lang="ts" setup>
import {
ref,
shallowRef,
reactive,
computed,
nextTick,
onMounted,
watch,
onBeforeUnmount,
h,
markRaw,
defineAsyncComponent,
} from 'vue';
import {
createSalesProduct,
createSalesProductPrice,
deleteSalesProduct,
deleteSalesProductPrice,
getSalesProductDetail,
getSalesProductList,
getSalesProductAllocation,
getSalesProductPrice,
getSalesProductPriceList,
getSalesProductPublishPriceList,
getSalesProductPublishRecord,
getSalesProductPublishRulesList,
getSalesProductPublishPreview,
getSalesProductPublishSyncStatus,
publishSalesProduct,
rollbackSalesProductPublish,
saveSalesProductAllocation,
saveSalesProductCustomerGuide,
toggleSalesProductPriceStatus,
updateSalesProduct,
updateSalesProductCode,
updateSalesProductPrice,
} from '@/api/channel/salesProduct';
import { getLabelTemplateList } from '@/api/channel/labelTemplate';
import { isDiscountCostItem } from '@/constants/feeCostItems';
import { postForewarningServiceKpiAreaGetKpiAreas } from '@/api/channel/kpiArea';
import { getWarehouseList } from '@/api/system/warehouse';
import { postWeightRuleList } from '@/api/channel/weightRule';
import { postWeightRoundingList } from '@/api/channel/weightRounding';
import { getDictListAll, getDictListByTypes } from '@/api/system/dict';
import { getServiceChannelOptions } from '@/api/channel/serviceChannel';
import {
buildWeightFactorSelectOptions,
canonicalWeightFactorCellForApi,
isWeightPricingFactor,
sortFactorValuesBySize,
weightValueToIntervalCell,
} from '@/utils/priceWeightInterval';
import {
estimateFactorValuesColumnWidth,
resolveVisibleFactorValueCount,
} from '@/utils/factorValueTagPreview';
import { IconPlus, IconDelete, IconSearch, IconEdit, IconDragArrow, IconQuestionCircleFill, IconQuestionCircle, IconSync } from '@arco-design/web-vue/es/icon';
import FormLabelWithPreview from './components/FormLabelWithPreview.vue';
import BillingConditionEditor from './components/BillingConditionEditor.vue';
import PreScriptEditor from '@/views/channel/serviceChannels/components/PreScriptEditor.vue';
import {
PRE_STORAGE_SCRIPT_AI_CHAT_SCENE,
PRE_STORAGE_SCRIPT_AI_DEFAULT_SKILL_KEY,
PRE_STORAGE_SCRIPT_AI_QUICK_PROMPTS,
PRE_STORAGE_SCRIPT_AI_SCENE,
PRE_STORAGE_SCRIPT_AI_STORAGE_KEY,
buildPreStorageScriptAiShortSystemPrompt,
buildPreStorageScriptAiSystemPrompt,
} from './preStorageScriptAiSkill';
import ChannelReferencePreviewModal, {
type ReferencePreviewType,
} from './components/ChannelReferencePreviewModal.vue';
import type { PricePublishAiAdoptPayload } from './components/PricePublishAiAssistDrawer.vue';
import { retryApprovalExecute } from '@/api/system/approval';
import { buildPricePublishAiSkipReport, type PricePublishRiskLevel } from './pricePublishAiSkill';
import { pickResolvedAudit } from '@/utils/auditFields';
import { useUserStore } from '@/store';
import { useRbacUserStore } from '@/store/modules/rbac-user';
import { Message, Modal, Input } from '@arco-design/web-vue';
import ModalPro from '@/components/ModalPro/index.vue';
import useModal from '@/components/ModalPro/useModal';
import CustomLeftMenu from '@/components/CustomLeftMenu/index.vue';
import type { CustomLeftMenuTreeNode } from '@/components/CustomLeftMenu/types';
import { useI18n } from 'vue-i18n';
import {
computeSnapshotDiff,
formatSnapshotJson,
type SnapshotDiffRow,
} from '@/utils/publishSnapshotDiff';
import dayjs from 'dayjs';
import PriceListHotTable, {
type PriceListHotColumn,
} from './components/PriceListHotTable.vue';
import customerGuideTemplate from './customerGuideTemplate.md?raw';
import { isEnableStatusEnabled, toEnableStatus, ENABLE_STATUS } from '@/utils/enableStatus';
const PricePublishAiAssistDrawer = defineAsyncComponent(
() => import('./components/PricePublishAiAssistDrawer.vue'),
);
const BillingSimulateDrawer = defineAsyncComponent(
() => import('./components/BillingSimulateDrawer.vue'),
);
const ApprovalDetailDrawer = defineAsyncComponent(
() => import('@/components/ApprovalDetailDrawer/index.vue'),
);
const PublishDiffPanel = defineAsyncComponent(
() => import('@/components/PublishDiff/index.vue'),
);
const MarkdownDocPanel = defineAsyncComponent(
() => import('@/components/MarkdownDocPanel/index.vue'),
);
defineOptions({
name: 'SalesProducts',
});
const { t } = useI18n();
const userStore = useUserStore();
const rbacUserStore = useRbacUserStore();
const preStorageFallbackPrompt = buildPreStorageScriptAiSystemPrompt();
const preStorageShortPrompt = buildPreStorageScriptAiShortSystemPrompt();
function getPricePublishOperatorName(): string {
return (
rbacUserStore.userInfo?.name?.trim() ||
userStore.name?.trim() ||
rbacUserStore.userInfo?.account?.trim() ||
'—'
);
}
// 搜索关键词
const searchKeyword = ref('');
// 当前选中的产品(初始不选中)
const selectedProduct = ref<number | null>(null);
// 当前激活的标签页
const activeTab = ref('price');
/** 进过的页签保持挂载,切回来不用重新渲染 */
const mountedTabs = reactive({
price: true,
config: false,
rules: false,
records: false,
customerGuide: false,
});
watch(activeTab, (tab) => {
if (tab in mountedTabs) mountedTabs[tab as keyof typeof mountedTabs] = true;
});
const productList = ref<any[]>([]);
async function loadProductList() {
try {
const { items } = await getSalesProductList({
page: 1,
pageSize: 500,
keyword: searchKeyword.value?.trim() || undefined,
});
productList.value = (items || []).map((it: any) => {
const audit = pickResolvedAudit(it);
return {
id: it.id ?? it.Id,
name: it.productName ?? it.ProductName ?? it.name,
isActive: isEnableStatusEnabled(it.isActive ?? it.IsActive),
createTime: audit.createTime,
updateTime: audit.updateTime,
createBy: audit.createBy,
updateBy: audit.updateBy,
creator: audit.updateBy || audit.createBy || '',
raw: it,
};
});
// 有数据但未选中时自动选中首条,以便「产品配置」等 Tab 能展示详情(表单来自 detail 接口,非 list)
if (productList.value.length > 0 && selectedProduct.value == null) {
await handleSelectProduct(productList.value[0]);
}
} catch (e: any) {
Message.error(e?.message || '加载销售产品失败');
productList.value = [];
}
}
// 标签页配置
const tabs = ref([
{ key: 'config', labelKey: 'channel.salesProducts.tabs.config' },
{ key: 'price', labelKey: 'channel.salesProducts.tabs.price' },
{ key: 'rules', labelKey: 'channel.salesProducts.tabs.rules' },
{ key: 'records', labelKey: 'channel.salesProducts.tabs.records' },
{ key: 'customerGuide', labelKey: 'channel.salesProducts.tabs.customerGuide' },
]);
const slidingTabItems = computed(() =>
tabs.value.map((tab) => ({ key: tab.key, label: t(tab.labelKey) }))
);
// 表单数据
const formData = reactive({
productCode: '',
productName: '',
group: '',
minTimeliness: '',
maxTimeliness: '',
tradeTerms: '' as '' | 'DDP' | 'DDU',
routeSort: 0,
customerWaybill: '系统面单',
labelTemplateId: undefined as number | undefined,
blacklistArea: '',
remoteAreaDivision: '',
additionalServices: [] as string[],
weightCalculationRule: '',
weightRounding: '',
productDescription: '',
preStorageScript: '',
});
const customerGuideMarkdown = ref('');
const customerGuideSaving = ref(false);
const customerGuidePanelRef = ref<InstanceType<typeof MarkdownDocPanel> | null>(null);
const savingConfig = ref(false);
const productCodeModalVisible = ref(false);
const productCodeDraft = ref('');
const savingProductCode = ref(false);
function parseAdditionalServiceCodes(raw: unknown): string[] {
if (Array.isArray(raw)) {
return raw.map((x) => String(x ?? '').trim()).filter(Boolean);
}
if (raw == null || raw === '') return [];
const s = String(raw).trim();
if (!s) return [];
try {
const parsed = JSON.parse(s);
if (Array.isArray(parsed)) {
return parsed.map((x) => String(x ?? '').trim()).filter(Boolean);
}
} catch {
/* ignore */
}
return s
.split(/[,,]/)
.map((x) => x.trim())
.filter(Boolean);
}
function serializeAdditionalServices(codes: string[]): string | null {
const normalized = [...new Set(codes.map((c) => String(c ?? '').trim()).filter(Boolean))];
return normalized.length ? JSON.stringify(normalized) : null;
}
type ConfigFormSnapshot = {
productCode: string;
productName: string;
group: string;
minTimeliness: string;
maxTimeliness: string;
tradeTerms: string;
routeSort: number;
customerWaybill: string;
labelTemplateId: number | undefined;
blacklistArea: string;
remoteAreaDivision: string;
additionalServicesKey: string;
weightCalculationRule: string;
weightRounding: string;
productDescription: string;
preStorageScript: string;
};
const configFormBaseline = ref<ConfigFormSnapshot | null>(null);
function snapshotConfigForm(): ConfigFormSnapshot {
return {
productCode: formData.productCode,
productName: formData.productName,
group: formData.group,
minTimeliness: formData.minTimeliness,
maxTimeliness: formData.maxTimeliness,
tradeTerms: formData.tradeTerms,
routeSort: formData.routeSort,
customerWaybill: formData.customerWaybill,
labelTemplateId: formData.labelTemplateId,
blacklistArea: formData.blacklistArea,
remoteAreaDivision: formData.remoteAreaDivision,
additionalServicesKey: [...formData.additionalServices].sort().join(','),
weightCalculationRule: formData.weightCalculationRule,
weightRounding: formData.weightRounding,
productDescription: formData.productDescription,
preStorageScript: formData.preStorageScript,
};
}
function resetConfigFormBaseline() {
configFormBaseline.value = snapshotConfigForm();
}
/** 已保存但尚未发布:允许点「发布」 */
const configPublishPending = ref(false);
const rulesPublishPending = ref(false);
const configFormDirty = computed(() => {
const baseline = configFormBaseline.value;
if (!baseline) return false;
const cur = snapshotConfigForm();
return (Object.keys(baseline) as Array<keyof ConfigFormSnapshot>).some(
(key) => cur[key] !== baseline[key]
);
});
/** 有未保存改动时不可发布,须先保存 */
const canPublishConfig = computed(
() => !configFormDirty.value && configPublishPending.value,
);
/** 产品/渠道代码:仅大写、数字、- */
function normalizeBizCode(value: unknown): string {
return String(value ?? '')
.toUpperCase()
.replace(/[^A-Z0-9-]/g, '');
}
function openProductCodeModal() {
if (selectedProduct.value == null) return;
productCodeDraft.value = normalizeBizCode(formData.productCode);
productCodeModalVisible.value = true;
}
async function handleSaveProductCode() {
const pid = selectedProduct.value;
if (pid == null) return;
const next = normalizeBizCode(productCodeDraft.value);
if (!next) {
Message.warning(t('channel.salesProducts.messages.productCodeRequired'));
return Promise.reject();
}
savingProductCode.value = true;
try {
await updateSalesProductCode({ id: pid, productCode: next });
formData.productCode = next;
const hit = productList.value.find((p: any) => p.id === pid);
if (hit?.raw) {
hit.raw.productCode = next;
hit.raw.ProductCode = next;
}
if (configFormBaseline.value) {
configFormBaseline.value = { ...configFormBaseline.value, productCode: next };
}
productCodeModalVisible.value = false;
Message.success(t('channel.salesProducts.messages.productCodeUpdated'));
} catch (e: any) {
Message.error(e?.message || '修改产品代码失败');
return Promise.reject(e);
} finally {
savingProductCode.value = false;
}
}
const selectedProductContext = computed(() => {
const pid = selectedProduct.value;
if (pid == null) return null;
const product = productList.value.find((p: any) => p.id === pid);
const audit = pickResolvedAudit(product?.raw || product);
const groupLabel =
groupOptions.value.find((o) => o.value === formData.group)?.label ?? formData.group;
return {
productName: formData.productName || product?.name || '-',
productCode: formData.productCode || '-',
groupName: groupLabel || '-',
updateTime: audit.updateTime || '--',
updateBy: audit.updateBy || '--',
};
});
function confirmDiscardUnsavedChanges(): Promise<boolean> {
const dirty =
(activeTab.value === 'config' && configFormDirty.value)
|| (activeTab.value === 'rules' && rulesFormDirty.value);
if (!dirty) return Promise.resolve(true);
return new Promise((resolve) => {
Modal.confirm({
title: t('channel.salesProducts.unsaved.title'),
content: t('channel.salesProducts.unsaved.message'),
okText: t('channel.salesProducts.unsaved.discard'),
cancelText: t('channel.salesProducts.unsaved.stay'),
onOk: () => resolve(true),
onCancel: () => resolve(false),
});
});
}
type IdSelectOption = { label: string; value: string };
// 分组选项:字典 sales_product_group
const SALES_PRODUCT_GROUP_DICT = 'sales_product_group';
const groupOptions = ref<IdSelectOption[]>([]);
function defaultProductGroupValue(): string {
return groupOptions.value[0]?.value ?? '';
}
function resolveProductGroupValue(raw: unknown): string {
const s = String(raw ?? '').trim();
if (!s) return defaultProductGroupValue();
const hit = groupOptions.value.find((o) => o.value === s || o.label === s);
return hit?.value ?? s;
}
async function loadGroupSelectOptions() {
try {
const items = await getDictListAll({ dictType: SALES_PRODUCT_GROUP_DICT });
groupOptions.value = (items || [])
.map((raw: any) => {
const dictCode = String(raw?.dictCode ?? raw?.DictCode ?? '').trim();
const dictName = String(raw?.dictName ?? raw?.DictName ?? '').trim();
if (!dictCode && !dictName) return null;
const dictSort = Number(raw?.dictSort ?? raw?.DictSort ?? 0) || 0;
return {
dictCode: dictCode || dictName,
dictName: dictName || dictCode,
dictSort,
};
})
.filter((row): row is { dictCode: string; dictName: string; dictSort: number } => Boolean(row))
.sort((a, b) => a.dictSort - b.dictSort || String(a.dictCode).localeCompare(String(b.dictCode)))
.map((row) => ({
label: row.dictName || row.dictCode,
value: row.dictCode,
}));
} catch (e: any) {
Message.error(e?.message || '加载产品分组失败');
groupOptions.value = [];
}
}
// 系统面单:真实标签模板下拉
const labelTemplateOptions = ref<{ label: string; value: number }[]>([]);
async function loadLabelTemplateOptions() {
try {
const items = await getLabelTemplateList();
labelTemplateOptions.value = (items || []).map((it) => ({
label: it.name,
value: it.id,
}));
} catch {
labelTemplateOptions.value = [];
}
}
/** 重量因素值:与买价共用(0.5 步进至 30,其后固定 999) */
const weightFactorOptions: IdSelectOption[] = buildWeightFactorSelectOptions();
function filterKpiAreasByType(items: any[], areaType: string) {
const want = areaType.toLowerCase();
return (items || []).filter((item) => {
const t = String(item?.areaType ?? item?.AreaType ?? '').toLowerCase();
return !t || t === want;
});
}
function mapKpiAreasToSelectOptions(items: any[]): IdSelectOption[] {
return (items || []).map((it: any) => {
const id = it.id ?? it.Id;
const name = it.name ?? it.Name ?? String(id ?? '');
return { label: String(name), value: String(id ?? '') };
});
}
/** 保存时把分区下拉的值转为 KPI 分区表主键 id(正整数) */
function toOptionalPositiveId(v: unknown): number | undefined {
if (v === '' || v == null) return undefined;
const n = Number(v);
if (!Number.isFinite(n) || n <= 0) return undefined;
return n;
}
// 黑名单区 / 偏远分区:来自 KPI 分区列表接口(areaType 区分)
const blacklistAreaOptions = ref<IdSelectOption[]>([]);
const remoteAreaDivisionOptions = ref<IdSelectOption[]>([]);
const priceAreaFactorOptions = ref<IdSelectOption[]>([]);
const warehouseFactorOptions = ref<IdSelectOption[]>([]);
let billingFactorSelectOptionsPromise: Promise<void> | null = null;
const billingFactorSelectOptionsLoaded = ref(false);
async function loadKpiAreaSelectOptions() {
try {
const [blRes, rmRes] = await Promise.all([
postForewarningServiceKpiAreaGetKpiAreas({
pageIndex: 1,
pageSize: 500,
areaType: 'blacklist',
}),
postForewarningServiceKpiAreaGetKpiAreas({
pageIndex: 1,
pageSize: 500,
areaType: 'remote',
}),
]);
const blItems =
blRes?.items ?? (blRes as any)?.data?.items ?? [];
const rmItems =
rmRes?.items ?? (rmRes as any)?.data?.items ?? [];
blacklistAreaOptions.value = mapKpiAreasToSelectOptions(
filterKpiAreasByType(blItems, 'blacklist')
);
remoteAreaDivisionOptions.value = mapKpiAreasToSelectOptions(
filterKpiAreasByType(rmItems, 'remote')
);
} catch (e: any) {
Message.error(e?.message || '加载分区列表失败');
blacklistAreaOptions.value = [];
remoteAreaDivisionOptions.value = [];
}
}
// 计重规则 / 计重进位:来自对应列表接口
const weightCalculationRuleOptions = ref<IdSelectOption[]>([]);
const weightRoundingOptions = ref<IdSelectOption[]>([]);
function mapRuleSelectOptions(items: any[]): IdSelectOption[] {
return (items || []).map((it: any) => {
const id = it.id ?? it.Id;
const name = it.name ?? it.Name ?? String(id ?? '');
return { label: String(name), value: String(id ?? '') };
});
}
const referencePreviewRef = ref<InstanceType<typeof ChannelReferencePreviewModal> | null>(null);
function openReferencePreview(
type: ReferencePreviewType,
rawId: string | number | undefined | null,
options: IdSelectOption[]
) {
const id = toOptionalPositiveId(rawId);
if (!id) {
Message.warning(t('channel.salesProducts.referencePreview.noSelection'));
return;
}
void ensureSalesPriceDictLoaded().then(() => {
const hit = options.find((o) => String(o.value) === String(rawId));
const name = hit?.label || String(id);
referencePreviewRef.value?.open({ type, id, name });
});
}
async function loadWeightSelectOptions() {
try {
const [ruleRes, roundingRes] = await Promise.all([
postWeightRuleList({
page: 1,
pageSize: 500,
}),
postWeightRoundingList({
page: 1,
pageSize: 500,
}),
]);
weightCalculationRuleOptions.value = mapRuleSelectOptions(ruleRes?.items ?? []);
weightRoundingOptions.value = mapRuleSelectOptions(roundingRes?.items ?? []);
} catch (e: any) {
Message.error(e?.message || '加载计重规则/进位失败');
weightCalculationRuleOptions.value = [];
weightRoundingOptions.value = [];
}
}
async function loadBillingFactorSelectOptions(force = false) {
if (!force && billingFactorSelectOptionsLoaded.value) return;
if (!force && billingFactorSelectOptionsPromise) {
await billingFactorSelectOptionsPromise;
return;
}
billingFactorSelectOptionsPromise = (async () => {
try {
const [areaRes, warehouseRes] = await Promise.all([
postForewarningServiceKpiAreaGetKpiAreas({
page: 1,
pageSize: 500,
areaType: 'price',
}),
getWarehouseList({
page: 1,
pageSize: 500,
}),
]);
const areaItems = areaRes?.items ?? (areaRes as any)?.data?.items ?? [];
const warehouseItems = warehouseRes?.items ?? [];
priceAreaFactorOptions.value = filterKpiAreasByType(areaItems, 'price').map((it: any) => {
const id = it?.id ?? it?.Id;
const name = String(it?.name ?? it?.Name ?? id ?? '');
return { label: name, value: String(id ?? '') };
});
warehouseFactorOptions.value = warehouseItems.map((it: any) => {
const id = it?.id ?? it?.Id;
const name = String(it?.warehouseName ?? it?.WarehouseName ?? id ?? '');
return { label: name, value: String(id ?? '') };
});
billingFactorSelectOptionsLoaded.value = true;
} catch (e: any) {
Message.error(e?.message || '加载计费因素下拉失败');
priceAreaFactorOptions.value = [];
warehouseFactorOptions.value = [];
billingFactorSelectOptionsLoaded.value = false;
} finally {
billingFactorSelectOptionsPromise = null;
}
})();
await billingFactorSelectOptionsPromise;
}
type NormalizedDictRow = {
dictType: string;
dictCode: string;
dictName: string;
dictSort: number;
};
const salesPriceDictRows = ref<NormalizedDictRow[]>([]);
const salesPriceDictLoading = ref(false);
const salesPriceDictFetched = ref(false);
let salesPriceDictLoadPromise: Promise<void> | null = null;
function normalizeAnyDictRow(raw: any): NormalizedDictRow | null {
const dictType = String(raw?.dictType ?? raw?.DictType ?? '').trim();
if (!dictType) return null;
const dictCode = String(raw?.dictCode ?? raw?.DictCode ?? '').trim();
const dictName = String(raw?.dictName ?? raw?.DictName ?? '').trim();
if (!dictCode && !dictName) return null;
const dictSort = Number(raw?.dictSort ?? raw?.DictSort ?? 0) || 0;
return {
dictType,
dictCode: dictCode || dictName,
dictName: dictName || dictCode,
dictSort,
};
}
function dictRowsOfType(dictType: string): NormalizedDictRow[] {
const want = dictType.toLowerCase();
return salesPriceDictRows.value
.filter((r) => r.dictType.toLowerCase() === want)
.sort((a, b) => a.dictSort - b.dictSort || String(a.dictCode).localeCompare(String(b.dictCode)));
}
function mapDictToSelectOptions(dictType: string): IdSelectOption[] {
return dictRowsOfType(dictType).map((r) => ({
label: r.dictName || r.dictCode,
value: r.dictCode,
}));
}
/** 列表/展示:字典编码 → 字典名称(无匹配则回显原编码) */
function dictLabelByType(dictType: string, code: string | undefined | null): string {
if (code == null || code === '') return '';
const c = String(code).trim();
const want = dictType.toLowerCase();
const hit = salesPriceDictRows.value.find(
(r) => r.dictType.toLowerCase() === want && r.dictCode === c
);
if (hit?.dictName) return hit.dictName;
const byName = salesPriceDictRows.value.find(
(r) => r.dictType.toLowerCase() === want && r.dictName === c
);
return byName?.dictName || c;
}
/** 卖价表格:计费因素编码列表展示 */
function formatPriceTableBillingFactors(row: any): string {
const list = row?.factors;
if (Array.isArray(list) && list.length > 0) {
return list
.map((f: any) => pricingFactorColumnLabel(String(f?.factor ?? f?.name ?? '')))
.filter(Boolean)
.join('+');
}
const legacy = row?.billingFactors;
return typeof legacy === 'string' ? legacy : '';
}
const SALES_PRICE_DICT_TYPES = [
'fee_item',
'cost_unit',
'currency',
'pricing_factor',
'calculation_formula',
'additional_service',
'customer_group',
'cargo_attribute',
] as const;
async function ensureSalesPriceDictLoaded(force = false) {
if (force) {
salesPriceDictFetched.value = false;
salesPriceDictLoadPromise = null;
}
if (salesPriceDictFetched.value) return;
if (salesPriceDictLoadPromise) {
await salesPriceDictLoadPromise;
return;
}
salesPriceDictLoading.value = true;
salesPriceDictLoadPromise = (async () => {
try {
const items = await getDictListByTypes([...SALES_PRICE_DICT_TYPES]);
salesPriceDictRows.value = (items || [])
.map(normalizeAnyDictRow)
.filter(Boolean) as NormalizedDictRow[];
} catch (e: any) {
Message.error(e?.message || '加载字典失败');
salesPriceDictRows.value = [];
} finally {
salesPriceDictFetched.value = true;
salesPriceDictLoading.value = false;
salesPriceDictLoadPromise = null;
}
})();
await salesPriceDictLoadPromise;
}
/** 定价因素编码 → 中文名兜底(字典 dictName 未导入/误写成英文时仍可读) */
const PRICING_FACTOR_LABEL_FALLBACK: Record<string, string> = {
cargo: '货物类型',
zone: '价格分区',
remoteZone: '偏远分区',
weight: '重量',
warehouse: '仓库',
customer: '客户',
};
function pricingFactorColumnLabel(factorValue: string): string {
if (!factorValue) return '';
const key = String(factorValue).trim();
const fallback = PRICING_FACTOR_LABEL_FALLBACK[key];
const hit = dictRowsOfType('pricing_factor').find(
(r) => r.dictCode === key || r.dictName === key,
);
const name = hit?.dictName?.trim() || '';
// 字典名若为空/等于编码/仍是英文编码,优先用中文兜底(避免选中态显示 customer)
if (fallback && (!name || name === hit?.dictCode || PRICING_FACTOR_LABEL_FALLBACK[name])) {
return fallback;
}
if (name) return name;
return fallback || key;
}
function pricingFactorFallbackOption(val: string | number | boolean | Record<string, unknown>) {
const value = typeof val === 'object' && val != null && 'value' in val
? String((val as { value: unknown }).value ?? '')
: String(val ?? '');
return { value, label: pricingFactorColumnLabel(value) };
}
function getPricingFactorMeta(factorKey: string): NormalizedDictRow | undefined {
if (!factorKey) return undefined;
return dictRowsOfType('pricing_factor').find(
(r) => r.dictCode === factorKey || r.dictName === factorKey
);
}
/** 因素值来自字典 cargo_attribute,存/传 dictCode */
function isCargoTypeValueFactor(factorKey: string): boolean {
if (factorKey === '货物类型') return true;
const m = getPricingFactorMeta(factorKey);
return m?.dictCode === 'cargo';
}
/** 因素值来自字典 customer_group,存/传 dictCode(因素下拉存的是 pricing_factor 的 dictCode,如 customer) */
function isCustomerGroupValueFactor(factorKey: string): boolean {
if (!factorKey) return false;
const k = String(factorKey).trim();
if (k === '客户' || k === '客户组' || k === 'customer') return true;
const m = getPricingFactorMeta(k);
return m?.dictCode === 'customer' || m?.dictName === '客户' || m?.dictName === '客户组';
}
/** 计费因素里「客户组」行当前勾选的因素值(编码),用于价格表 customer_* 列与表头 */
function getSelectedCustomerGroupCodesFromBilling(): string[] {
for (const item of billingFactorsData.value) {
if (!item.factor || !Array.isArray(item.factorValues) || item.factorValues.length === 0) {
continue;
}
if (!isCustomerGroupValueFactor(item.factor)) continue;
return item.factorValues.map((v) => String(v).trim()).filter(Boolean);
}
return [];
}
/** 全部客户(与其它客户组互斥;价格表只一列) */
const ALL_CUSTOMER_CODE = 'all';
const ALL_CUSTOMER_LABEL = '全部客户';
function isAllCustomerCode(code: string): boolean {
const s = String(code ?? '').trim();
return s === ALL_CUSTOMER_CODE || s === ALL_CUSTOMER_LABEL;
}
/** 因素值存价格分区 KPI 主键 id(兼容旧名「分区」) */
function isPartitionValueFactor(factorKey: string): boolean {
if (factorKey === '分区' || factorKey === '价格分区') return true;
const m = getPricingFactorMeta(factorKey);
return m?.dictCode === 'zone' || m?.dictName === '价格分区' || m?.dictName === '分区';
}
/** 因素值存偏远分区 KPI 主键 id */
function isRemotePartitionValueFactor(factorKey: string): boolean {
if (factorKey === '偏远分区') return true;
const m = getPricingFactorMeta(factorKey);
return m?.dictCode === 'remoteZone' || m?.dictName === '偏远分区';
}
/** 因素值存仓库主键 id */
function isWarehouseValueFactor(factorKey: string): boolean {
if (factorKey === '仓库') return true;
const m = getPricingFactorMeta(factorKey);
return m?.dictCode === 'warehouse';
}
function isWeightValueFactor(factorKey: string): boolean {
if (isWeightPricingFactor(factorKey)) return true;
const m = getPricingFactorMeta(factorKey);
return m?.dictCode === 'weight';
}
function isCustomerFactor(factorValue: string): boolean {
return isCustomerGroupValueFactor(factorValue);
}
/** 客户因素值互斥:选全部客户则只保留 all,否则去掉 all */
function normalizeCustomerFactorSelection(values: string[]): string[] {
const codes = values.map((v) => String(v).trim()).filter(Boolean);
if (codes.some(isAllCustomerCode)) {
const hit = dictRowsOfType('customer_group').find(
(r) => isAllCustomerCode(r.dictCode) || isAllCustomerCode(r.dictName),
);
return [hit?.dictCode || ALL_CUSTOMER_CODE];
}
return codes.filter((c) => !isAllCustomerCode(c));
}
/** 提交/回填统一:分区、仓库传 id;货物类型、客户组传字典编码 */
function toCanonicalFactorValues(factor: string, values: string[] | undefined): string[] {
const vs = Array.isArray(values) ? values : [];
if (isPartitionValueFactor(factor)) {
return vs.map((v) => {
const s = String(v).trim();
if (priceAreaFactorOptions.value.some((o) => o.value === s)) return s;
const byLabel = priceAreaFactorOptions.value.find((o) => o.label === s);
return byLabel?.value ?? s;
});
}
if (isRemotePartitionValueFactor(factor)) {
return vs.map((v) => {
const s = String(v).trim();
if (remoteAreaDivisionOptions.value.some((o) => o.value === s)) return s;
const byLabel = remoteAreaDivisionOptions.value.find((o) => o.label === s);
return byLabel?.value ?? s;
});
}
if (isWarehouseValueFactor(factor)) {
return vs.map((v) => {
const s = String(v).trim();
if (warehouseFactorOptions.value.some((o) => o.value === s)) return s;
const byLabel = warehouseFactorOptions.value.find((o) => o.label === s);
return byLabel?.value ?? s;
});
}
if (isCargoTypeValueFactor(factor)) {
return vs.map((v) => {
const s = String(v).trim();
const hit = dictRowsOfType('cargo_attribute').find(
(r) => r.dictCode === s || r.dictName === s
);
return hit?.dictCode ?? s;
});
}
if (isCustomerGroupValueFactor(factor)) {
const mapped = vs.map((v) => {
const s = String(v).trim();
const hit = dictRowsOfType('customer_group').find(
(r) => r.dictCode === s || r.dictName === s
);
return hit?.dictCode ?? s;
});
return normalizeCustomerFactorSelection(mapped);
}
const mapped = vs.map((v) => String(v));
if (isWeightValueFactor(factor)) {
return sortFactorValuesBySize(mapped);
}
return mapped;
}
/** 价格表客户组列表头:与写死全量字典列一致,用 customer_group 的 dictName;入参为勾选的因素编码 */
function customerGroupPriceTableHeaderLabel(code: string, index: number): string {
const c = String(code ?? '').trim();
if (isAllCustomerCode(c)) return ALL_CUSTOMER_LABEL;
if (c) {
const hit = dictRowsOfType('customer_group').find(
(r) => r.dictCode === c || r.dictName === c
);
const name = hit?.dictName?.trim();
if (name) return name;
}
return `客户组${index + 1}`;
}
/** 字典因素值仅展示名称,不展示 dictCode(解析不到则空串,避免把编码露给用户) */
function dictFactorDisplayNameOnly(dictType: string, stored: string): string {
const s = String(stored ?? '').trim();
if (!s) return '';
const rows = dictRowsOfType(dictType);
const byCode = rows.find((r) => r.dictCode === s);
if (byCode?.dictName) return byCode.dictName;
const byName = rows.find((r) => r.dictName === s);
return byName?.dictName || '';
}
/** 因素值界面展示:分区/仓库只显示名称;货物类型/客户组只显示字典名称;重量等仍显示原值 */
function formatFactorValueTagDisplay(factorKey: string, stored: string): string {
const s = String(stored ?? '').trim();
if (!s) return '';
if (isCargoTypeValueFactor(factorKey)) {
return dictFactorDisplayNameOnly('cargo_attribute', s) || '';
}
if (isCustomerGroupValueFactor(factorKey)) {
return dictFactorDisplayNameOnly('customer_group', s) || '';
}
if (isPartitionValueFactor(factorKey)) {
const opt = priceAreaFactorOptions.value.find((o) => o.value === s || o.label === s);
return opt?.label || '';
}
if (isRemotePartitionValueFactor(factorKey)) {
const opt = remoteAreaDivisionOptions.value.find((o) => o.value === s || o.label === s);
return opt?.label || '';
}
if (isWarehouseValueFactor(factorKey)) {
const opt = warehouseFactorOptions.value.find((o) => o.value === s || o.label === s);
return opt?.label || '';
}
if (isWeightValueFactor(factorKey)) {
const bf = billingFactorsData.value.find((item) => item.factor === factorKey);
return weightValueToIntervalCell(s, bf?.factorValues ?? []);
}
return s;
}
function formatPriceTableFactorCell(factorIndex: number | undefined, raw: string): string {
if (factorIndex == null || factorIndex < 0) return '';
const fac = billingFactorsData.value[factorIndex]?.factor;
if (!fac) return '';
return formatFactorValueTagDisplay(fac, raw);
}
const cargoAttributeValueOptions = computed<IdSelectOption[]>(() =>
dictRowsOfType('cargo_attribute').map((r) => ({
label: r.dictName || '(未命名)',
value: r.dictCode,
}))
);
const customerGroupValueOptions = computed<IdSelectOption[]>(() =>
dictRowsOfType('customer_group').map((r) => ({
label: r.dictName || '(未命名)',
value: r.dictCode,
}))
);
function defaultCalculationFormulaCode(): string {
const rows = dictRowsOfType('calculation_formula');
const hit = rows.find((r) => r.dictName === '总价');
return hit?.dictCode || rows[0]?.dictCode || '总价';
}
function formulaCodeToLabel(code: string): string {
const c = String(code ?? '').trim();
if (!c) return '';
return dictLabelByType('calculation_formula', c) || c;
}
function formulaLabelToCode(labelOrCode: string): string {
const s = String(labelOrCode ?? '').trim();
if (!s) return defaultCalculationFormulaCode();
const rows = dictRowsOfType('calculation_formula');
const byName = rows.find((r) => r.dictName === s);
if (byName?.dictCode) return byName.dictCode;
const byCode = rows.find((r) => r.dictCode === s);
if (byCode?.dictCode) return byCode.dictCode;
return s;
}
function defaultCalculationFormulaDisplay(): string {
return formulaCodeToLabel(defaultCalculationFormulaCode());
}
const factorValuesOptionsByFactor = computed<Record<string, IdSelectOption[]>>(() => {
const cargoOpts = cargoAttributeValueOptions.value;
const cgOpts = customerGroupValueOptions.value;
const priceZoneOpts = priceAreaFactorOptions.value;
const remoteZoneOpts = remoteAreaDivisionOptions.value;
const whOpts = warehouseFactorOptions.value;
const base: Record<string, IdSelectOption[]> = {
货物类型: cargoOpts,
cargo: cargoOpts,
分区: priceZoneOpts,
价格分区: priceZoneOpts,
zone: priceZoneOpts,
偏远分区: remoteZoneOpts,
remoteZone: remoteZoneOpts,
重量: weightFactorOptions,
weight: weightFactorOptions,
仓库: whOpts,
warehouse: whOpts,
客户: cgOpts,
客户组: cgOpts,
customer: cgOpts,
};
const out: Record<string, IdSelectOption[]> = { ...base };
const resolveFactorValueSource = (code: string, name: string): IdSelectOption[] | undefined => {
const fromBase = (name && base[name]) || base[code];
if (fromBase) return fromBase;
if (code === 'zone' || name === '分区' || name === '价格分区') return priceZoneOpts;
if (code === 'remoteZone' || name === '偏远分区') return remoteZoneOpts;
if (code === 'customer' || name === '客户' || name === '客户组') return cgOpts;
if (code === 'cargo' || name === '货物类型') return cargoOpts;
if (code === 'warehouse' || name === '仓库') return whOpts;
if (code === 'weight' || name === '重量') return weightFactorOptions;
return undefined;
};
for (const r of dictRowsOfType('pricing_factor')) {
const code = r.dictCode;
const name = r.dictName;
if (!code) continue;
const src = resolveFactorValueSource(code, name);
if (src) {
out[code] = src;
if (name) out[name] = src;
}
}
return out;
});
const handleSearch = () => {
loadProductList();
};
// 新增产品弹窗相关
const addProductModalVisible = ref(false);
const addProductShowAdvanced = ref(false);
const addProductFormData = reactive({
productCode: '',
productName: '',
group: '',
minTimeliness: '',
maxTimeliness: '',
tradeTerms: '' as '' | 'DDP' | 'DDU',
routeSort: 0,
customerWaybill: '系统面单',
labelTemplateId: undefined as number | undefined,
blacklistArea: '',
remoteAreaDivision: '',
additionalServices: [] as string[],
weightCalculationRule: '',
weightRounding: '',
productDescription: '',
preStorageScript: '',
});
const additionalServiceOptions = computed(() => mapDictToSelectOptions('additional_service'));
/** 取现有产品最大线路排序 + 1;无产品时从 0 起 */
function resolveNextRouteSort(items: any[]): number {
let max = -1;
for (const it of items ?? []) {
const raw = it?.raw ?? it;
const n = Number(raw?.routeSort ?? raw?.RouteSort ?? 0);
if (Number.isFinite(n) && n > max) max = n;
}
return Math.max(0, max + 1);
}
async function fetchNextRouteSort(): Promise<number> {
// 左侧列表可能带 keyword 过滤,新增时单独拉全量以保证取到全局最大排序
try {
const { items } = await getSalesProductList({ page: 1, pageSize: 500 });
return resolveNextRouteSort(items || []);
} catch {
return resolveNextRouteSort(productList.value);
}
}
// 新增产品
const handleAddProduct = async () => {
void ensureSalesPriceDictLoaded();
const nextRouteSort = await fetchNextRouteSort();
// 重置表单数据
Object.assign(addProductFormData, {
productCode: '',
productName: '',
group: defaultProductGroupValue(),
minTimeliness: '',
maxTimeliness: '',
tradeTerms: '' as '' | 'DDP' | 'DDU',
routeSort: nextRouteSort,
customerWaybill: '系统面单',
labelTemplateId: undefined,
blacklistArea: '',
remoteAreaDivision: '',
additionalServices: [] as string[],
weightCalculationRule: '',
weightRounding: '',
productDescription: '',
preStorageScript: '',
});
addProductShowAdvanced.value = false;
addProductModalVisible.value = true;
};
const handleSaveAddProduct = async () => {
addProductFormData.productCode = normalizeBizCode(addProductFormData.productCode);
if (!addProductFormData.productCode?.trim() || !addProductFormData.productName?.trim()) {
Message.warning('请填写产品代码和名称');
return;
}
try {
const blId = toOptionalPositiveId(addProductFormData.blacklistArea);
const rmId = toOptionalPositiveId(addProductFormData.remoteAreaDivision);
const wrId = toOptionalPositiveId(addProductFormData.weightCalculationRule);
const roundingId = toOptionalPositiveId(addProductFormData.weightRounding);
const additionalServices = serializeAdditionalServices(addProductFormData.additionalServices);
await createSalesProduct({
productCode: addProductFormData.productCode.trim(),
productName: addProductFormData.productName.trim(),
productGroup: addProductFormData.group || defaultProductGroupValue(),
minTimeliness: Number(addProductFormData.minTimeliness) || 0,
maxTimeliness: Number(addProductFormData.maxTimeliness) || 0,
tradeTerms: addProductFormData.tradeTerms || null,
routeSort: Math.max(0, Number(addProductFormData.routeSort) || 0),
customerWaybill: addProductFormData.customerWaybill || '系统面单',
labelTemplateId: addProductFormData.labelTemplateId || undefined,
productDescription: addProductFormData.productDescription || '',
preStorageScript: addProductFormData.preStorageScript || '',
additionalServices,
isActive: ENABLE_STATUS.enabled,
scheme: 'costLowest',
...(blId != null ? { blacklistAreaId: blId } : {}),
...(rmId != null ? { remoteAreaId: rmId } : {}),
...(wrId != null ? { weightRuleId: wrId } : {}),
...(roundingId != null ? { weightRoundingId: roundingId } : {}),
});
Message.success('保存成功');
addProductModalVisible.value = false;
await loadProductList();
} catch (e: any) {
Message.error(e?.message || '保存失败');
}
};
// 取消新增产品
const handleCancelAddProduct = () => {
addProductShowAdvanced.value = false;
addProductModalVisible.value = false;
};
// 左侧菜单:筛选后的产品列表(按名称搜索)
const filteredProductList = computed(() => {
if (!searchKeyword.value) return productList.value;
return productList.value.filter((p: any) =>
p.name?.toLowerCase().includes(searchKeyword.value.toLowerCase())
);
});
// 左侧菜单:产品树数据(单分类 + 子节点,供 CustomLeftMenu 使用)
const productTreeData = computed<CustomLeftMenuTreeNode[]>(() => {
const list = filteredProductList.value || [];
if (list.length === 0) return [];
return [
{
key: 'category-products',
title: '产品',
children: list.map((p: any) => ({
key: `item-${p.id}`,
title: p.name,
isLeaf: true,
id: p.id,
name: p.name,
...p,
})),
},
];
});
const productSelectedKeys = computed(() =>
selectedProduct.value !== null ? [`item-${selectedProduct.value}`] : []
);
const productExpandedKeys = ref(['category-products']);
function handleProductSelectFromTree(keys: string[], info: any) {
void handleProductSelectFromTreeAsync(keys, info);
}
async function handleProductSelectFromTreeAsync(keys: string[], info: any) {
const node = info?.node;
if (!node || !node.isLeaf) return;
const key = node.key;
if (!key.startsWith('item-')) return;
const id = Number(key.slice(5));
const product = filteredProductList.value.find((p: any) => p.id === id);
if (!product) return;
// 已选中且卖价已加载:忽略重复 select(树/受控 selectedKeys 偶发连发)
if (
selectedProduct.value === id
&& activeTab.value === 'price'
&& priceTabLoadedProductId === id
&& !configFormDirty.value
&& !rulesFormDirty.value
) {
return;
}
const ok = await confirmDiscardUnsavedChanges();
if (!ok) return;
await handleSelectProduct(product);
}
async function refreshSalesProductPriceEffectiveInfo(productId: number) {
try {
// 只要版本号和生效时间,不拉快照正文。50 条完整价格矩阵会让切回卖价空等数秒。
const items = await loadPublishHeaders(productId, 'price');
if (selectedProduct.value !== productId) return;
const effectiveRow = items.find((r: any) => isPublishRecordEffectiveRow(r));
const pick = effectiveRow || items[0];
if (pick) {
effectiveVersion.value = String(pick.version ?? pick.Version ?? '--');
effectiveTime.value = String(pick.publishTime ?? pick.PublishTime ?? pick.createTime ?? pick.CreateTime ?? '--');
} else {
effectiveVersion.value = '--';
effectiveTime.value = '--';
}
} catch {
effectiveVersion.value = '--';
effectiveTime.value = '--';
}
}
let priceTabLoadSeq = 0;
/** 当前 priceTableData 所属产品;切走再回来时直接复用,不再空表重拉 */
let priceTabLoadedProductId: number | null = null;
/** 同产品进行中的列表请求复用,避免树 select 连发打两次 price/list */
let priceTabInflight: { productId: number; promise: Promise<void> } | null = null;
const priceListLoading = ref(false);
async function loadPriceTabData(productId: number, opts?: { force?: boolean }) {
if (priceTabInflight?.productId === productId) {
await priceTabInflight.promise;
return;
}
// 已加载过该产品(含空列表)且非强制刷新:跳过,避免重复 price/list
if (!opts?.force && priceTabLoadedProductId === productId) {
return;
}
const seq = ++priceTabLoadSeq;
const showSpinner = priceTabLoadedProductId !== productId || priceTableData.value.length === 0;
if (showSpinner) priceListLoading.value = true;
const run = (async () => {
try {
// 列表不拉 details,也不等发布记录。生效版本在列表渲染后单独补。
const prices = await getSalesProductPriceList(productId, { includeDetails: false });
// 快速切换产品时丢弃过期响应
if (seq !== priceTabLoadSeq || selectedProduct.value !== productId) return;
// 映射前确保字典就绪,计费因素列显示中文名而非 code
if (!salesPriceDictFetched.value) {
await ensureSalesPriceDictLoaded();
if (seq !== priceTabLoadSeq || selectedProduct.value !== productId) return;
}
// factors 仍可能较多:markRaw 禁止 Vue 深度代理
const rows = (prices || []).map((it: any) => {
const factors = Array.isArray(it.factors) ? it.factors : [];
const audit = pickResolvedAudit(it);
return {
id: it.id,
serialNumber: it.serialNumber,
status: isEnableStatusEnabled(it.status ?? it.Status),
priceName: it.priceName,
costItem: it.costItem,
costUnit: it.costUnit,
currency: it.currency,
chargingCondition: it.chargingCondition || '',
billingFactors: factors
.map((f: any) => pricingFactorColumnLabel(String(f?.factor ?? f?.name ?? '')))
.filter(Boolean)
.join('+'),
factors: markRaw(factors),
details: null as any[] | null,
modifyTime: audit.updateTime,
modifier: audit.updateBy,
};
});
priceTableData.value = rows;
priceTabLoadedProductId = productId;
void refreshSalesProductPriceEffectiveInfo(productId);
// 徽章只听后端 sync-status,不在前端算差异
void refreshPricePublishSyncStatus(productId);
} catch (e) {
if (seq !== priceTabLoadSeq) return;
console.error(e);
effectiveVersion.value = '--';
effectiveTime.value = '--';
} finally {
if (seq === priceTabLoadSeq) priceListLoading.value = false;
}
})();
priceTabInflight = { productId, promise: run };
try {
await run;
} finally {
if (priceTabInflight?.productId === productId && priceTabInflight.promise === run) {
priceTabInflight = null;
}
}
}
/** 排货规则:服务渠道下拉(GET /channel/service-channel/list) */
const serviceChannelListRaw = ref<any[]>([]);
/** 兼容 allocation/get:camelCase / PascalCase、以及多包一层 data */
function normalizeSalesProductAllocationPayload(raw: unknown): { scheme: string; providers: any[] } {
const empty = { scheme: 'costLowest', providers: [] as any[] };
if (raw == null || typeof raw !== 'object') return empty;
let cur: any = raw;
for (let depth = 0; depth < 4; depth++) {
const scheme = cur.scheme ?? cur.Scheme;
const providersRaw = cur.providers ?? cur.Providers;
if (Array.isArray(providersRaw) || scheme != null) {
return {
scheme: String(scheme ?? 'costLowest'),
providers: Array.isArray(providersRaw) ? providersRaw : [],
};
}
const next = cur.data ?? cur.Data;
if (next == null || typeof next !== 'object') break;
cur = next;
}
return empty;
}
const serviceChannelSelectOptions = computed(() => {
const fromApi = serviceChannelListRaw.value
.map((c: any) => {
const id = Number(c.id ?? c.Id);
const gn = String(c.groupName ?? c.GroupName ?? '').trim();
const cn = String(c.channelName ?? c.ChannelName ?? '').trim();
const label = `${gn}${cn}`.trim() || `渠道 #${id}`;
return { value: id, label };
})
.filter((o) => Number.isFinite(o.value));
const byVal = new Map<number, { value: number; label: string }>();
for (const o of fromApi) {
byVal.set(o.value, o);
}
for (const row of shippingProviderData.value) {
const rid = row.serviceChannelId;
const id = rid != null && rid !== '' ? Number(rid) : NaN;
if (!Number.isFinite(id) || byVal.has(id)) continue;
const label =
String(row.serviceChannelName || row.providerName || '').trim() || `渠道 #${id}`;
byVal.set(id, { value: id, label });
}
return Array.from(byVal.values());
});
let serviceChannelOptionsLoaded = false;
let serviceChannelOptionsPromise: Promise<void> | null = null;
async function loadServiceChannelOptionsForRules() {
if (serviceChannelOptionsLoaded) return;
if (serviceChannelOptionsPromise) return serviceChannelOptionsPromise;
serviceChannelOptionsPromise = (async () => {
try {
serviceChannelListRaw.value = (await getServiceChannelOptions()) ?? [];
serviceChannelOptionsLoaded = true;
} catch (e: any) {
Message.warning(e?.message || '加载服务渠道列表失败');
serviceChannelListRaw.value = [];
} finally {
serviceChannelOptionsPromise = null;
}
})();
await serviceChannelOptionsPromise;
}
function syncShippingRowProviderNameFromChannel(row: any) {
const rawId = row.serviceChannelId;
const id = rawId != null && rawId !== '' ? Number(rawId) : NaN;
if (!Number.isFinite(id)) {
row.providerName = '';
return;
}
const raw = serviceChannelListRaw.value.find((c: any) => Number(c.id ?? c.Id) === id);
if (raw) {
const gn = String(raw.groupName ?? raw.GroupName ?? '').trim();
const cn = String(raw.channelName ?? raw.ChannelName ?? '').trim();
row.providerName = `${gn}${cn}`.trim() || row.providerName || '';
}
}
let rulesTabLoadedProductId: number | null = null;
let rulesLoadSeq = 0;
const rulesLoading = ref(false);
async function loadRulesTabData(productId: number) {
if (rulesTabLoadedProductId === productId) return;
const seq = ++rulesLoadSeq;
rulesLoading.value = true;
try {
const [, allocRaw] = await Promise.all([
loadServiceChannelOptionsForRules(),
getSalesProductAllocation(productId),
]);
if (seq !== rulesLoadSeq || selectedProduct.value !== productId) return;
const alloc = normalizeSalesProductAllocationPayload(allocRaw);
shippingScheme.value = alloc.scheme || 'costLowest';
shippingProviderData.value = (alloc.providers || []).map((p: any) => ({
id: p.id ?? p.Id,
serialNumber: p.serialNumber ?? p.SerialNumber ?? 0,
providerName: String(p.providerName ?? p.ProviderName ?? '').trim(),
serviceChannelName: String(p.serviceChannelName ?? p.ServiceChannelName ?? '').trim() || undefined,
serviceChannelId:
p.serviceChannelId != null && p.serviceChannelId !== ''
? Number(p.serviceChannelId ?? p.ServiceChannelId)
: undefined,
weight: p.weight ?? p.Weight ?? 0,
matchCondition: String(p.matchCondition ?? p.MatchCondition ?? '').trim(),
customers: p.customerIds ?? p.CustomerIds ?? p.customers ?? p.Customers ?? [],
}));
resetRulesFormBaseline();
rulesTabLoadedProductId = productId;
} catch (e) {
console.error(e);
} finally {
if (seq === rulesLoadSeq) rulesLoading.value = false;
}
}
function publishContentToText(content: unknown) {
if (content == null || content === '') return '';
return typeof content === 'string' ? content : JSON.stringify(content);
}
let pricePublishHeaders: { productId: number; items: any[] } | null = null;
let rulesPublishHeaders: { productId: number; items: any[] } | null = null;
function clearPublishHeaderCache(productId?: number) {
if (productId == null || pricePublishHeaders?.productId === productId) pricePublishHeaders = null;
if (productId == null || rulesPublishHeaders?.productId === productId) rulesPublishHeaders = null;
}
/** 版本头只请求一次。页面没有分页,也不带快照正文。 */
async function loadPublishHeaders(productId: number, operatorType: 'price' | 'rules') {
const hit = operatorType === 'price' ? pricePublishHeaders : rulesPublishHeaders;
if (hit?.productId === productId) return hit.items;
const res = operatorType === 'price'
? await getSalesProductPublishPriceList({ salesProductId: productId, includeContent: false })
: await getSalesProductPublishRulesList({ salesProductId: productId, includeContent: false });
const items = res.items || [];
const next = { productId, items };
if (operatorType === 'price') pricePublishHeaders = next;
else rulesPublishHeaders = next;
return items;
}
/** 取最新一条发布快照。正文按 id 另取。 */
async function loadLatestPublishSnapshot(productId: number, operatorType: 'price' | 'rules') {
const items = await loadPublishHeaders(productId, operatorType);
const latest = items[0] as Record<string, any> | undefined;
const id = latest?.id ?? latest?.Id;
if (id == null) return null;
const cached = (operatorType === 'price' ? priceData.value : rulesData.value)
.find((row) => row.id === id);
if (cached?.contentLoaded) return cached.content || null;
const detail = await getSalesProductPublishRecord(id);
return detail?.content ?? detail?.Content ?? null;
}
/** 同步态:待发布 / 待审批 / 失败可重提 / 已发布 */
function clearPriceApprovalSyncState() {
priceApprovalRequired.value = false;
priceApprovalPending.value = false;
priceApprovalFailed.value = false;
priceApprovalExecuteFailed.value = false;
priceApprovalInstanceId.value = null;
priceApprovalInstanceNo.value = '';
priceApprovalStatusName.value = '';
priceApprovalComment.value = '';
}
async function refreshPricePublishSyncStatus(productId?: number) {
const pid = productId ?? selectedProduct.value;
if (pid == null) {
pricePublishChecking.value = false;
pricePublishPending.value = null;
clearPriceApprovalSyncState();
return;
}
const seq = priceTabLoadSeq;
pricePublishChecking.value = true;
try {
const status = await getSalesProductPublishSyncStatus({
salesProductId: pid,
operatorType: 'price',
});
if (seq !== priceTabLoadSeq || selectedProduct.value !== pid) return;
const pending = status?.pending ?? status?.Pending;
pricePublishPending.value = typeof pending === 'boolean' ? pending : null;
priceApprovalRequired.value = Boolean(
status?.approvalRequired ?? status?.ApprovalRequired,
);
const approvalPending = Boolean(
status?.approvalPending ?? status?.ApprovalPending,
);
const approvalFailed = Boolean(
status?.approvalFailed ?? status?.ApprovalFailed,
);
priceApprovalPending.value = approvalPending;
priceApprovalFailed.value = approvalFailed && !approvalPending;
const statusName = String(
status?.approvalStatusName ?? status?.ApprovalStatusName ?? '',
).trim();
priceApprovalStatusName.value = statusName;
priceApprovalExecuteFailed.value =
priceApprovalFailed.value && statusName === '执行失败';
const instanceId =
status?.approvalInstanceId ?? status?.ApprovalInstanceId ?? null;
priceApprovalInstanceId.value =
typeof instanceId === 'number' && instanceId > 0 ? instanceId : null;
priceApprovalInstanceNo.value = String(
status?.approvalInstanceNo ?? status?.ApprovalInstanceNo ?? '',
).trim();
priceApprovalComment.value = String(
status?.approvalComment ?? status?.ApprovalComment ?? '',
).trim();
} catch {
if (seq === priceTabLoadSeq) {
pricePublishPending.value = null;
clearPriceApprovalSyncState();
}
} finally {
if (seq === priceTabLoadSeq) pricePublishChecking.value = false;
}
}
const priceApprovalDrawerVisible = ref(false);
const priceApprovalRetryLoading = ref(false);
function openPriceApprovalDrawer() {
if (!priceApprovalInstanceId.value) {
Message.warning(t('channel.salesProducts.publish.approvalDetailMissing'));
return;
}
priceApprovalDrawerVisible.value = true;
}
async function retryPriceApprovalExecute() {
const id = priceApprovalInstanceId.value;
if (!id) {
Message.warning(t('channel.salesProducts.publish.approvalDetailMissing'));
return;
}
priceApprovalRetryLoading.value = true;
try {
await retryApprovalExecute(id);
Message.success(t('common.success'));
const pid = selectedProduct.value;
if (pid != null) {
await refreshPricePublishSyncStatus(pid);
await loadPriceTabData(pid, { force: true });
await loadRecordsTabData(pid, true);
}
} catch (e: unknown) {
Message.error((e as Error)?.message || t('common.failed'));
} finally {
priceApprovalRetryLoading.value = false;
}
}
async function onPriceApprovalChanged() {
const pid = selectedProduct.value;
if (pid == null) return;
await refreshPricePublishSyncStatus(pid);
await loadPriceTabData(pid, { force: true });
await loadRecordsTabData(pid, true);
}
let recordsTabLoadedProductId: number | null = null;
let recordsLoadSeq = 0;
let publishContentSeq = 0;
const recordsLoading = ref(false);
const publishRecordContentLoading = ref(false);
function mapPublishRecordHeader(r: any) {
return {
id: r.id ?? r.Id,
version: r.version ?? r.Version,
operatorType: r.operatorType ?? r.OperatorType,
status: r.status ?? r.Status,
publishUser: r.publishUser ?? r.PublishUser,
publishTime: r.publishTime ?? r.PublishTime,
description: r.description ?? r.Description,
aiAnalysisReport: '',
content: '',
contentLoaded: false,
};
}
async function ensureActivePublishRecordContent() {
const rec = currentPublishRecord.value as Record<string, any>;
if (!rec?.id || rec.contentLoaded) return;
const id = rec.id;
const seq = ++publishContentSeq;
publishRecordContentLoading.value = true;
try {
const detail = await getSalesProductPublishRecord(id);
if (seq !== publishContentSeq) return;
const target = [...priceData.value, ...rulesData.value].find((row) => row.id === id);
if (!target) return;
target.content = publishContentToText(detail?.content ?? detail?.Content);
target.aiAnalysisReport = detail?.aiAnalysisReport ?? detail?.AiAnalysisReport ?? '';
target.contentLoaded = true;
} catch (e) {
console.error(e);
} finally {
if (seq === publishContentSeq) publishRecordContentLoading.value = false;
}
}
async function loadRecordsTabData(productId: number, force = false) {
if (!force && recordsTabLoadedProductId === productId) {
void ensureActivePublishRecordContent();
return;
}
const seq = ++recordsLoadSeq;
recordsLoading.value = true;
if (force) clearPublishHeaderCache(productId);
try {
const [priceItems, rulesItems] = await Promise.all([
loadPublishHeaders(productId, 'price'),
loadPublishHeaders(productId, 'rules'),
]);
if (seq !== recordsLoadSeq || selectedProduct.value !== productId) return;
priceData.value = priceItems.map(mapPublishRecordHeader);
rulesData.value = rulesItems.map(mapPublishRecordHeader);
recordsTabLoadedProductId = productId;
void ensureActivePublishRecordContent();
} catch (e) {
console.error(e);
} finally {
if (seq === recordsLoadSeq) recordsLoading.value = false;
}
}
async function loadSalesProductRelatedByTab(productId: number, tabKey: string) {
if (tabKey === 'price') {
// 字典与卖价列表并行,避免串行拖慢首屏
await Promise.all([ensureSalesPriceDictLoaded(), loadPriceTabData(productId)]);
return;
}
if (tabKey === 'rules') {
await loadRulesTabData(productId);
return;
}
if (tabKey === 'records') {
await loadRecordsTabData(productId);
return;
}
}
function applyProductDetailToForm(product: any, d: Record<string, any>) {
const p = d;
const numStr = (v: unknown) => (v != null && v !== '' ? String(v) : '');
Object.assign(formData, {
productCode: p.productCode ?? p.ProductCode ?? '',
productName: p.productName ?? p.ProductName ?? '',
group: resolveProductGroupValue(p.productGroup ?? p.ProductGroup),
minTimeliness: numStr(p.minTimeliness ?? p.MinTimeliness),
maxTimeliness: numStr(p.maxTimeliness ?? p.MaxTimeliness),
tradeTerms: (() => {
const raw = String(p.tradeTerms ?? p.TradeTerms ?? '')
.trim()
.toUpperCase();
return raw === 'DDP' || raw === 'DDU' ? raw : '';
})(),
routeSort: (() => {
const n = Number(p.routeSort ?? p.RouteSort ?? 0);
return Number.isFinite(n) && n >= 0 ? n : 0;
})(),
customerWaybill: p.customerWaybill ?? p.CustomerWaybill ?? '系统面单',
labelTemplateId: (() => {
const raw = p.labelTemplateId ?? p.LabelTemplateId;
const n = Number(raw);
return Number.isFinite(n) && n > 0 ? n : undefined;
})(),
blacklistArea: numStr(p.blacklistAreaId ?? p.BlacklistAreaId),
remoteAreaDivision: numStr(p.remoteAreaId ?? p.RemoteAreaId),
additionalServices: parseAdditionalServiceCodes(
p.additionalServices ?? p.AdditionalServices,
),
weightCalculationRule: numStr(p.weightRuleId ?? p.WeightRuleId),
weightRounding: numStr(p.weightRoundingId ?? p.WeightRoundingId),
productDescription: p.productDescription ?? p.ProductDescription ?? '',
preStorageScript: p.preStorageScript ?? p.PreStorageScript ?? '',
});
customerGuideMarkdown.value = p.customerGuideMarkdown ?? p.CustomerGuideMarkdown ?? '';
const audit = pickResolvedAudit(p);
const hit = productList.value.find((item: any) => item.id === product.id);
if (hit) {
hit.createTime = audit.createTime || hit.createTime;
hit.updateTime = audit.updateTime || hit.updateTime;
hit.createBy = audit.createBy || hit.createBy;
hit.updateBy = audit.updateBy || hit.updateBy;
hit.creator = hit.updateBy || hit.createBy || hit.creator || '';
hit.raw = { ...(hit.raw || {}), ...p };
}
resetConfigFormBaseline();
}
const handleSelectProduct = async (product: any) => {
const productChanged = selectedProduct.value !== product.id;
// 同产品重复选中且当前 tab 数据已在:不再打 detail / price/list
if (
!productChanged
&& product?.id
&& (
(activeTab.value === 'price' && priceTabLoadedProductId === product.id)
|| (activeTab.value === 'rules' && rulesTabLoadedProductId === product.id)
|| (activeTab.value === 'records' && recordsTabLoadedProductId === product.id)
|| activeTab.value === 'config'
|| activeTab.value === 'customerGuide'
)
) {
return;
}
selectedProduct.value = product.id;
configPublishPending.value = false;
rulesPublishPending.value = false;
if (!product?.id) return;
// 卖价页切产品不先清空表格,避免空表→填表双次重绘;离开卖价后再换产品则丢掉缓存,避免切回来看到上一个产品
if (productChanged && activeTab.value !== 'price') {
priceTableData.value = [];
priceTabLoadedProductId = null;
pricePublishPending.value = null;
pricePublishChecking.value = false;
clearPriceApprovalSyncState();
effectiveVersion.value = '--';
effectiveTime.value = '--';
} else if (activeTab.value === 'price') {
// 切到卖价 tab / 换产品:先清空徽章,等 sync-status 回来再显示
pricePublishPending.value = null;
pricePublishChecking.value = false;
clearPriceApprovalSyncState();
}
if (productChanged && activeTab.value !== 'rules') {
rulesTabLoadedProductId = null;
shippingProviderData.value = [];
shippingScheme.value = 'costLowest';
}
if (productChanged && activeTab.value !== 'records') {
recordsTabLoadedProductId = null;
priceData.value = [];
rulesData.value = [];
clearPublishHeaderCache();
} else if (productChanged) {
clearPublishHeaderCache();
}
try {
// 卖价 tab:详情与列表并行,显著缩短等待
if (activeTab.value === 'price') {
const [d] = await Promise.all([
getSalesProductDetail(product.id),
loadSalesProductRelatedByTab(product.id, 'price'),
]);
if (selectedProduct.value !== product.id) return;
if (d == null || typeof d !== 'object') {
Message.error('产品详情为空,请检查接口返回');
return;
}
applyProductDetailToForm(product, d as Record<string, any>);
return;
}
const d = await getSalesProductDetail(product.id);
if (selectedProduct.value !== product.id) return;
if (d == null || typeof d !== 'object') {
Message.error('产品详情为空,请检查接口返回');
return;
}
applyProductDetailToForm(product, d as Record<string, any>);
await loadSalesProductRelatedByTab(product.id, activeTab.value);
} catch (e: any) {
console.error(e);
Message.error(e?.message || '加载产品详情失败');
}
};
onMounted(() => {
void loadGroupSelectOptions();
void loadKpiAreaSelectOptions();
void loadWeightSelectOptions();
void loadBillingFactorSelectOptions();
void loadLabelTemplateOptions();
void ensureSalesPriceDictLoaded();
loadProductList();
});
const handleToggleProduct = async (product: any) => {
if (!product?.id) return;
const targetEnabled = !!product.isActive;
const previousActive = !targetEnabled;
try {
if (!targetEnabled) {
const confirmed = await new Promise<boolean>((resolve) => {
Modal.confirm({
title: t('channel.salesProducts.messages.toggleDisableTitle'),
content: t('channel.salesProducts.messages.toggleDisableConfirm', {
name: product.name || product.id,
}),
okText: t('channel.salesProducts.modal.actions.ok'),
cancelText: t('channel.salesProducts.modal.actions.cancel'),
onOk: () => resolve(true),
onCancel: () => resolve(false),
});
});
if (!confirmed) {
product.isActive = previousActive;
return;
}
}
const d = await getSalesProductDetail(product.id);
if (d == null || typeof d !== 'object') {
Message.error('无法加载产品详情');
product.isActive = previousActive;
return;
}
const next = toEnableStatus(targetEnabled);
await updateSalesProduct({ ...(d as Record<string, any>), isActive: next });
product.isActive = isEnableStatusEnabled(next);
Message.success('已更新状态');
await loadProductList();
} catch (e: any) {
product.isActive = previousActive;
Message.error(e?.message || '更新失败');
}
};
// 删除产品确认弹窗
const deleteProductModalVisible = ref(false);
const deleteProductInput = ref('');
const deletingProduct = ref<any>(null);
// 删除产品
const handleDeleteProduct = (product: any) => {
deletingProduct.value = product;
deleteProductInput.value = '';
deleteProductModalVisible.value = true;
};
const handleConfirmDeleteProduct = async () => {
if (!deletingProduct.value) return;
if (deleteProductInput.value !== deletingProduct.value.name) {
Message.error('输入的产品名称不正确,请重新输入');
return;
}
try {
await deleteSalesProduct(deletingProduct.value.id);
if (selectedProduct.value === deletingProduct.value.id) {
selectedProduct.value = null;
configFormBaseline.value = null;
rulesFormBaseline.value = null;
}
Message.success('删除成功');
deleteProductModalVisible.value = false;
deletingProduct.value = null;
deleteProductInput.value = '';
await loadProductList();
} catch (e: any) {
Message.error(e?.message || '删除失败');
}
};
// 取消删除产品
const handleCancelDeleteProduct = () => {
deleteProductModalVisible.value = false;
deletingProduct.value = null;
deleteProductInput.value = '';
};
// 标签页切换
const handleTabChange = async (key: string) => {
if (key === activeTab.value) return;
const ok = await confirmDiscardUnsavedChanges();
if (!ok) return;
activeTab.value = key;
if (selectedProduct.value == null) return;
if (key === 'price' && priceTabLoadedProductId === selectedProduct.value) return;
if (key === 'rules' && rulesTabLoadedProductId === selectedProduct.value) return;
if (key === 'records' && recordsTabLoadedProductId === selectedProduct.value) {
void ensureActivePublishRecordContent();
return;
}
// 产品配置、对客说明的数据在选中产品时已经随详情写入,切页不再请求
if (key === 'config' || key === 'customerGuide') return;
if (['price', 'rules', 'records'].includes(key)) {
await loadSalesProductRelatedByTab(selectedProduct.value, key);
}
};
async function handleSaveCustomerGuide(content: string) {
const pid = selectedProduct.value;
if (pid == null) {
Message.warning('请先选择产品');
return;
}
customerGuideSaving.value = true;
try {
await saveSalesProductCustomerGuide({
salesProductId: pid,
customerGuideMarkdown: content,
});
customerGuideMarkdown.value = content;
customerGuidePanelRef.value?.stopEditing?.();
Message.success('对客说明已保存');
} catch (e: any) {
Message.error(e?.message || '保存对客说明失败');
} finally {
customerGuideSaving.value = false;
}
}
// 状态开关滑动切换:记录触摸起点
const statusTouchStartX = ref(0)
const STATUS_SWIPE_THRESHOLD = 40
function onStatusSwipeStart(e: TouchEvent) {
statusTouchStartX.value = e.touches[0].clientX
}
function onStatusSwipeEnd(record: any, e: TouchEvent) {
const endX = e.changedTouches[0].clientX
if (Math.abs(endX - statusTouchStartX.value) >= STATUS_SWIPE_THRESHOLD) {
record.status = !record.status
void handleTogglePriceStatus(record)
}
}
function onProductSwitchSwipeEnd(nodeData: any, e: TouchEvent) {
const endX = e.changedTouches[0].clientX
if (Math.abs(endX - statusTouchStartX.value) >= STATUS_SWIPE_THRESHOLD) {
const product = productList.value.find((p: any) => p.id === nodeData?.id)
if (product) {
product.isActive = !product.isActive
handleToggleProduct(product)
}
}
}
async function persistSalesProductConfig(pid: number) {
const d = await getSalesProductDetail(pid);
if (d == null || typeof d !== 'object') {
throw new Error('无法加载产品详情,保存已取消');
}
const prev = d as Record<string, any>;
const id = Number(prev.id ?? prev.Id ?? pid);
const blAreaId = toOptionalPositiveId(formData.blacklistArea);
const rmAreaId = toOptionalPositiveId(formData.remoteAreaDivision);
const wrId = toOptionalPositiveId(formData.weightCalculationRule);
const roundingId = toOptionalPositiveId(formData.weightRounding);
await updateSalesProduct({
id,
productCode: formData.productCode,
productName: formData.productName,
productGroup: formData.group,
minTimeliness: Number(formData.minTimeliness) || 0,
maxTimeliness: Number(formData.maxTimeliness) || 0,
tradeTerms: formData.tradeTerms || null,
routeSort: Math.max(0, Number(formData.routeSort) || 0),
customerWaybill: formData.customerWaybill,
labelTemplateId: formData.labelTemplateId || undefined,
blacklistAreaId: blAreaId ?? null,
remoteAreaId: rmAreaId ?? null,
additionalServices: serializeAdditionalServices(formData.additionalServices),
weightRuleId: wrId ?? null,
weightRoundingId: roundingId ?? null,
productDescription: formData.productDescription,
preStorageScript: formData.preStorageScript,
isActive: toEnableStatus(isEnableStatusEnabled(prev.isActive ?? prev.IsActive)),
scheme: String(prev.scheme ?? prev.Scheme ?? 'costLowest'),
});
resetConfigFormBaseline();
}
async function persistSalesProductAllocation(pid: number) {
await saveSalesProductAllocation({
salesProductId: Number(pid),
publish: false,
scheme: shippingScheme.value,
providers: shippingProviderData.value.map((row: any) => ({
id: row.id || 0,
serialNumber: row.serialNumber,
providerName: row.providerName ?? '',
serviceChannelId:
row.serviceChannelId != null && row.serviceChannelId !== ''
? Number(row.serviceChannelId)
: 0,
weight: row.weight,
matchCondition: String(row.matchCondition ?? '').trim(),
customerIds: [],
})),
});
resetRulesFormBaseline();
}
const publishOperatorType = ref<'price' | 'rules'>('price');
const publishHasOnlineSnapshot = ref(false);
const publishDiffLength = ref(0);
const publishDiffRows = ref<SnapshotDiffRow[]>([]);
const pricePublishPending = ref<boolean | null>(null);
const pricePublishChecking = ref(false);
const priceApprovalRequired = ref(false);
const priceApprovalPending = ref(false);
const priceApprovalFailed = ref(false);
const priceApprovalExecuteFailed = ref(false);
const priceApprovalInstanceId = ref<number | null>(null);
const priceApprovalInstanceNo = ref('');
const priceApprovalStatusName = ref('');
const priceApprovalComment = ref('');
const priceApprovalFailedBadgeText = computed(() => {
const name = priceApprovalStatusName.value || t('channel.salesProducts.publish.badge.failed');
return priceApprovalInstanceNo.value
? `${name} · ${priceApprovalInstanceNo.value}`
: name;
});
const pricePublishStep2Title = computed(() =>
priceApprovalRequired.value
? t('channel.salesProducts.publish.step2TitleApproval')
: t('channel.salesProducts.publish.step2Title'),
);
const pricePublishStep2Desc = computed(() =>
priceApprovalRequired.value
? t('channel.salesProducts.publish.step2DescApproval')
: t('channel.salesProducts.publish.step2Desc'),
);
const pricePublishStep2ReadyHint = computed(() =>
priceApprovalRequired.value
? t('channel.salesProducts.publish.step2ReadyHintApproval')
: t('channel.salesProducts.publish.step2ReadyHint'),
);
const pricePublishGotoStep2Text = computed(() =>
priceApprovalRequired.value
? t('channel.salesProducts.publish.gotoStep2Approval')
: t('channel.salesProducts.publish.gotoStep2'),
);
const pricePublishFinalConfirmText = computed(() =>
priceApprovalRequired.value
? t('channel.salesProducts.publish.finalConfirmApproval')
: t('channel.salesProducts.publish.finalConfirm'),
);
const pricePublishFinalConfirmHighRiskText = computed(() =>
priceApprovalRequired.value
? t('channel.salesProducts.publish.finalConfirmHighRiskApproval')
: t('channel.salesProducts.publish.finalConfirmHighRisk'),
);
const publishDiffStatus = computed(() => {
if (!publishHasOnlineSnapshot.value) return 'first';
if (publishDiffLength.value === 0) return 'synced';
if (publishDiffLength.value < 0) return 'changed';
return 'changed';
});
function applyPublishDiffState(originalRaw: unknown, modifiedRaw: unknown, hasOnline: boolean) {
publishHasOnlineSnapshot.value = hasOnline;
const { length, rows } = computeSnapshotDiff(originalRaw, modifiedRaw);
publishDiffLength.value = length;
publishDiffRows.value = rows;
}
function yieldToMain() {
return new Promise<void>((resolve) => {
window.setTimeout(resolve, 0);
});
}
let publishJsonFormatTask: Promise<void> | null = null;
let publishJsonFormatGen = 0;
/** 后台格式化原始 JSON:不阻塞弹窗首屏;展开「高级 JSON」/开 AI 前再确保就绪 */
function schedulePublishJsonFormat() {
if (publishJsonFormatTask) return publishJsonFormatTask;
const pendingRaw = publishPendingRaw.value;
const onlineRaw = publishOnlineRaw.value;
if (pendingRaw == null && onlineRaw == null) return Promise.resolve();
const gen = publishJsonFormatGen;
publishJsonFormatTask = (async () => {
try {
await yieldToMain();
if (gen !== publishJsonFormatGen) return;
if (pendingRaw != null && !modifiedModel.value) {
modifiedModel.value = formatSnapshotJson(pendingRaw);
}
await yieldToMain();
if (gen !== publishJsonFormatGen) return;
if (onlineRaw != null && !originalValue.value) {
originalValue.value = formatSnapshotJson(onlineRaw);
}
} catch (error) {
console.warn('[salesProducts] format publish json failed', error);
} finally {
if (gen === publishJsonFormatGen) publishJsonFormatTask = null;
}
})();
return publishJsonFormatTask;
}
async function ensurePublishJsonFormatted() {
if (modifiedModel.value && originalValue.value) return;
publishModalLoading.value = true;
try {
await schedulePublishJsonFormat();
} finally {
publishModalLoading.value = false;
}
}
/** 用后端 publish/preview 接口展示真实快照(含黑名单/计重等内嵌明细) */
async function openPublishDiffModal(operatorType: 'rules' | 'price') {
if (operatorType === 'price') {
// 打开弹窗前刷新,保证流程卡能读到最新 ApprovalRequired
void refreshPricePublishSyncStatus();
}
const pid = selectedProduct.value;
if (pid == null) {
Message.warning('请先选择产品');
return;
}
publishOperatorType.value = operatorType;
publishModalLoading.value = true;
publishJsonFormatGen += 1;
publishJsonFormatTask = null;
publishDiffRows.value = [];
publishDiffLength.value = 0;
publishHasOnlineSnapshot.value = false;
originalValue.value = '';
modifiedModel.value = '';
publishOnlineRaw.value = null;
publishPendingRaw.value = null;
pricePublishShowRawJson.value = false;
clearPricePublishAiReport();
// 先打开弹窗再算大快照,避免长时间白屏/看起来像卡死
publishModalMethods.openModal();
await nextTick();
await yieldToMain();
try {
const preview = await getSalesProductPublishPreview({
salesProductId: pid,
operatorType,
});
publishPendingRaw.value = preview;
await yieldToMain();
const online = await loadLatestPublishSnapshot(Number(pid), operatorType);
const hasOnline = online != null;
publishOnlineRaw.value = hasOnline ? online : {};
await yieldToMain();
applyPublishDiffState(publishOnlineRaw.value ?? {}, preview, hasOnline);
showOnlyDiff.value = publishDiffLength.value > 0;
// JSON 美化放到后台,首屏只展示 diff 摘要
void schedulePublishJsonFormat();
} catch (error) {
publishModalMethods.closeModal();
throw error;
} finally {
publishModalLoading.value = false;
}
}
const handlePublishPrice = async () => {
const pid = selectedProduct.value;
if (pid == null) {
Message.warning('请先选择产品');
return;
}
if (priceTableData.value.length === 0) {
Message.warning('暂无可发布的费用项');
return;
}
if (publishModalLoading.value) return;
try {
await openPublishDiffModal('price');
} catch (e: any) {
Message.error(e?.message || '加载发布预览失败');
}
};
const handleSaveConfig = async () => {
const pid = selectedProduct.value;
if (pid == null) {
Message.warning('请先选择产品');
return;
}
if (!configFormDirty.value) return;
savingConfig.value = true;
try {
await persistSalesProductConfig(pid);
configPublishPending.value = true;
Message.success(t('channel.salesProducts.messages.saveSuccess'));
} catch (e: any) {
Message.error(e?.message || t('channel.salesProducts.messages.saveFailed'));
} finally {
savingConfig.value = false;
}
};
const handlePublishConfig = async () => {
const pid = selectedProduct.value;
if (pid == null) {
Message.warning('请先选择产品');
return;
}
if (configFormDirty.value) {
Message.warning(t('channel.salesProducts.messages.saveFirst'));
return;
}
if (!canPublishConfig.value) return;
Modal.confirm({
title: t('channel.salesProducts.publishConfirm.title'),
content: () =>
h(
'div',
{ style: 'white-space: pre-line; line-height: 1.6;' },
t('channel.salesProducts.publishConfirm.message'),
),
okText: t('channel.salesProducts.publishConfirm.ok'),
cancelText: t('channel.salesProducts.publishConfirm.cancel'),
onOk: async () => {
savingConfig.value = true;
try {
await openPublishDiffModal('rules');
} catch (e: any) {
Message.error(e?.message || t('channel.salesProducts.messages.saveFailed'));
} finally {
savingConfig.value = false;
}
},
});
};
const handleSaveRules = async () => {
const pid = selectedProduct.value;
if (pid == null) {
Message.warning('请先选择产品');
return;
}
if (!rulesFormDirty.value) return;
savingConfig.value = true;
try {
await persistSalesProductAllocation(pid);
rulesPublishPending.value = true;
Message.success(t('channel.salesProducts.messages.saveSuccess'));
Message.warning({
content: t('channel.salesProducts.messages.downstreamSyncTip'),
duration: 8000,
});
} catch (e: any) {
Message.error(e?.message || t('channel.salesProducts.messages.saveFailed'));
} finally {
savingConfig.value = false;
}
};
const handlePublishRules = async () => {
const pid = selectedProduct.value;
if (pid == null) {
Message.warning('请先选择产品');
return;
}
if (rulesFormDirty.value) {
Message.warning(t('channel.salesProducts.messages.saveFirst'));
return;
}
if (!canPublishRules.value) return;
Modal.confirm({
title: t('channel.salesProducts.publishConfirm.title'),
content: () =>
h(
'div',
{ style: 'white-space: pre-line; line-height: 1.6;' },
t('channel.salesProducts.publishConfirm.message'),
),
okText: t('channel.salesProducts.publishConfirm.okRules'),
cancelText: t('channel.salesProducts.publishConfirm.cancel'),
onOk: async () => {
savingConfig.value = true;
try {
await openPublishDiffModal('rules');
} catch (e: any) {
Message.error(e?.message || t('channel.salesProducts.messages.saveFailed'));
} finally {
savingConfig.value = false;
}
},
});
};
// 发布弹窗相关
const pricePublishAiVisible = ref(false);
const billingSimulateVisible = ref(false);
const pricePublishAiReport = ref('');
const pricePublishAiLevel = ref<PricePublishRiskLevel | undefined>();
const pricePublishAiSummary = ref('');
const pricePublishAiPendingFingerprint = ref('');
const pricePublishAiSkipped = ref(false);
/** 价格发布两步:1=AI分析 2=提交(审批或直发);等待在卖价页承接 */
const pricePublishStep = ref<1 | 2>(1);
const pricePublishSubmitting = ref(false);
const pricePublishShowRawJson = ref(false);
const pricePublishReportExpanded = ref(false);
const pricePublishHighRiskAck = ref(false);
const publishModalBodyStyle = {
height: 'min(72vh, 720px)',
maxHeight: '72vh',
overflow: 'hidden',
display: 'flex',
flexDirection: 'column',
padding: '16px',
} as const;
const pricePublishIsHighRisk = computed(() => pricePublishAiLevel.value === '高风险');
const pricePublishAiReady = computed(() => {
if (publishOperatorType.value !== 'price') return true;
if (pricePublishAiSkipped.value) return true;
if (!pricePublishAiReport.value.trim()) return false;
const currentFp = String(getModifiedModel.value || '').trim();
if (
pricePublishAiPendingFingerprint.value &&
currentFp &&
pricePublishAiPendingFingerprint.value !== currentFp
) {
return false;
}
return true;
});
const pricePublishCanFinalSubmit = computed(() => {
if (!pricePublishAiReady.value) return false;
if (pricePublishIsHighRisk.value && !pricePublishHighRiskAck.value) return false;
return true;
});
const isPricePublishFlow = computed(() => publishOperatorType.value === 'price');
function clearPricePublishAiReport() {
pricePublishAiReport.value = '';
pricePublishAiLevel.value = undefined;
pricePublishAiSummary.value = '';
pricePublishAiPendingFingerprint.value = '';
pricePublishAiSkipped.value = false;
pricePublishStep.value = 1;
pricePublishReportExpanded.value = false;
pricePublishHighRiskAck.value = false;
}
async function openPricePublishAiAssist() {
if (publishOperatorType.value !== 'price') return;
await ensurePublishJsonFormatted();
pricePublishAiVisible.value = true;
}
function goPricePublishStep1() {
pricePublishStep.value = 1;
}
function goPricePublishStep2() {
if (!pricePublishAiReady.value) {
if (!pricePublishAiReport.value.trim()) {
Message.warning(t('channel.salesProducts.ai.requireBeforePublish'));
pricePublishAiVisible.value = true;
return;
}
Message.warning(t('channel.salesProducts.ai.pendingChangedNeedReanalyze'));
clearPricePublishAiReport();
pricePublishAiVisible.value = true;
return;
}
publishConfirmDate.value = dayjs();
pricePublishStep.value = 2;
}
function onPricePublishAiAdopt(payload: PricePublishAiAdoptPayload) {
pricePublishAiSkipped.value = false;
pricePublishAiReport.value = payload.report;
pricePublishAiLevel.value = payload.level;
pricePublishAiSummary.value = payload.summary || '';
pricePublishAiPendingFingerprint.value = payload.pendingFingerprint || '';
publishConfirmDate.value = dayjs();
pricePublishReportExpanded.value = false;
pricePublishHighRiskAck.value = false;
pricePublishStep.value = 2;
Message.success(t('channel.salesProducts.ai.adoptedToStep2'));
}
function onPricePublishAiSkip() {
const at = dayjs();
const timeStr = at.format('YYYY-MM-DD HH:mm:ss');
const operator = getPricePublishOperatorName();
pricePublishAiSkipped.value = true;
pricePublishAiReport.value = buildPricePublishAiSkipReport(operator, timeStr);
pricePublishAiLevel.value = undefined;
pricePublishAiSummary.value = t('channel.salesProducts.ai.skipSummary', {
operator,
time: timeStr,
});
pricePublishAiPendingFingerprint.value = '';
publishConfirmDate.value = at;
pricePublishReportExpanded.value = true;
pricePublishHighRiskAck.value = false;
pricePublishStep.value = 2;
Message.success(t('channel.salesProducts.ai.skippedToStep2'));
}
const [registerPublishModal, publishModalMethods] = useModal() as [any, any];
const modifiedModel = ref<string>('');
const originalValue = ref<string | undefined>('');
/** 未格式化的原始快照,供后台 stringify,避免阻塞弹窗 */
const publishPendingRaw = ref<unknown>(null);
const publishOnlineRaw = ref<unknown>(null);
const publishModalLoading = ref(false);
const showOnlyDiff = ref(true);
const publishConfirmVisible = ref(false);
const publishDescription = ref('');
const publishConfirmDate = ref(dayjs());
// 已在打开弹窗时格式化过,禁止再次 formatSnapshotJson(大快照会二次卡死)
const getOriginalValue = computed(() => originalValue.value || '{}');
const getModifiedModel = computed(() => modifiedModel.value || '{}');
watch(pricePublishShowRawJson, (open) => {
if (open) void ensurePublishJsonFormatted();
});
const handlePublishConfirm = () => {
if (publishDiffStatus.value === 'synced') {
Message.info(t('channel.salesProducts.publish.status.synced'));
return;
}
// 规则发布:沿用二次确认弹窗;价格发布走步骤 2
if (publishOperatorType.value === 'price') {
goPricePublishStep2();
return;
}
publishConfirmDate.value = dayjs();
publishConfirmVisible.value = true;
};
const handleConfirmPublish = async () => {
const pid = selectedProduct.value;
if (pid == null) return;
const operatorType = publishOperatorType.value;
if (operatorType === 'price' && !pricePublishAiReady.value) {
Message.warning(t('channel.salesProducts.ai.requireBeforePublish'));
pricePublishStep.value = 1;
return;
}
if (operatorType === 'price' && pricePublishIsHighRisk.value && !pricePublishHighRiskAck.value) {
Message.warning(t('channel.salesProducts.publish.highRiskNeedAck'));
return;
}
pricePublishSubmitting.value = true;
try {
const publishResult = await publishSalesProduct({
salesProductId: Number(pid),
operatorType,
description: publishDescription.value || undefined,
aiAnalysisReport:
operatorType === 'price' ? pricePublishAiReport.value.trim() || undefined : undefined,
});
const decision = String(
publishResult?.decision ?? publishResult?.Decision ?? '',
).trim();
const approvalNo = String(
publishResult?.approvalInstanceNo ?? publishResult?.ApprovalInstanceNo ?? '',
).trim();
if (decision === 'PendingApproval') {
Message.info(
approvalNo
? t('channel.salesProducts.publish.pendingApproval', { no: approvalNo })
: t('channel.salesProducts.publish.pendingApprovalFallback'),
);
if (operatorType === 'price') {
priceApprovalPending.value = true;
priceApprovalInstanceNo.value = approvalNo;
const approvalId =
publishResult?.approvalInstanceId ?? publishResult?.ApprovalInstanceId ?? null;
priceApprovalInstanceId.value =
typeof approvalId === 'number' && approvalId > 0 ? approvalId : null;
}
} else {
Message.success(t('channel.salesProducts.publish.success'));
}
if (operatorType === 'rules') {
configPublishPending.value = false;
rulesPublishPending.value = false;
Message.warning({
content: t('channel.salesProducts.publish.downstreamSyncTip'),
duration: 8000,
});
}
publishConfirmVisible.value = false;
publishDescription.value = '';
publishConfirmDate.value = dayjs();
clearPricePublishAiReport();
publishModalMethods.closeModal();
if (operatorType === 'price') {
await loadRecordsTabData(pid, true);
await loadPriceTabData(pid, { force: true });
await refreshPricePublishSyncStatus(pid);
} else if (decision !== 'PendingApproval') {
await loadRecordsTabData(pid, true);
}
} catch (e: any) {
Message.error(e?.message || t('channel.salesProducts.publish.fail'));
} finally {
pricePublishSubmitting.value = false;
}
};
const handleCancelPublishConfirm = () => {
publishConfirmVisible.value = false;
publishDescription.value = '';
publishConfirmDate.value = dayjs();
};
// 禁用小于当前时间的日期
const disabledDate = (current: any) => {
try {
if (!current) return false;
// 确保 current 是 dayjs 对象
const currentDate = dayjs.isDayjs(current) ? current : dayjs(current);
if (!currentDate.isValid()) return false;
const now = dayjs();
if (!now.isValid()) return false;
return currentDate.isBefore(now, 'day');
} catch (error) {
return false;
}
};
// 禁用小于当前时间的时间(如果选择的是今天)
const disabledTime = (current: any) => {
try {
if (!current || !dayjs.isDayjs(current)) return {};
const now = dayjs();
if (!now.isValid()) return {};
if (current.isSame(now, 'day')) {
// 如果是今天,禁用当前时间之前的时间
const currentHour = now.hour();
const currentMinute = now.minute();
const currentSecond = now.second();
return {
disabledHours: () => {
const hours: number[] = [];
for (let i = 0; i < currentHour; i++) {
hours.push(i);
}
return hours;
},
disabledMinutes: (selectedHour: number) => {
if (selectedHour === currentHour) {
const minutes: number[] = [];
for (let i = 0; i <= currentMinute; i++) {
minutes.push(i);
}
return minutes;
}
return [];
},
disabledSeconds: (selectedHour: number, selectedMinute: number) => {
if (selectedHour === currentHour && selectedMinute === currentMinute) {
const seconds: number[] = [];
for (let i = 0; i <= currentSecond; i++) {
seconds.push(i);
}
return seconds;
}
return [];
},
};
}
return {};
} catch (error) {
return {};
}
};
// 排货规则相关数据
const shippingScheme = ref('costLowest'); // 成本最低、时效最快、综合最优
const shippingSchemeOptions = [
{ labelKey: 'channel.salesProducts.rules.scheme.costLowest', value: 'costLowest' },
{ labelKey: 'channel.salesProducts.rules.scheme.timeFastest', value: 'timeFastest' },
{ labelKey: 'channel.salesProducts.rules.scheme.overallBest', value: 'overallBest' },
];
const shippingProviderData = ref<any[]>([]);
type RulesFormSnapshot = {
scheme: string;
providers: Array<{
serialNumber: number;
serviceChannelId: number | undefined;
weight: number;
matchCondition: string;
}>;
};
const rulesFormBaseline = ref<RulesFormSnapshot | null>(null);
function snapshotRulesForm(): RulesFormSnapshot {
return {
scheme: shippingScheme.value,
providers: shippingProviderData.value.map((row: any) => ({
serialNumber: Number(row.serialNumber ?? 0),
serviceChannelId:
row.serviceChannelId != null && row.serviceChannelId !== ''
? Number(row.serviceChannelId)
: undefined,
weight: Number(row.weight ?? 0),
matchCondition: String(row.matchCondition ?? '').trim(),
})),
};
}
function resetRulesFormBaseline() {
rulesFormBaseline.value = snapshotRulesForm();
}
const rulesFormDirty = computed(() => {
const baseline = rulesFormBaseline.value;
if (!baseline) return false;
return JSON.stringify(snapshotRulesForm()) !== JSON.stringify(baseline);
});
const canPublishRules = computed(
() => !rulesFormDirty.value && rulesPublishPending.value,
);
// 新增服务商
const handleAddShippingProvider = () => {
const newId = Math.max(...shippingProviderData.value.map((item) => item.id), 0) + 1;
shippingProviderData.value.push({
id: newId,
serialNumber: shippingProviderData.value.length + 1,
providerName: '',
serviceChannelId: undefined,
weight: shippingProviderData.value.length,
matchCondition: '',
customers: [],
});
};
// 删除服务商
const handleDeleteShippingProvider = (index: number) => {
shippingProviderData.value.splice(index, 1);
// 重新编号
shippingProviderData.value.forEach((item, idx) => {
item.serialNumber = idx + 1;
});
};
const matchConditionModalVisible = ref(false);
const matchConditionDraft = ref('');
const matchConditionEditingRow = ref<any>(null);
function matchConditionSummary(row: any) {
const formula = String(row?.matchCondition ?? '').trim();
if (formula) return formula;
const legacy = row?.customers;
if (Array.isArray(legacy) && legacy.length > 0) {
return t('channel.salesProducts.table.providers.matchConditionLegacy');
}
return t('channel.salesProducts.table.providers.matchConditionAll');
}
function openMatchConditionEditor(row: any) {
matchConditionEditingRow.value = row;
matchConditionDraft.value = String(row?.matchCondition ?? '').trim();
matchConditionModalVisible.value = true;
}
function confirmMatchConditionEditor() {
if (matchConditionEditingRow.value) {
matchConditionEditingRow.value.matchCondition = String(matchConditionDraft.value ?? '').trim();
matchConditionEditingRow.value.customers = [];
}
matchConditionModalVisible.value = false;
matchConditionEditingRow.value = null;
}
function closeMatchConditionEditor() {
matchConditionModalVisible.value = false;
matchConditionEditingRow.value = null;
}
// 发布记录相关数据
const publishRecordActiveIndex = ref(0);
const publishRecordTab = ref('price'); // price 或 rules
const publishRecordTabItems = computed(() => [
{
key: 'price',
label: t('channel.salesProducts.publish.tabs.price'),
badge: priceData.value.length || undefined,
},
{
key: 'rules',
label: t('channel.salesProducts.publish.tabs.rules'),
badge: rulesData.value.length || undefined,
},
]);
const publishDateVisible = ref(false);
const publishDate = ref();
const priceData = ref<any[]>([]);
const rulesData = ref<any[]>([]);
// 当前显示的列表数据
const currentListData = computed(() => {
return publishRecordTab.value === 'price' ? priceData.value : rulesData.value;
});
// 当前选中的发布记录
const currentPublishRecord = computed(() => {
const list = currentListData.value;
return list[publishRecordActiveIndex.value] || {};
});
const hasCurrentPublishRecord = computed(() => {
const rec = currentPublishRecord.value as Record<string, any>;
return rec != null && rec.id != null;
});
/** 选中行若已是当前生效版本,则不可再回滚到该版本 */
const canRollbackPublishRecord = computed(() => {
const rec = currentPublishRecord.value as Record<string, any>;
if (!rec || rec.id == null) return false;
const list = currentListData.value as Record<string, any>[];
const effectiveRow = list.find((item) => isPublishRecordEffectiveRow(item));
if (effectiveRow != null && Number(effectiveRow.id) === Number(rec.id)) return false;
return true;
});
function publishRecordStatusMeta(status: unknown) {
if (status === '生效') {
return { label: t('channel.salesProducts.publish.status.publish'), className: 'type-effective' };
}
if (status === '回滚') {
return { label: t('channel.salesProducts.publish.status.rollback'), className: 'type-rollback' };
}
return {
label: status == null || status === '' ? '--' : String(status),
className: 'type-invalid',
};
}
// 切换发布记录
const handleChangePublishRecordIndex = (index: number) => {
publishRecordActiveIndex.value = index;
void ensureActivePublishRecordContent();
};
// 切换标签页
const handleChangePublishRecordTab = (tab: string) => {
publishRecordTab.value = tab;
publishRecordActiveIndex.value = 0;
void ensureActivePublishRecordContent();
};
// 发布操作 - 弹出日期选择器
const handlePublish = () => {
publishDateVisible.value = true;
};
// 确认发布日期
const handleConfirmPublishDate = (date: any) => {
if (date) {
Message.success(`发布成功,日期:${date}`);
publishDateVisible.value = false;
publishDate.value = undefined;
} else {
Message.warning('请选择发布日期');
}
};
/** 是否为「线上生效」的发布记录(兼容后端 PascalCase / 枚举) */
function isPublishRecordEffectiveRow(row: Record<string, any> | undefined): boolean {
if (!row) return false;
const s = row.status ?? row.Status;
if (s === '生效') return true;
if (typeof s === 'string' && ['effective', 'active', 'published'].includes(s.toLowerCase())) return true;
if (s === 1 || s === '1') return true;
return false;
}
// 回滚到此版本(POST /channel/sales-product/publish/rollback)
const handleRollbackToVersion = () => {
const pid = selectedProduct.value;
const rec = currentPublishRecord.value as Record<string, any>;
if (pid == null) {
Message.warning('请先选择产品');
return;
}
if (!rec || rec.id == null) {
Message.warning('请先选择一个版本');
return;
}
// 仅当选中行就是「当前生效」那条时禁止(避免后端给每条都标生效时误伤全部)
const list = currentListData.value as Record<string, any>[];
const effectiveRow = list.find((item) => isPublishRecordEffectiveRow(item));
if (effectiveRow != null && Number(effectiveRow.id) === Number(rec.id)) {
Message.warning('当前选中版本为线上生效版本,无需回滚');
return;
}
Modal.confirm({
title: '确认回滚',
content: `确定要回滚到版本 "${rec.version}" 吗?`,
onOk: async () => {
try {
const operatorType = publishRecordTab.value === 'rules' ? 'rules' : 'price';
await rollbackSalesProductPublish({
salesProductId: Number(pid),
recordId: rec.id,
operatorType,
});
Message.success('回滚成功');
publishRecordActiveIndex.value = 0;
await loadRecordsTabData(Number(pid), true);
} catch (e: any) {
Message.error(e?.message || '回滚失败');
}
},
});
};
// 格式化JSON内容用于显示
const formattedJsonContent = computed(() => {
const content = currentPublishRecord.value.content || '';
try {
// 如果内容是JSON字符串,尝试格式化
const parsed = JSON.parse(content);
return JSON.stringify(parsed, null, 2);
} catch {
// 如果不是有效的JSON,直接返回原内容
return content;
}
});
const effectiveVersion = ref('--');
const effectiveTime = ref('--');
const priceTableData = ref<any[]>([]);
// 价格配置弹窗相关
const priceModalVisible = ref(false);
const priceDrawerActiveTab = ref('basic');
const priceListMergeSame = ref(false);
const priceDrawerTabList = [
{ key: 'basic', labelKey: 'channel.salesProducts.drawer.tabs.basic' },
{ key: 'priceList', labelKey: 'channel.salesProducts.drawer.tabs.priceList' },
];
/** 两个 tab 共用固定内容区高度,仅价格表内部滚动 */
const PRICE_LIST_HOT_HEIGHT = 550;
// 编辑模式
const isEditMode = ref(false);
const editingPriceRecord = ref<any>(null);
// 基础信息表单数据
const basicInfoForm = reactive({
costItem: '',
costUnit: '',
currency: '',
chargingCondition: '无',
});
const costItemOptions = computed(() =>
mapDictToSelectOptions('fee_item').filter((o) => !isDiscountCostItem(o.value)),
);
/** 费用项 → 必须先在产品勾选的附加服务 code(与字典约定一致) */
const COST_ITEM_REQUIRED_ADDITIONAL_SERVICE: Record<string, string> = {
insurance: 'insurance',
proxyPacking: 'proxyPacking',
};
function requiredAdditionalServiceCode(costItem: string): string | null {
const code = String(costItem ?? '').trim();
if (!code) return null;
const mapped = COST_ITEM_REQUIRED_ADDITIONAL_SERVICE[code]
?? COST_ITEM_REQUIRED_ADDITIONAL_SERVICE[code.toLowerCase()];
if (mapped) return mapped;
// 兼容字典大小写不一致
const hit = Object.entries(COST_ITEM_REQUIRED_ADDITIONAL_SERVICE).find(
([k]) => k.toLowerCase() === code.toLowerCase(),
);
return hit?.[1] ?? null;
}
function productSupportsAdditionalService(serviceCode: string): boolean {
const needle = String(serviceCode ?? '').trim().toLowerCase();
if (!needle) return true;
return formData.additionalServices.some(
(c) => String(c ?? '').trim().toLowerCase() === needle,
);
}
function additionalServiceLabel(serviceCode: string): string {
return dictLabelByType('additional_service', serviceCode) || serviceCode;
}
function isCostItemMissingAdditionalService(costItem: string): boolean {
const required = requiredAdditionalServiceCode(costItem);
if (!required) return false;
return !productSupportsAdditionalService(required);
}
function costItemOptionDisabledReason(costItem: string): string {
if (isCostItemAlreadyUsed(costItem)) {
return t('channel.salesProducts.drawer.form.costItemDisabled.alreadyUsed');
}
const required = requiredAdditionalServiceCode(costItem);
if (required && !productSupportsAdditionalService(required)) {
return t('channel.salesProducts.drawer.form.costItemDisabled.needAdditionalService', {
service: additionalServiceLabel(required),
});
}
return '';
}
function defaultChargingConditionForCostItem(costItem: string): string | null {
const required = requiredAdditionalServiceCode(costItem);
if (!required) return null;
return `附加服务包含('${required}')`;
}
function applyDefaultChargingConditionIfNeeded(costItem: string) {
const next = defaultChargingConditionForCostItem(costItem);
if (!next) return;
const current = String(basicInfoForm.chargingCondition ?? '').trim();
if (!current || current === '无') {
basicInfoForm.chargingCondition = next;
}
}
watch(
() => basicInfoForm.costItem,
(costItem) => {
if (!costItem) return;
applyDefaultChargingConditionIfNeeded(costItem);
},
);
/** 同一产品下已占用的费用项(编辑当前条时排除自身) */
function isCostItemAlreadyUsed(costItem: string) {
const code = String(costItem ?? '').trim().toLowerCase();
if (!code) return false;
const editingId = isEditMode.value ? editingPriceRecord.value?.id : null;
return priceTableData.value.some((row: any) => {
if (editingId != null && row?.id === editingId) return false;
return String(row?.costItem ?? '').trim().toLowerCase() === code;
});
}
const costUnitOptions = computed(() => mapDictToSelectOptions('cost_unit'));
const currencyOptions = computed(() => mapDictToSelectOptions('currency'));
const factorOptions = computed(() => {
const fromDict = mapDictToSelectOptions('pricing_factor').map((opt) => ({
value: opt.value,
label: pricingFactorColumnLabel(opt.value),
}));
// 字典未加载全时仍保证常见因素可选
const seen = new Set(fromDict.map((o) => o.value));
for (const [code, label] of Object.entries(PRICING_FACTOR_LABEL_FALLBACK)) {
if (!seen.has(code)) {
fromDict.push({ value: code, label });
}
}
return fromDict;
});
const calculationFormulaOptions = computed(() => mapDictToSelectOptions('calculation_formula'));
/** 保险费 / 燃油附加费:费用项旁问号配置说明 */
const costItemConfigHelpKey = computed(() => {
const code = String(basicInfoForm.costItem ?? '').trim();
if (!code) return '';
const label = dictLabelByType('fee_item', code) || code;
const blob = `${code} ${label}`.toLowerCase();
if (
code === 'insurance'
|| blob.includes('insurance')
|| label.includes('保险')
) {
return 'channel.salesProducts.drawer.form.costItemHelp.insurance';
}
if (
code === 'fuelSurcharge'
|| blob.includes('fuelsurcharge')
|| blob.includes('fuel')
|| label.includes('燃油')
) {
return 'channel.salesProducts.drawer.form.costItemHelp.fuelSurcharge';
}
return '';
});
const getDefaultBillingFactorsData = () => {
const preferred = [
{ code: 'zone', names: ['价格分区', '分区'] },
{ code: 'weight', names: ['重量'] },
{ code: 'customer', names: ['客户', '客户组'] },
];
const rows = dictRowsOfType('pricing_factor');
const resolveFactor = (pref: { code: string; names: string[] }): string => {
const byCode = rows.find((r) => r.dictCode === pref.code);
if (byCode?.dictCode) return byCode.dictCode;
for (const name of pref.names) {
const hit = rows.find((r) => r.dictName === name || r.dictCode === name);
if (hit?.dictCode) return hit.dictCode;
}
return pref.code;
};
return preferred.map((pref, index) => ({
id: index + 1,
serialNumber: index + 1,
factor: resolveFactor(pref),
factorValues: [] as string[],
}));
};
// 计费因素数据
const billingFactorsData = ref(getDefaultBillingFactorsData().map(item => ({ ...item })));
function normalizeBillingFactorsFromApi(factors: any): Array<{ id: number; serialNumber: number; factor: string; factorValues: string[] }> {
if (!Array.isArray(factors) || factors.length === 0) {
return getDefaultBillingFactorsData().map((item) => ({ ...item }));
}
return factors.map((item: any, index: number) => ({
id: item?.id ?? index + 1,
serialNumber: item?.serialNumber ?? index + 1,
factor: item?.factor ?? item?.name ?? '',
factorValues: item?.factorValues ?? item?.values ?? [],
}));
}
// 新增价格配置
const handleAddPrice = async () => {
await Promise.all([
ensureSalesPriceDictLoaded(),
loadBillingFactorSelectOptions(),
]);
// 重置编辑模式
isEditMode.value = false;
editingPriceRecord.value = null;
// 重置表单
Object.assign(basicInfoForm, {
costItem: '',
costUnit: '',
currency: '',
chargingCondition: '无',
});
// 重置计费因素数据为默认值
billingFactorsData.value = getDefaultBillingFactorsData().map(item => ({ ...item }));
// 重置价格表数据
replacePriceListData([]);
priceListCustomerCodesSnapshot.value = [];
clearPriceListChecked();
priceDrawerActiveTab.value = 'basic';
priceModalVisible.value = true;
// 初始化拖拽排序
nextTick(() => {
initSortable();
});
};
/** 计费因素去重键:同义词(如 zone/价格分区)视为同一因素 */
function billingFactorDedupKey(factor: string): string {
const s = String(factor ?? '').trim();
if (!s) return '';
if (isPartitionValueFactor(s)) return 'zone';
if (isRemotePartitionValueFactor(s)) return 'remoteZone';
if (isWarehouseValueFactor(s)) return 'warehouse';
if (isWeightValueFactor(s)) return 'weight';
if (isCustomerGroupValueFactor(s) || isCustomerFactor(s)) return 'customer';
if (isCargoTypeValueFactor(s)) return 'cargo';
return s;
}
function isBillingFactorAlreadyUsed(factor: string, currentRowId?: number): boolean {
const key = billingFactorDedupKey(factor);
if (!key) return false;
return billingFactorsData.value.some(
(r) =>
r.id !== currentRowId
&& billingFactorDedupKey(String(r.factor ?? '')) === key,
);
}
function isBillingFactorOptionDisabled(optionValue: string, currentRow: { id: number; factor?: string }) {
const key = billingFactorDedupKey(optionValue);
if (!key) return false;
// 当前行已选中的项保持可选,便于回显
if (billingFactorDedupKey(String(currentRow?.factor ?? '')) === key) return false;
return isBillingFactorAlreadyUsed(optionValue, currentRow?.id);
}
function handleBillingFactorChange(row: { id: number; factor?: string; factorValues?: string[] }, value: string) {
if (!value) return;
if (isBillingFactorAlreadyUsed(value, row.id)) {
Message.warning('该因素已存在,不能重复添加');
row.factor = '';
row.factorValues = [];
}
}
const billingFactorsTableRef = ref<any>(null);
const billingFactorColumns = computed(() => [
{
field: 'sort',
title: t('channel.salesProducts.drawer.table.billingFactors.serialNo'),
className: 'sort',
width: 52,
align: 'center',
slots: { default: 'sort' },
},
{
field: 'factor',
title: t('channel.salesProducts.drawer.table.billingFactors.factor'),
width: 140,
slots: { default: 'factor' },
},
{
field: 'factorValues',
title: t('channel.salesProducts.drawer.table.billingFactors.factorValues'),
minWidth: 420,
showOverflow: false,
slots: { default: 'factorValues' },
},
{
field: 'action',
title: t('channel.salesProducts.drawer.table.billingFactors.actions'),
width: 64,
align: 'center',
showOverflow: false,
slots: { default: 'action' },
},
]);
/** 容器贴底后,把实测高度写进 TablePro,避免只拉高外壳留白 */
const billingFactorsTableWrapRef = ref<HTMLElement | null>(null);
const billingFactorsTableHeight = ref(220);
let billingFactorsResizeObserver: ResizeObserver | null = null;
let billingFactorsHeightRaf = 0;
function applyBillingFactorsTableHeight(h: number) {
if (h < 120) return;
billingFactorsTableHeight.value = h;
const table = billingFactorsTableRef.value;
table?.setHeight?.(h);
nextTick(() => {
const grid = table?.xGrid;
if (grid && typeof grid.recalculate === 'function') {
grid.recalculate(true);
}
});
}
function syncBillingFactorsTableHeight(force = false) {
const el = billingFactorsTableWrapRef.value;
if (!el) return;
const h = Math.floor(el.clientHeight || el.getBoundingClientRect().height);
if (h < 120) return;
if (!force && Math.abs(h - billingFactorsTableHeight.value) < 2) return;
applyBillingFactorsTableHeight(h);
}
function setupBillingFactorsResizeObserver() {
billingFactorsResizeObserver?.disconnect();
billingFactorsResizeObserver = null;
if (billingFactorsHeightRaf) {
cancelAnimationFrame(billingFactorsHeightRaf);
billingFactorsHeightRaf = 0;
}
const el = billingFactorsTableWrapRef.value;
if (!el || typeof ResizeObserver === 'undefined') return;
billingFactorsResizeObserver = new ResizeObserver(() => {
if (billingFactorsHeightRaf) cancelAnimationFrame(billingFactorsHeightRaf);
billingFactorsHeightRaf = requestAnimationFrame(() => {
billingFactorsHeightRaf = 0;
syncBillingFactorsTableHeight();
syncFactorValuesCellWidth();
});
});
billingFactorsResizeObserver.observe(el);
nextTick(() => {
syncBillingFactorsTableHeight(true);
syncFactorValuesCellWidth();
setTimeout(() => {
syncBillingFactorsTableHeight(true);
syncFactorValuesCellWidth();
}, 80);
});
}
const billingFactorsTableProps = computed(() => ({
columns: billingFactorColumns.value,
isCellSort: false,
showToolbar: false,
isColumnsDrag: false,
showPager: false,
showIndex: false,
data: billingFactorsData.value,
minHeight: 120,
keepSource: true,
size: 'small',
useForm: false,
autoHeight: false,
height: billingFactorsTableHeight.value,
tableConfig: {
height: billingFactorsTableHeight.value,
},
toolbarConfig: { setting: false, enabled: false },
rowConfig: { isHover: true, keyField: 'id', height: 52 },
scrollY: { enabled: true, gt: 0 },
}));
function refreshBillingFactorsTable() {
nextTick(() => {
syncBillingFactorsTableHeight();
billingFactorsTableRef.value?.reloadData?.(billingFactorsData.value);
initSortable();
});
}
// 新增计费因素行
const handleAddBillingFactor = () => {
const newId = Math.max(...billingFactorsData.value.map((item) => item.id), 0) + 1;
billingFactorsData.value.push({
id: newId,
serialNumber: billingFactorsData.value.length + 1,
factor: '',
factorValues: [],
});
if (priceModalVisible.value && priceDrawerActiveTab.value === 'basic') {
refreshBillingFactorsTable();
}
};
// 删除计费因素行
const handleDeleteBillingFactor = (row: { id: number } | number) => {
const index =
typeof row === 'number'
? row
: billingFactorsData.value.findIndex((item) => item.id === row.id);
if (index < 0) return;
billingFactorsData.value.splice(index, 1);
billingFactorsData.value.forEach((item, idx) => {
item.serialNumber = idx + 1;
});
if (priceModalVisible.value && priceDrawerActiveTab.value === 'basic') {
refreshBillingFactorsTable();
}
};
// 添加因素值弹窗
const addFactorValueModalVisible = ref(false);
const addFactorValueSelected = ref<string[]>([]);
const currentFactorRow = ref<any>(null);
const currentFactorValueOptions = computed(() => {
const factor = currentFactorRow.value?.factor;
if (!factor) return [];
const base = factorValuesOptionsByFactor.value[factor] || [];
if (!isCustomerGroupValueFactor(factor)) return base;
const selected = addFactorValueSelected.value.map((v) => String(v));
const hasAll = selected.some(isAllCustomerCode);
return base.map((opt) => {
const isAll = isAllCustomerCode(opt.value) || isAllCustomerCode(opt.label);
return {
...opt,
disabled: hasAll ? !isAll : false,
};
});
});
const isAllFactorValuesSelected = computed(() => {
const options = currentFactorValueOptions.value.filter((o) => !(o as any).disabled);
if (options.length === 0) return false;
return options.every((option) => addFactorValueSelected.value.includes(option.value));
});
function handleAddFactorValueSelectedChange(vals: string[]) {
const factor = currentFactorRow.value?.factor;
if (factor && isCustomerGroupValueFactor(factor)) {
addFactorValueSelected.value = normalizeCustomerFactorSelection(vals || []);
return;
}
const next = vals || [];
addFactorValueSelected.value =
factor && isWeightValueFactor(factor) ? sortFactorValuesBySize(next) : next;
}
// 添加因素值
const handleAddFactorValue = (row: any) => {
if (!row?.factor) {
Message.warning('请先选择因素');
return;
}
currentFactorRow.value = row;
const factor = row.factor as string;
const opts = factorValuesOptionsByFactor.value[factor] || [];
if (
opts.length === 0
&& isCustomerGroupValueFactor(factor)
&& customerGroupValueOptions.value.length === 0
) {
Message.warning('未加载到客户组字典(customer_group),请先导入 OMS 预置字典后重试');
}
const allowed = new Set(opts.map((o) => String(o.value)));
const canonical = toCanonicalFactorValues(factor, row.factorValues || []);
const selected = canonical
.map((v) => String(v).trim())
.filter((v) => v && allowed.has(v));
addFactorValueSelected.value = isWeightValueFactor(factor)
? sortFactorValuesBySize(selected)
: selected;
addFactorValueModalVisible.value = true;
};
function resetAddFactorValueModal() {
addFactorValueModalVisible.value = false;
addFactorValueSelected.value = [];
currentFactorRow.value = null;
}
/** 将弹窗内勾选的因素值写入当前行;forbidEmpty 为 true 且无勾选时提示并返回 false */
function commitAddFactorSelections(opts: { forbidEmpty: boolean }): boolean {
let selectedValues = addFactorValueSelected.value || [];
const factor = currentFactorRow.value?.factor as string | undefined;
if (factor && isCustomerGroupValueFactor(factor)) {
selectedValues = normalizeCustomerFactorSelection(selectedValues);
// 全部客户与其它互斥:直接覆盖为规范化结果
if (selectedValues.some(isAllCustomerCode)) {
if (!currentFactorRow.value) return false;
currentFactorRow.value.factorValues = selectedValues;
Message.success('添加成功');
return true;
}
}
if (selectedValues.length === 0) {
if (opts.forbidEmpty) {
Message.warning('请至少选择一个因素值');
}
return false;
}
if (!currentFactorRow.value) return false;
const existing = new Set(currentFactorRow.value.factorValues || []);
// 若已有全部客户,再加具体组时清掉全部客户
if (factor && isCustomerGroupValueFactor(factor) && selectedValues.some((v) => !isAllCustomerCode(v))) {
currentFactorRow.value.factorValues = (currentFactorRow.value.factorValues || []).filter(
(v: string) => !isAllCustomerCode(v),
);
}
const existingAfter = new Set(currentFactorRow.value.factorValues || []);
const toAdd = selectedValues.filter((value) => !existingAfter.has(value));
if (toAdd.length === 0) {
Message.warning(existing.size ? '所选因素值均已存在' : '请至少选择一个因素值');
return false;
}
currentFactorRow.value.factorValues.push(...toAdd);
if (factor && isCustomerGroupValueFactor(factor)) {
currentFactorRow.value.factorValues = normalizeCustomerFactorSelection(
currentFactorRow.value.factorValues,
);
}
if (factor && isWeightValueFactor(factor)) {
currentFactorRow.value.factorValues = sortFactorValuesBySize(
currentFactorRow.value.factorValues,
);
}
Message.success('添加成功');
return true;
}
// 确认添加因素值
const handleConfirmAddFactorValue = () => {
if (!commitAddFactorSelections({ forbidEmpty: true })) return;
resetAddFactorValueModal();
};
/** 点击遮罩关闭时:按当前勾选提交(无勾选则仅关闭);点取消/X/ESC 仍丢弃 */
function handleAddFactorValueModalCancel(e?: Event) {
const el = e && 'target' in e ? ((e as MouseEvent).target as HTMLElement | null) : null;
const fromMask = !!el?.classList?.contains('arco-modal-wrapper');
if (fromMask) {
commitAddFactorSelections({ forbidEmpty: false });
resetAddFactorValueModal();
return;
}
resetAddFactorValueModal();
}
const handleSelectAllFactorValues = () => {
if (isAllFactorValuesSelected.value) {
addFactorValueSelected.value = [];
return;
}
const factor = currentFactorRow.value?.factor;
const enabled = currentFactorValueOptions.value
.filter((option) => !(option as any).disabled)
.map((option) => option.value);
// 全选具体客户组时排除「全部客户」,避免互斥折叠成只剩 all
addFactorValueSelected.value =
factor && isCustomerGroupValueFactor(factor)
? normalizeCustomerFactorSelection(enabled.filter((v) => !isAllCustomerCode(v)))
: factor && isWeightValueFactor(factor)
? sortFactorValuesBySize(enabled)
: enabled;
};
// 拖拽排序相关
let sortableInstance: any = null;
// 初始化拖拽排序(TablePro / vxe-table tbody)
const initSortable = () => {
if (sortableInstance) {
sortableInstance.destroy();
sortableInstance = null;
}
nextTick(() => {
void (async () => {
const root = billingFactorsTableRef.value?.$el as HTMLElement | undefined;
const tbody = root?.querySelector(
'.body--wrapper>.vxe-table--body tbody',
) as HTMLElement | null;
if (!tbody) return;
const { default: Sortable } = await import('sortablejs');
sortableInstance = Sortable.create(tbody, {
handle: '.sort',
animation: 150,
onEnd: (evt: any) => {
const { oldIndex, newIndex } = evt;
if (oldIndex === newIndex || oldIndex === undefined || newIndex === undefined) return;
const movedItem = billingFactorsData.value.splice(oldIndex, 1)[0];
billingFactorsData.value.splice(newIndex, 0, movedItem);
billingFactorsData.value.forEach((item, idx) => {
item.serialNumber = idx + 1;
});
billingFactorsTableRef.value?.reloadData?.(billingFactorsData.value);
},
});
})();
});
};
// 删除因素值
const handleDeleteFactorValue = (row: any, valueIndex: number) => {
row.factorValues.splice(valueIndex, 1);
};
/** 因素值列可用宽度(随表格 resize 更新),用于按字符宽动态算可见标签数 */
const factorValuesCellWidth = ref(520);
function syncFactorValuesCellWidth() {
const el = billingFactorsTableWrapRef.value;
if (!el) return;
const cell = el.querySelector('.factor-values-cell') as HTMLElement | null;
const w = cell?.clientWidth || estimateFactorValuesColumnWidth(el.clientWidth);
if (w > 0 && Math.abs(w - factorValuesCellWidth.value) > 2) {
factorValuesCellWidth.value = w;
}
}
function getFactorValuePreview(row: any) {
const values = Array.isArray(row?.factorValues) ? row.factorValues : [];
const items = values.map((value: string, index: number) => {
const label = formatFactorValueTagDisplay(row.factor, value) || String(value ?? '');
return { value, index, label };
});
const limit = resolveVisibleFactorValueCount(
items.map((it) => it.label),
factorValuesCellWidth.value,
);
return {
items,
visible: items.slice(0, limit),
extraCount: Math.max(0, items.length - limit),
};
}
// 价格表数据:shallowRef + 普通对象,避免上千行 deep 响应式拖垮 Handsontable
const priceListData = shallowRef<any[]>([]);
function replacePriceListData(rows: any[]) {
priceListData.value = (rows || []).map((row) => ({
...row,
checked: !!(row as any)?.checked,
}));
}
/** 换新数组引用,触发 Handsontable 浅监听刷新(行对象可复用) */
function touchPriceListData() {
priceListData.value = priceListData.value.slice();
}
/** 当前价格表行对应的客户组编码顺序(用于同步时按编码保留价格) */
const priceListCustomerCodesSnapshot = ref<string[]>([]);
const priceListSelectedIds = ref<number[]>([]);
/** 上次非空选中(点工具栏时 HOT 可能先清空当前选中) */
const lastPriceListSelectedIds = ref<number[]>([]);
const batchFillTargetIds = ref<number[]>([]);
const priceListHotRef = ref<{ selectAll: () => void; clearSelection: () => void } | null>(null);
const batchFillModalVisible = ref(false);
const batchFillValue = ref<number | undefined>(undefined);
function buildPriceRowFactorKey(row: any, factorColKeys: string[]): string {
return factorColKeys.map((k) => String(row?.[k] ?? '').trim()).join('\u0001');
}
function capturePriceListCustomerCodesSnapshot() {
priceListCustomerCodesSnapshot.value = getSelectedCustomerGroupCodesFromBilling();
}
function buildEmptyCustomerPrices(codes: string[]): Record<string, number> {
const out: Record<string, number> = {};
codes.forEach((_, i) => {
out[`customer_${i}`] = 0;
});
return out;
}
function extractCustomerPricesByCode(row: any, codes: string[]): Record<string, number> {
const map: Record<string, number> = {};
codes.forEach((code, i) => {
const raw = row?.[`customer_${i}`];
const n = Number(raw);
map[code] = Number.isFinite(n) ? n : 0;
});
return map;
}
function applyCustomerPricesByCode(
row: any,
newCodes: string[],
priceByCode: Record<string, number>
) {
newCodes.forEach((code, i) => {
row[`customer_${i}`] = priceByCode[code] ?? 0;
});
}
// 价格表列顺序(表头):[ 非客户计费因素列… ] → [ 计算公式 ] → [ 客户组列… ]
// 客户组列表头为 customer_group.dictName,且整段客户组列紧跟在「计算公式」列之后(右侧)
const priceTableHeaders = computed(() => {
type H = { key: string; label: string; isCustomer: boolean; factorIndex?: number };
const rows = priceListData.value;
const factorHeaders: H[] = [];
for (let i = 0; i < billingFactorsData.value.length; i++) {
const factor = billingFactorsData.value[i];
if (!factor.factor || isCustomerFactor(factor.factor)) continue;
const colKey = `factor_${i}`;
const hasMappedValues = factor.factorValues.length > 0;
const hasRowValues =
!hasMappedValues
&& rows.some((row) => {
const v = (row as any)?.[colKey];
return v != null && String(v).trim() !== '';
});
if (hasMappedValues || hasRowValues) {
factorHeaders.push({
key: colKey,
label: pricingFactorColumnLabel(factor.factor),
isCustomer: false,
factorIndex: i,
});
}
}
const formulaHeader: H = {
key: 'calculationFormula',
label: '计算公式',
isCustomer: false,
};
const customerGroupHeaders: H[] = [];
const selectedCg = getSelectedCustomerGroupCodesFromBilling();
if (selectedCg.length > 0) {
selectedCg.forEach((code, index) => {
customerGroupHeaders.push({
key: `customer_${index}`,
label: customerGroupPriceTableHeaderLabel(code, index),
isCustomer: true,
});
});
} else {
let maxIdx = -1;
for (const row of rows) {
if (!row || typeof row !== 'object') continue;
for (const k of Object.keys(row as object)) {
const m = /^customer_(\d+)$/.exec(k);
if (m) maxIdx = Math.max(maxIdx, Number(m[1]));
}
}
for (let index = 0; index <= maxIdx; index++) {
customerGroupHeaders.push({
key: `customer_${index}`,
label: `客户组${index + 1}`,
isCustomer: true,
});
}
}
return [...factorHeaders, formulaHeader, ...customerGroupHeaders];
});
// 按计费因素同步价格表:已有组合保留价格,仅补新增行
const syncPriceListData = (opts?: { dropMissing?: boolean }) => {
const dropMissing = opts?.dropMissing !== false;
const nonCustomerFactors = billingFactorsData.value.filter(
(item) => item.factor && !isCustomerFactor(item.factor) && item.factorValues.length > 0
);
if (nonCustomerFactors.length === 0) {
Message.warning('请至少配置一个非客户因素');
return null;
}
const generateCombinations = (arrays: string[][]): string[][] => {
if (arrays.length === 0) return [[]];
if (arrays.length === 1) return arrays[0].map((item) => [item]);
const [first, ...rest] = arrays;
const restCombinations = generateCombinations(rest);
const result: string[][] = [];
for (const firstItem of first) {
for (const restCombination of restCombinations) {
result.push([firstItem, ...restCombination]);
}
}
return result;
};
const factorValueArrays = nonCustomerFactors.map((factor) => factor.factorValues);
const combinations = generateCombinations(factorValueArrays);
const factorColKeys = nonCustomerFactors.map((factor) => {
const colIdx = billingFactorsData.value.findIndex((item) => item.id === factor.id);
return `factor_${colIdx}`;
});
const oldCodes = priceListCustomerCodesSnapshot.value.length
? [...priceListCustomerCodesSnapshot.value]
: getSelectedCustomerGroupCodesFromBilling();
const newCodes = getSelectedCustomerGroupCodesFromBilling();
const oldByKey = new Map<string, any>();
for (const row of priceListData.value) {
const key = buildPriceRowFactorKey(row, factorColKeys);
if (!key || key.split('\u0001').every((p) => !p)) continue;
if (!oldByKey.has(key)) oldByKey.set(key, row);
}
const newData: any[] = [];
let kept = 0;
let added = 0;
combinations.forEach((combination, index) => {
const row: any = {
id: index + 1,
calculationFormula: defaultCalculationFormulaDisplay(),
...buildEmptyCustomerPrices(newCodes),
};
nonCustomerFactors.forEach((factor, factorIndex) => {
const colIdx = billingFactorsData.value.findIndex((item) => item.id === factor.id);
const raw = combination[factorIndex];
row[`factor_${colIdx}`] = isWeightValueFactor(factor.factor)
? weightValueToIntervalCell(raw, factor.factorValues)
: raw;
});
const key = buildPriceRowFactorKey(row, factorColKeys);
const oldRow = oldByKey.get(key);
if (oldRow) {
kept += 1;
row.calculationFormula = oldRow.calculationFormula || row.calculationFormula;
const priceByCode = extractCustomerPricesByCode(oldRow, oldCodes);
applyCustomerPricesByCode(row, newCodes, priceByCode);
oldByKey.delete(key);
} else {
added += 1;
}
newData.push(row);
});
const removed = dropMissing ? oldByKey.size : 0;
if (!dropMissing && oldByKey.size > 0) {
// 保留未匹配旧行(极端兜底,默认不会走)
let nextId = newData.length + 1;
for (const oldRow of oldByKey.values()) {
newData.push({ ...oldRow, id: nextId++ });
}
}
return { newData, kept, added, removed };
};
const applySyncedPriceList = (result: {
newData: any[];
kept: number;
added: number;
removed: number;
}) => {
replacePriceListData(result.newData.map((row) => ({ ...row, checked: false })));
capturePriceListCustomerCodesSnapshot();
clearPriceListChecked();
priceDrawerActiveTab.value = 'priceList';
const parts = [`保留 ${result.kept} 行`, `新增 ${result.added} 行`];
if (result.removed > 0) parts.push(`移除 ${result.removed} 行`);
Message.success(`价格表已同步(${parts.join(',')})`);
};
// 同步价格表结构(保留已有价格)
const handleGeneratePriceList = async () => {
await ensureSalesPriceDictLoaded();
const preview = syncPriceListData({ dropMissing: true });
if (!preview) return;
if (preview.removed > 0 && priceListData.value.length > 0) {
Modal.confirm({
title: '同步价格表',
content: `将新增 ${preview.added} 行、移除 ${preview.removed} 行。被移除行的已填价格会丢失,是否继续?`,
okText: '继续同步',
cancelText: '取消',
onOk: () => {
applySyncedPriceList(preview);
},
});
return;
}
applySyncedPriceList(preview);
};
/** 与文档 /channel/sales-product/price/create 的 factors 一致:serialNumber、factor、factorValues */
function buildSalesProductFactorsForApi(): Array<{
serialNumber: number;
factor: string;
factorValues: string[];
}> {
return billingFactorsData.value
.filter((item) => item.factor)
.map((item, idx) => ({
serialNumber: item.serialNumber ?? idx + 1,
factor: item.factor,
factorValues: toCanonicalFactorValues(item.factor, item.factorValues),
}));
}
/**
* 与文档 details 一致:factorValuesJson、calculationFormula、calculatedValue、customerGroupValues
* (与服务渠道买价 buildServiceChannelDetailsPayload 同构)
*/
function buildSalesProductPriceDetailsForApi(): any[] {
if (!priceListData.value.length) return [];
return priceListData.value.map((row: any, index: number) => {
const factorValuesJson: Record<string, string> = {};
for (let i = 0; i < billingFactorsData.value.length; i++) {
const bf = billingFactorsData.value[i];
if (!bf.factor || isCustomerFactor(bf.factor)) continue;
const colKey = `factor_${i}`;
const v = row[colKey];
const nameKey = pricingFactorColumnLabel(bf.factor);
let cellVal = v != null && String(v).trim() !== '' ? String(v) : '';
if (cellVal && isWeightValueFactor(bf.factor)) {
cellVal = canonicalWeightFactorCellForApi(cellVal, bf.factorValues ?? []);
}
factorValuesJson[nameKey] = cellVal;
}
const cgCodes = getSelectedCustomerGroupCodesFromBilling();
const customerGroupValues: Record<string, number> = {};
cgCodes.forEach((code, idx) => {
const label = customerGroupPriceTableHeaderLabel(code, idx);
customerGroupValues[label] = Number(row[`customer_${idx}`]) || 0;
});
return {
id: row.id ?? index + 1,
factorValuesJson,
calculationFormula: formulaLabelToCode(
row.calculationFormula || defaultCalculationFormulaDisplay(),
),
calculatedValue: Number(row.calculatedValue ?? 0) || 0,
customerGroupValues,
};
});
}
/** 将 list 接口返回的 details(含 factorValuesJson)还原为弹窗内价格表行 */
function mapSalesProductDetailsToPriceListRows(details: any[]): any[] {
if (!Array.isArray(details)) return [];
return details.map((item: any, index: number) => {
if (item?.factorValuesJson && typeof item.factorValuesJson === 'object') {
const row: any = {
id: item.id ?? index + 1,
calculationFormula: formulaCodeToLabel(
item.calculationFormula || defaultCalculationFormulaCode(),
),
calculatedValue: item.calculatedValue,
checked: false,
};
const fj = item.factorValuesJson as Record<string, string>;
for (let i = 0; i < billingFactorsData.value.length; i++) {
const bf = billingFactorsData.value[i];
if (!bf.factor || isCustomerFactor(bf.factor)) continue;
const label = pricingFactorColumnLabel(bf.factor);
const raw = fj[label] ?? fj[bf.factor] ?? '';
row[`factor_${i}`] = isWeightValueFactor(bf.factor)
? weightValueToIntervalCell(String(raw), bf.factorValues ?? [])
: raw;
}
const cgs = item.customerGroupValues;
if (cgs && typeof cgs === 'object') {
const codes = getSelectedCustomerGroupCodesFromBilling();
codes.forEach((code, idx) => {
const lab = customerGroupPriceTableHeaderLabel(code, idx);
row[`customer_${idx}`] = Number(cgs[lab]) || 0;
});
}
return row;
}
return {
id: item?.id ?? index + 1,
...item,
calculationFormula: formulaCodeToLabel(
item?.calculationFormula || defaultCalculationFormulaCode(),
),
checked: false,
};
});
}
function buildPricePayload(pid: number) {
const priceName =
dictLabelByType('fee_item', basicInfoForm.costItem) || basicInfoForm.costItem || '';
return {
salesProductId: pid,
serialNumber: isEditMode.value && editingPriceRecord.value?.serialNumber
? editingPriceRecord.value.serialNumber
: priceTableData.value.length + 1,
status: isEditMode.value && editingPriceRecord.value
? toEnableStatus(!!editingPriceRecord.value.status)
: toEnableStatus(true),
priceName,
costItem: basicInfoForm.costItem,
costUnit: basicInfoForm.costUnit,
currency: basicInfoForm.currency,
chargingCondition: basicInfoForm.chargingCondition || '',
factors: buildSalesProductFactorsForApi(),
details: buildSalesProductPriceDetailsForApi(),
};
}
async function submitPriceConfig(pid: number) {
const payload = buildPricePayload(pid);
if (isEditMode.value && editingPriceRecord.value?.id) {
await updateSalesProductPrice({
...payload,
id: editingPriceRecord.value.id,
});
return '价格配置更新成功';
}
const created = await createSalesProductPrice(payload);
const createdId = created?.id ?? created?.Id;
if (createdId != null) {
isEditMode.value = true;
editingPriceRecord.value = {
...(editingPriceRecord.value || {}),
id: createdId,
serialNumber: payload.serialNumber,
status: isEnableStatusEnabled(payload.status),
};
} else {
// 兼容后端不返回 id:用唯一组合定位刚新增记录,切成编辑态避免下次重复 create
await loadPriceTabData(pid, { force: true });
const latest = [...priceTableData.value]
.reverse()
.find((row: any) => row.serialNumber === payload.serialNumber && row.costItem === payload.costItem);
if (latest?.id != null) {
isEditMode.value = true;
editingPriceRecord.value = latest;
}
}
return '价格配置添加成功';
}
// 保存价格表
const handleSavePriceList = async () => {
const pid = selectedProduct.value;
if (pid == null) {
Message.warning('请先选择产品');
return;
}
if (!basicInfoForm.costItem?.trim()) {
Message.warning('请先填写费用项');
return;
}
if (isCostItemAlreadyUsed(basicInfoForm.costItem)) {
Message.warning('该产品已存在此费用项,同一产品下每种费用项只能有一条');
return;
}
const requiredService = requiredAdditionalServiceCode(basicInfoForm.costItem);
if (requiredService && !productSupportsAdditionalService(requiredService)) {
Message.warning(
t('channel.salesProducts.drawer.form.costItemBlocked.needAdditionalService', {
service: additionalServiceLabel(requiredService),
}),
);
return;
}
try {
const msg = await submitPriceConfig(pid);
Message.success(msg);
await loadPriceTabData(pid, { force: true });
priceModalVisible.value = false;
} catch (e: any) {
Message.error(e?.message || '保存失败');
}
};
// 导出价格表到Excel
const handleExportPriceList = async () => {
try {
const XLSX = await import('xlsx');
// 准备表头数据
const headers = priceTableHeaders.value.map((h) => h.label);
// 准备表格数据(所有行都导出,合并的单元格只在第一行显示值)
const tableData: any[] = [];
const merges: Array<{ s: { r: number; c: number }; e: { r: number; c: number } }> = [];
const rowSpanLookup = buildFactorRowSpanLookup();
priceListData.value.forEach((row: any, rowIndex: number) => {
const rowData: any = {};
priceTableHeaders.value.forEach((header, colIndex) => {
if (header.key.startsWith('factor_')) {
// 因素列:只在需要合并的第一行显示值(与表格展示一致:名称而非编码/id)
const rowSpan = getFactorRowSpan(header.key, rowIndex, rowSpanLookup);
if (rowSpan > 0) {
// 这是合并的第一行,显示值
rowData[header.label] = formatPriceTableFactorCell(
header.factorIndex,
String((row as any)[header.key] ?? ''),
);
if (rowSpan > 1) {
// 需要合并:从当前行(rowIndex+1,因为第0行是表头)到rowIndex+rowSpan-1
merges.push({
s: { r: rowIndex + 1, c: colIndex }, // +1 因为第0行是表头
e: { r: rowIndex + rowSpan, c: colIndex }, // rowIndex + rowSpan 是最后一行(包含)
});
}
} else {
// 这是合并的其他行,留空(Excel会自动处理合并)
rowData[header.label] = '';
}
} else if (header.key === 'calculationFormula') {
rowData[header.label] = row.calculationFormula || '';
} else if (header.isCustomer) {
rowData[header.label] = (row as any)[header.key] || 0;
}
});
tableData.push(rowData);
});
// 创建工作簿
const wb = XLSX.utils.book_new();
const ws = XLSX.utils.json_to_sheet(tableData);
// 设置合并单元格
if (merges.length > 0) {
ws['!merges'] = merges;
}
// 设置列宽
const colWidths = headers.map(() => ({ wch: 15 }));
ws['!cols'] = colWidths;
// 添加工作表到工作簿
XLSX.utils.book_append_sheet(wb, ws, '价格表');
// 导出文件
const fileName = `${basicInfoForm.costItem || '价格表'}_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`;
XLSX.writeFile(wb, fileName);
Message.success('导出成功');
} catch (error) {
Message.error('导出失败,请重试');
}
};
// 导入价格表
const handleImportPriceList = () => {
// 创建文件输入元素
const input = document.createElement('input');
input.type = 'file';
input.accept = '.xlsx,.xls';
input.onchange = (e: any) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event: any) => {
void (async () => {
try {
const XLSX = await import('xlsx');
const data = new Uint8Array(event.target.result);
const workbook = XLSX.read(data, { type: 'array' });
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
// 转换为JSON
const jsonData = XLSX.utils.sheet_to_json(worksheet);
if (jsonData.length === 0) {
Message.warning('Excel文件为空');
return;
}
// 转换数据格式
const importedData = jsonData.map((row: any, index) => {
const formulaRaw =
row[priceTableHeaders.value.find((h) => h.key === 'calculationFormula')?.label || '']
|| defaultCalculationFormulaDisplay();
const newRow: any = {
id: index + 1,
calculationFormula: formulaCodeToLabel(formulaLabelToCode(String(formulaRaw))),
checked: false,
};
// 设置因素值和客户组
priceTableHeaders.value.forEach((header) => {
if (header.key !== 'calculationFormula') {
if (header.isCustomer) {
newRow[header.key] = Number(row[header.label]) || 0;
} else {
newRow[header.key] = row[header.label] || '';
}
}
});
return newRow;
});
replacePriceListData(importedData);
coercePriceListRowsFactorCells();
capturePriceListCustomerCodesSnapshot();
clearPriceListChecked();
touchPriceListData();
Message.success('导入成功');
} catch (error) {
Message.error('导入失败,请检查文件格式');
}
})();
};
reader.readAsArrayBuffer(file);
};
input.click();
};
const priceListHotColumns = computed<PriceListHotColumn[]>(() => {
// 下拉只展示字典中文名;单元格统一存展示名,保存时再 formulaLabelToCode
const formulaSource = Array.from(
new Set(
calculationFormulaOptions.value
.map((o) => String(o.label || o.value || '').trim())
.filter(Boolean),
),
);
if (!formulaSource.length) {
const fallback = defaultCalculationFormulaDisplay();
if (fallback) formulaSource.push(fallback);
}
return priceTableHeaders.value.map((header) => {
if (header.key.startsWith('factor_')) {
const factorIndex = header.factorIndex;
return {
key: header.key,
label: header.label,
width: 120,
readOnly: true,
type: 'text' as const,
formatter: (row: any) =>
formatPriceTableFactorCell(factorIndex, String(row?.[header.key] ?? '')),
};
}
if (header.key === 'calculationFormula') {
return {
key: header.key,
label: header.label,
width: 140,
type: 'dropdown' as const,
source: formulaSource,
};
}
return {
key: header.key,
label: header.label,
width: 110,
type: 'numeric' as const,
};
});
});
/** 仅列结构变化时重挂载 */
const priceListHotTableKey = computed(
() => `price-hot-${priceListHotColumns.value.map((c) => c.key).join('|')}`,
);
function onPriceListSelectionChange(ids: Array<number | string>) {
const next = ids.map((id) => Number(id)).filter((id) => Number.isFinite(id));
priceListSelectedIds.value = next;
if (next.length) lastPriceListSelectedIds.value = next;
}
function resolvePriceListSelectedIds() {
if (priceListSelectedIds.value.length) return [...priceListSelectedIds.value];
return [...lastPriceListSelectedIds.value];
}
function clearPriceListChecked() {
priceListSelectedIds.value = [];
lastPriceListSelectedIds.value = [];
batchFillTargetIds.value = [];
try {
priceListHotRef.value?.clearSelection?.();
} catch {
// Handsontable / mergeCells 未就绪时忽略
}
}
function selectAllPriceListRows() {
try {
priceListHotRef.value?.selectAll?.();
} catch {
/* ignore */
}
}
function clearAllPriceListRowsSelection() {
try {
priceListHotRef.value?.clearSelection?.();
} catch {
/* ignore */
}
}
const openBatchFillModal = () => {
const ids = resolvePriceListSelectedIds();
if (!ids.length) {
Message.warning('请先选中要填价的行');
return;
}
batchFillTargetIds.value = ids;
batchFillValue.value = undefined;
batchFillModalVisible.value = true;
};
const handleConfirmBatchFill = () => {
const val = Number(batchFillValue.value);
if (!Number.isFinite(val) || val < 0) {
Message.warning('请输入有效价格(≥0)');
return;
}
const selected = new Set(
batchFillTargetIds.value.length
? batchFillTargetIds.value
: resolvePriceListSelectedIds(),
);
const customerKeys = priceTableHeaders.value.filter((h) => h.isCustomer).map((h) => h.key);
if (!customerKeys.length) {
Message.warning('当前没有客户组价格列');
return;
}
let touched = 0;
for (const row of priceListData.value) {
if (!selected.has(row.id)) continue;
for (const key of customerKeys) {
(row as any)[key] = val;
touched += 1;
}
}
batchFillModalVisible.value = false;
batchFillTargetIds.value = [];
// 触发 Handsontable 刷新可视区(数值已写回源对象)
touchPriceListData();
Message.success(touched ? `已填充 ${touched} 个价格格` : '没有需要填充的格子');
};
// 取消
const handleCancelPriceDrawer = () => {
priceModalVisible.value = false;
// 重置编辑模式
isEditMode.value = false;
editingPriceRecord.value = null;
clearPriceListChecked();
// 清理拖拽实例
if (sortableInstance) {
sortableInstance.destroy();
sortableInstance = null;
}
};
// 检查是否可以切换到价格表tab(已有明细行时允许进入,便于编辑时查看接口返回的 priceList)
const canSwitchToPriceList = computed(() => {
if (priceListData.value.length > 0) return true;
return billingFactorsData.value.some(
(item) => item.factor && !isCustomerFactor(item.factor) && item.factorValues.length > 0
);
});
// 处理tab切换
const handlePriceDrawerTabSwitch = async (tabKey: string) => {
if (tabKey === 'priceList' && !canSwitchToPriceList.value) {
Message.warning('请配置计费因素和映射值,点击「同步价格表」');
return;
}
if (tabKey === 'priceList') {
await ensureSalesPriceDictLoaded();
normalizePriceListFormulaDisplays();
}
priceDrawerActiveTab.value = tabKey;
if (tabKey === 'basic' && priceModalVisible.value) {
nextTick(() => {
initSortable();
});
}
};
watch(
() => [priceModalVisible.value, priceDrawerActiveTab.value] as const,
([visible, tab]) => {
if (visible && tab === 'basic') {
nextTick(() => {
setupBillingFactorsResizeObserver();
initSortable();
});
return;
}
billingFactorsResizeObserver?.disconnect();
billingFactorsResizeObserver = null;
if (sortableInstance) {
sortableInstance.destroy();
sortableInstance = null;
}
}
);
onBeforeUnmount(() => {
if (billingFactorsHeightRaf) {
cancelAnimationFrame(billingFactorsHeightRaf);
billingFactorsHeightRaf = 0;
}
billingFactorsResizeObserver?.disconnect();
billingFactorsResizeObserver = null;
if (priceListHeightRaf) {
cancelAnimationFrame(priceListHeightRaf);
priceListHeightRaf = 0;
}
priceListResizeObserver?.disconnect();
priceListResizeObserver = null;
if (sortableInstance) {
sortableInstance.destroy();
sortableInstance = null;
}
});
/** 导出 Excel 用:按需计算 rowspan,不做成 computed,避免大表持续重算 */
function buildFactorRowSpanLookup(): Map<string, number> {
const lookup = new Map<string, number>();
const rows = priceListData.value;
const factorHeaders = priceTableHeaders.value.filter((h) => h.key.startsWith('factor_'));
if (!rows.length || !factorHeaders.length) return lookup;
for (let col = 0; col < factorHeaders.length; col++) {
const headerKey = factorHeaders[col].key;
let i = 0;
while (i < rows.length) {
const currentRow = rows[i] as any;
const currentValue = currentRow?.[headerKey];
if (currentValue === undefined || currentValue === '') {
lookup.set(`${headerKey}:${i}`, 0);
i += 1;
continue;
}
let end = i + 1;
while (end < rows.length) {
const nextRow = rows[end] as any;
if (nextRow?.[headerKey] !== currentValue) break;
let prefixMatch = true;
for (let p = 0; p < col; p++) {
const pk = factorHeaders[p].key;
if (nextRow?.[pk] !== (rows[i] as any)?.[pk]) {
prefixMatch = false;
break;
}
}
if (!prefixMatch) break;
end += 1;
}
lookup.set(`${headerKey}:${i}`, end - i);
for (let k = i + 1; k < end; k++) {
lookup.set(`${headerKey}:${k}`, 0);
}
i = end;
}
}
return lookup;
}
function getFactorRowSpan(headerKey: string, rowIndex: number, lookup?: Map<string, number>) {
const map = lookup ?? buildFactorRowSpanLookup();
return map.get(`${headerKey}:${rowIndex}`) ?? 0;
}
/** 明细行里 factor_i 与计费因素对齐,将名称/旧值统一为 id 或字典编码 */
function coercePriceListRowsFactorCells() {
const rows = billingFactorsData.value;
for (const prow of priceListData.value) {
if (!prow || typeof prow !== 'object') continue;
rows.forEach((bf, i) => {
const k = `factor_${i}`;
if (!Object.prototype.hasOwnProperty.call(prow, k)) return;
const cur = (prow as any)[k];
if (cur == null || String(cur).trim() === '') return;
if (isWeightValueFactor(bf.factor)) {
const next = weightValueToIntervalCell(String(cur), bf.factorValues ?? []);
if (next) (prow as any)[k] = next;
return;
}
const [next] = toCanonicalFactorValues(bf.factor, [String(cur)]);
if (next != null && String(next).trim() !== '') (prow as any)[k] = next;
});
}
}
const priceEditPreparing = ref(false);
/** 价格表内计算公式统一成字典名,保证 dropdown source 能匹配、不会点开被滤空/清空 */
function normalizePriceListFormulaDisplays() {
for (const row of priceListData.value) {
if (!row || typeof row !== 'object') continue;
row.calculationFormula = formulaCodeToLabel(
formulaLabelToCode(String(row.calculationFormula ?? '')),
);
}
}
function applyPriceEditSourceRecord(sourceRecord: any) {
billingFactorsData.value = normalizeBillingFactorsFromApi(sourceRecord?.factors);
for (const row of billingFactorsData.value) {
row.factorValues = toCanonicalFactorValues(row.factor, row.factorValues);
}
replacePriceListData(mapSalesProductDetailsToPriceListRows(sourceRecord?.details || []));
coercePriceListRowsFactorCells();
normalizePriceListFormulaDisplays();
capturePriceListCustomerCodesSnapshot();
priceListSelectedIds.value = [];
void nextTick(() => clearPriceListChecked());
if (priceModalVisible.value && priceDrawerActiveTab.value === 'basic') {
refreshBillingFactorsTable();
}
}
async function activateEditPriceListTab() {
await nextTick();
await new Promise<void>((resolve) => {
requestAnimationFrame(() => resolve());
});
if (!priceModalVisible.value || !isEditMode.value) return;
// 编辑场景默认进入价格表(详情异步回填后也要切过去)
priceDrawerActiveTab.value = 'priceList';
}
// 编辑价格配置(先开弹窗再填数据,避免串行接口 + 大表同步挂载卡死)
const handleEditPrice = async (record: any) => {
if (priceEditPreparing.value) return;
priceEditPreparing.value = true;
try {
isEditMode.value = true;
editingPriceRecord.value = record;
Object.assign(basicInfoForm, {
costItem: record.costItem || '',
costUnit: record.costUnit || '',
currency: record.currency || '',
chargingCondition: record.chargingCondition || '无',
});
// 列表行已带 factors/details,先本地回填并立刻打开弹窗(勿在 HT 挂载前 clear)
billingFactorsData.value = normalizeBillingFactorsFromApi(record?.factors);
replacePriceListData(mapSalesProductDetailsToPriceListRows(record?.details || []));
coercePriceListRowsFactorCells();
capturePriceListCustomerCodesSnapshot();
priceListSelectedIds.value = [];
// 列表行常无 details:先开基础信息保证即时反馈,数据就绪后再切价格表
priceDrawerActiveTab.value = 'basic';
priceModalVisible.value = true;
await Promise.all([
ensureSalesPriceDictLoaded(),
loadBillingFactorSelectOptions(),
]);
applyPriceEditSourceRecord(record);
normalizePriceListFormulaDisplays();
await activateEditPriceListTab();
// 列表默认不含 details:按需拉单条完整配置
const hasLocalDetails = Array.isArray(record?.details) && record.details.length > 0;
if (hasLocalDetails || record?.id == null) return;
try {
const matched = await getSalesProductPrice(record.id);
if (!priceModalVisible.value || editingPriceRecord.value?.id !== record?.id) return;
if (matched) {
applyPriceEditSourceRecord(matched);
await activateEditPriceListTab();
}
} catch (e: any) {
Message.warning(e?.message || '加载最新价格配置失败,已使用列表数据回填');
}
} finally {
priceEditPreparing.value = false;
}
};
// 删除价格配置确认弹窗
const deletePriceModalVisible = ref(false);
const deletePriceInput = ref('');
const deletingPriceRecord = ref<any>(null);
// 删除价格配置
const handleDeletePrice = (record: any) => {
deletingPriceRecord.value = record;
deletePriceInput.value = '';
deletePriceModalVisible.value = true;
};
// 确认删除价格配置(落库 POST /channel/sales-product/price/delete)
const handleConfirmDeletePrice = async () => {
if (!deletingPriceRecord.value) return;
const record = deletingPriceRecord.value;
const typed = String(deletePriceInput.value ?? '').trim();
const correctNames = [
record.priceName,
record.costItem,
dictLabelByType('fee_item', record.costItem),
]
.map((x) => String(x ?? '').trim())
.filter(Boolean);
if (!correctNames.includes(typed)) {
Message.error('输入的费用项名称不正确,请重新输入');
return;
}
const productId = selectedProduct.value;
const priceId = record.id;
if (priceId == null) {
Message.error('删除失败,未找到该记录');
return;
}
try {
await deleteSalesProductPrice(priceId);
Message.success('删除成功');
deletePriceModalVisible.value = false;
deletingPriceRecord.value = null;
deletePriceInput.value = '';
if (productId != null) await loadPriceTabData(productId, { force: true });
} catch (e: any) {
Message.error(e?.message || '删除失败');
}
};
// 取消删除价格配置
const handleCancelDeletePrice = () => {
deletePriceModalVisible.value = false;
deletingPriceRecord.value = null;
deletePriceInput.value = '';
};
// 切换卖价费用项状态(落库 POST /channel/sales-product/price/toggleStatus)
const handleTogglePriceStatus = async (record: any) => {
const pid = selectedProduct.value
if (pid == null || record?.id == null) return
try {
await toggleSalesProductPriceStatus(record.id, toEnableStatus(!!record.status))
await loadPriceTabData(pid, { force: true })
} catch (e: any) {
record.status = !record.status
Message.error(e?.message || '更新失败')
}
}
// 产品卖价列表(TablePro):字典编码展示用 slot
const priceListTableRef = ref<any>(null);
const priceTableContainerRef = ref<HTMLElement | null>(null);
const priceListTableHeight = ref(400);
let priceListResizeObserver: ResizeObserver | null = null;
let priceListHeightRaf = 0;
function applyPriceListTableHeight(h: number, force = false) {
if (h < 160) return;
if (!force && Math.abs(h - priceListTableHeight.value) < 2) return;
priceListTableHeight.value = h;
// 只改高度,避免强制 recalculate 造成切产品卡顿
priceListTableRef.value?.setHeight?.(h);
}
function syncPriceListTableHeight(force = false) {
const el = priceTableContainerRef.value;
if (!el) return;
const h = Math.floor(el.clientHeight || el.getBoundingClientRect().height);
applyPriceListTableHeight(h, force);
}
function setupPriceListResizeObserver() {
if (priceListResizeObserver) return;
if (priceListHeightRaf) {
cancelAnimationFrame(priceListHeightRaf);
priceListHeightRaf = 0;
}
const el = priceTableContainerRef.value;
if (!el || typeof ResizeObserver === 'undefined') return;
priceListResizeObserver = new ResizeObserver(() => {
if (priceListHeightRaf) cancelAnimationFrame(priceListHeightRaf);
priceListHeightRaf = requestAnimationFrame(() => {
priceListHeightRaf = 0;
syncPriceListTableHeight();
});
});
priceListResizeObserver.observe(el);
nextTick(() => syncPriceListTableHeight(true));
}
const priceColumns = computed(() => [
{
field: 'serialNumber',
title: t('channel.salesProducts.table.providers.serialNo'),
width: 72,
align: 'center',
},
{
field: 'status',
title: t('channel.salesProducts.table.price.status'),
width: 100,
align: 'center',
slots: { default: 'status' },
},
{
field: 'costItem',
title: t('channel.salesProducts.drawer.form.costItem'),
minWidth: 120,
slots: { default: 'costItemCell' },
},
{
field: 'costUnit',
title: t('channel.salesProducts.drawer.form.costUnit'),
width: 100,
align: 'center',
slots: { default: 'costUnitCell' },
},
{
field: 'currency',
title: t('channel.salesProducts.drawer.form.currency'),
width: 100,
align: 'center',
slots: { default: 'currencyCell' },
},
{
field: 'billingFactors',
title: t('channel.salesProducts.drawer.section.billingFactors'),
minWidth: 200,
showOverflow: true,
slots: { default: 'billingFactorsCell' },
},
{
field: 'modifyTime',
title: '修改时间',
width: 180,
},
{
field: 'modifier',
title: '修改人',
width: 100,
},
{
field: 'action',
title: t('channel.salesProducts.table.providers.actions'),
width: 120,
align: 'center',
fixed: 'right',
slots: { default: 'operations' },
},
]);
// 高度走 setHeight,数据走 reloadData,避免 computed 随 height/data 重建触发 TablePro 重绑
const priceListTableProps = computed(() => ({
columns: priceColumns.value,
showPager: false,
showToolbar: false,
showIndex: false,
isCellSort: false,
isColumnsDrag: false,
useForm: false,
autoHeight: false,
keepSource: true,
size: 'small',
tableConfig: { height: 400 },
toolbarConfig: { setting: false, enabled: false },
rowConfig: { isHover: true, keyField: 'id' },
}));
watch(
priceTableData,
(rows) => {
nextTick(() => {
priceListTableRef.value?.reloadData?.(rows || []);
});
},
{ deep: false },
);
// 仅在卖价 tab 可见时监听高度。切走用 display:none 保留表格实例,回来重算布局即可
watch(
() => [activeTab.value, selectedProduct.value] as const,
([tab, productId]) => {
if (tab !== 'price' || productId == null) {
priceListResizeObserver?.disconnect();
priceListResizeObserver = null;
return;
}
nextTick(() => {
setupPriceListResizeObserver();
syncPriceListTableHeight(true);
const grid = priceListTableRef.value?.xGrid;
const visible = grid?.getTableData?.()?.fullData;
// display:none 期间表格可能丢行,有缓存就补回去,避免切回看到空表
if (priceTableData.value.length > 0 && (!Array.isArray(visible) || visible.length === 0)) {
priceListTableRef.value?.reloadData?.(priceTableData.value);
}
grid?.recalculate?.(true);
});
},
{ immediate: true },
);
</script>
<template>
<div class="sales-product-layout">
<!-- 左侧产品列表:使用公共组件 CustomLeftMenu -->
<div class="left-sidebar">
<CustomLeftMenu
:tree-data="productTreeData"
:selected-keys="productSelectedKeys"
v-model:expanded-keys="productExpandedKeys"
v-model:search-keyword="searchKeyword"
:search-placeholder="t('channel.salesProducts.search.placeholder')"
:refresh-title="t('channel.salesProducts.search.refresh')"
:add-title="t('channel.salesProducts.search.addProduct')"
:show-node-index="true"
:show-method="false"
:show-map-count="false"
:show-node-code="false"
:show-node-actions="true"
:delete-label="t('channel.salesProducts.actions.delete')"
@search="handleSearch"
@refresh="handleSearch"
@add="handleAddProduct"
@select="handleProductSelectFromTree"
@delete-node="(nodeData) => {
const product = productList.find((p: any) => p.id === nodeData?.id);
if (product) handleDeleteProduct(product);
}"
>
<template #node-second-row-extra="{ nodeData }">
<div class="product-second-row">
<span class="modify-time">修改: {{ nodeData?.updateTime || '--' }}</span>
<span
class="switch-swipe-wrapper"
@click.capture.stop="() => {
const product = productList.find((p: any) => p.id === nodeData?.id);
if (product) { product.isActive = !product.isActive; handleToggleProduct(product); }
}"
@touchstart.passive="onStatusSwipeStart"
@touchend="(e) => onProductSwitchSwipeEnd(nodeData, e)"
>
<a-switch
:model-value="nodeData?.isActive"
size="small"
type="circle"
class="product-active-switch"
checked-color="#00b42a"
unchecked-color="#f53f3f"
/>
</span>
</div>
</template>
</CustomLeftMenu>
</div>
<!-- 右侧产品配置 -->
<div class="right-content content-panel">
<!-- 标签页 -->
<div class="tabs-section">
<SlidingTabs
:model-value="activeTab"
:items="slidingTabItems"
@change="handleTabChange"
/>
<div v-if="selectedProduct != null && activeTab === 'config'" class="tabs-toolbar">
<a-space :size="8">
<a-button
size="small"
:loading="savingConfig"
:disabled="!configFormDirty"
@click="handleSaveConfig"
>
{{ t('channel.salesProducts.actions.save') }}
</a-button>
<a-button
type="primary"
size="small"
:loading="savingConfig"
:disabled="!canPublishConfig"
@click="handlePublishConfig"
>
{{ t('channel.salesProducts.actions.publishConfig') }}
</a-button>
</a-space>
</div>
<div v-else-if="selectedProduct != null && activeTab === 'rules'" class="tabs-toolbar">
<a-space :size="8">
<a-button
size="small"
:loading="savingConfig"
:disabled="!rulesFormDirty"
@click="handleSaveRules"
>
{{ t('channel.salesProducts.actions.save') }}
</a-button>
<a-button
type="primary"
size="small"
:loading="savingConfig"
:disabled="!canPublishRules"
@click="handlePublishRules"
>
{{ t('channel.salesProducts.actions.publishRules') }}
</a-button>
</a-space>
</div>
<div v-else-if="selectedProduct != null && activeTab === 'price'" class="tabs-toolbar">
<a-space :size="8">
<template v-if="priceApprovalPending">
<a-button type="primary" size="small" @click="openPriceApprovalDrawer">
{{ t('channel.salesProducts.actions.viewPriceApproval') }}
</a-button>
</template>
<template v-else-if="priceApprovalExecuteFailed">
<a-button
type="primary"
size="small"
:loading="priceApprovalRetryLoading"
@click="retryPriceApprovalExecute"
>
{{ t('channel.salesProducts.actions.retryPriceApprovalExecute') }}
</a-button>
<a-button size="small" @click="openPriceApprovalDrawer">
{{ t('channel.salesProducts.actions.viewPriceApproval') }}
</a-button>
<a-button
size="small"
:loading="publishModalLoading"
@click="handlePublishPrice"
>
{{ t('channel.salesProducts.actions.resubmitPriceApproval') }}
</a-button>
</template>
<template v-else-if="priceApprovalFailed">
<a-button
type="primary"
size="small"
:loading="publishModalLoading"
@click="handlePublishPrice"
>
{{ t('channel.salesProducts.actions.resubmitPriceApproval') }}
</a-button>
<a-button size="small" @click="openPriceApprovalDrawer">
{{ t('channel.salesProducts.actions.viewPriceApproval') }}
</a-button>
</template>
<a-button
v-else
type="primary"
size="small"
:loading="publishModalLoading"
@click="handlePublishPrice"
>
{{ t('channel.salesProducts.actions.publishPrice') }}
</a-button>
</a-space>
</div>
</div>
<div v-if="selectedProduct != null && selectedProductContext" class="product-context-bar">
<span class="context-item">
<span class="context-label">{{ t('channel.salesProducts.context.product') }}:</span>
<span class="context-value">{{ selectedProductContext.productName }}</span>
<span v-if="selectedProductContext.productCode" class="context-code">({{ selectedProductContext.productCode }})</span>
</span>
<span class="context-divider">|</span>
<span class="context-item">
<span class="context-label">{{ t('channel.salesProducts.context.group') }}:</span>
<span class="context-value">{{ selectedProductContext.groupName }}</span>
</span>
<span class="context-divider">|</span>
<span class="context-item">
<span class="context-label">{{ t('channel.salesProducts.context.updateTime') }}:</span>
<span class="context-value">{{ selectedProductContext.updateTime }}</span>
</span>
<span class="context-divider">|</span>
<span class="context-item">
<span class="context-label">{{ t('channel.salesProducts.context.updateBy') }}:</span>
<span class="context-value">{{ selectedProductContext.updateBy }}</span>
</span>
<a-tag
v-if="(activeTab === 'config' && configFormDirty) || (activeTab === 'rules' && rulesFormDirty)"
color="orangered"
size="small"
class="context-dirty-tag"
>
{{ t('channel.salesProducts.context.unsaved') }}
</a-tag>
<a-tag
v-else-if="activeTab === 'config' && configPublishPending"
color="arcoblue"
size="small"
class="context-dirty-tag"
>
{{ t('channel.salesProducts.context.publishPending') }}
</a-tag>
<a-tag
v-else-if="activeTab === 'rules' && rulesPublishPending"
color="arcoblue"
size="small"
class="context-dirty-tag"
>
{{ t('channel.salesProducts.context.rulesPublishPending') }}
</a-tag>
</div>
<div v-if="selectedProduct == null" class="empty-state-panel">
<div class="empty-state">
<p>{{ t('channel.salesProducts.empty.selectProduct') }}</p>
</div>
</div>
<template v-else>
<!-- 产品卖价:切走不卸载,避免回来空表再等接口 -->
<div v-show="activeTab === 'price'" class="price-section">
<div
v-if="priceApprovalPending"
class="price-approval-banner is-waiting"
>
<div class="price-approval-banner-main">
<div class="price-approval-banner-title">
{{ t('channel.salesProducts.publish.waitingBannerTitle') }}
</div>
<div class="price-approval-banner-desc">
{{
priceApprovalInstanceNo
? t('channel.salesProducts.publish.waitingBannerDesc', {
no: priceApprovalInstanceNo,
})
: t('channel.salesProducts.publish.waitingBannerDescNoNo')
}}
</div>
</div>
<div class="price-approval-banner-actions">
<a-button type="primary" size="small" @click="openPriceApprovalDrawer">
{{ t('channel.salesProducts.publish.viewProgress') }}
</a-button>
<a-button size="small" @click="openPriceApprovalDrawer">
{{ t('channel.salesProducts.publish.withdrawHint') }}
</a-button>
</div>
</div>
<div
v-else-if="priceApprovalFailed"
class="price-approval-banner is-failed"
>
<div class="price-approval-banner-main">
<div class="price-approval-banner-title">
{{ t('channel.salesProducts.publish.failedBannerTitle') }}
</div>
<div class="price-approval-banner-desc">
{{
priceApprovalInstanceNo
? t('channel.salesProducts.publish.failedBannerDesc', {
status: priceApprovalStatusName || t('channel.salesProducts.publish.badge.failed'),
no: priceApprovalInstanceNo,
})
: t('channel.salesProducts.publish.failedBannerDescNoNo', {
status: priceApprovalStatusName || t('channel.salesProducts.publish.badge.failed'),
})
}}
<template v-if="priceApprovalComment">
— {{ priceApprovalComment }}
</template>
</div>
</div>
<div class="price-approval-banner-actions">
<a-button
v-if="priceApprovalExecuteFailed"
type="primary"
size="small"
:loading="priceApprovalRetryLoading"
@click="retryPriceApprovalExecute"
>
{{ t('channel.salesProducts.actions.retryPriceApprovalExecute') }}
</a-button>
<a-button
v-else
type="primary"
size="small"
:loading="publishModalLoading"
@click="handlePublishPrice"
>
{{ t('channel.salesProducts.actions.resubmitPriceApproval') }}
</a-button>
<a-button size="small" @click="openPriceApprovalDrawer">
{{ t('channel.salesProducts.actions.viewPriceApproval') }}
</a-button>
</div>
</div>
<div class="price-header">
<div class="version-info">
{{ t('channel.salesProducts.price.effectiveVersion', { version: effectiveVersion }) }}
<span style="margin-left: 16px; color: var(--color-text-3);">生效时间:{{ effectiveTime }}</span>
<a-tag
v-if="pricePublishChecking && pricePublishPending == null && !priceApprovalPending && !priceApprovalFailed"
color="gray"
size="small"
class="price-sync-tag"
>
{{ t('channel.salesProducts.publish.badge.checking') }}
</a-tag>
<a-tag
v-else-if="priceApprovalPending"
color="arcoblue"
size="small"
class="price-sync-tag price-approval-tag"
@click="openPriceApprovalDrawer"
>
{{ t('channel.salesProducts.publish.badge.pendingApproval') }}
<template v-if="priceApprovalInstanceNo">
· {{ priceApprovalInstanceNo }}
</template>
</a-tag>
<a-tag
v-else-if="priceApprovalFailed"
color="red"
size="small"
class="price-sync-tag price-approval-tag"
:title="priceApprovalComment || undefined"
@click="openPriceApprovalDrawer"
>
{{ priceApprovalFailedBadgeText }}
</a-tag>
<a-tag
v-else-if="pricePublishPending === true"
color="orangered"
size="small"
class="price-sync-tag"
>
{{ t('channel.salesProducts.publish.badge.pending') }}
</a-tag>
<a-tag
v-else-if="pricePublishPending === false"
color="green"
size="small"
class="price-sync-tag"
>
{{ t('channel.salesProducts.publish.badge.synced') }}
</a-tag>
</div>
<div class="price-header-actions">
<a-button
type="secondary"
size="small"
class="add-price-btn"
@click="billingSimulateVisible = true"
>
{{ t('channel.salesProducts.billingSimulate.open') }}
</a-button>
<a-button
type="secondary"
size="small"
class="add-price-btn"
@click="handleAddPrice"
>
<icon-plus class="btn-icon" />
{{ t('channel.salesProducts.actions.add') }}
</a-button>
</div>
</div>
<div ref="priceTableContainerRef" class="price-table-container">
<a-spin :loading="priceListLoading" class="price-list-spin">
<TablePro
ref="priceListTableRef"
v-bind="priceListTableProps"
class="price-list-table-pro"
>
<template #status="{ row }">
<div
class="switch-swipe-wrapper"
@touchstart.passive="onStatusSwipeStart"
@touchend="(e) => onStatusSwipeEnd(row, e)"
>
<a-switch
v-model="row.status"
type="circle"
size="small"
class="product-active-switch"
checked-color="#00b42a"
unchecked-color="#f53f3f"
@change="() => handleTogglePriceStatus(row)"
/>
</div>
</template>
<template #costItemCell="{ row }">
{{ dictLabelByType('fee_item', row.costItem) }}
</template>
<template #costUnitCell="{ row }">
{{ dictLabelByType('cost_unit', row.costUnit) }}
</template>
<template #currencyCell="{ row }">
{{ dictLabelByType('currency', row.currency) }}
</template>
<template #billingFactorsCell="{ row }">
{{ formatPriceTableBillingFactors(row) }}
</template>
<template #operations="{ row }">
<a-space>
<a-button
type="text"
size="small"
class="action-btn"
:title="t('channel.salesProducts.actions.edit')"
@click="handleEditPrice(row)"
>
<icon-edit />
</a-button>
<a-button
type="text"
size="small"
class="action-btn delete-btn"
:title="t('channel.salesProducts.actions.delete')"
@click="handleDeletePrice(row)"
>
<icon-delete />
</a-button>
</a-space>
</template>
</TablePro>
</a-spin>
</div>
</div>
<!-- 排货规则tab内容 -->
<div v-if="mountedTabs.rules" v-show="activeTab === 'rules'" class="shipping-rules-section">
<div class="shipping-rules-header">
<div class="scheme-selection">
<div class="scheme-title">{{ t('channel.salesProducts.rules.schemeTitle') }}</div>
<a-radio-group v-model="shippingScheme" class="scheme-radio-group">
<a-radio
v-for="option in shippingSchemeOptions"
:key="option.value"
:value="option.value"
>
{{ t(option.labelKey) }}
</a-radio>
</a-radio-group>
<span class="scheme-explanation">
{{ t('channel.salesProducts.rules.scheme.explanation') }}
</span>
</div>
<div class="shipping-rules-header-actions">
<a-button
type="secondary"
class="add-provider-btn"
@click="handleAddShippingProvider"
>
<icon-plus />
{{ t('channel.salesProducts.actions.add') }}
</a-button>
</div>
</div>
<a-spin :loading="rulesLoading" class="tab-pane-spin">
<div class="shipping-rules-content">
<div class="shipping-provider-table-container">
<table class="shipping-provider-table">
<colgroup>
<col class="shipping-col-serial" />
<col class="shipping-col-channel" />
<col class="shipping-col-weight" />
<col class="shipping-col-match-condition" />
<col class="shipping-col-actions" />
</colgroup>
<thead>
<tr>
<th>{{ t('channel.salesProducts.table.providers.serialNo') }}</th>
<th>{{ t('channel.salesProducts.table.providers.serviceChannel') }}</th>
<th>{{ t('channel.salesProducts.table.providers.weight') }}</th>
<th>{{ t('channel.salesProducts.table.providers.matchCondition') }}</th>
<th>{{ t('channel.salesProducts.table.providers.actions') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="(row, index) in shippingProviderData"
:key="row.id"
>
<td class="shipping-col-serial-cell">{{ row.serialNumber }}</td>
<td class="shipping-service-channel-cell shipping-col-channel-cell">
<a-select
v-model="row.serviceChannelId"
:options="serviceChannelSelectOptions"
allow-search
allow-clear
size="small"
class="shipping-service-channel-select"
:placeholder="t('channel.serviceChannels.form.placeholder.select')"
@change="() => syncShippingRowProviderNameFromChannel(row)"
/>
</td>
<td class="shipping-col-weight-cell">
<a-input-number
v-model="row.weight"
size="small"
style="width: 100%"
:min="0"
/>
</td>
<td class="shipping-col-match-condition-cell">
<div class="match-condition-cell">
<span
class="match-condition-summary"
:class="{
'is-empty': !String(row.matchCondition || '').trim(),
'is-legacy':
!String(row.matchCondition || '').trim() &&
Array.isArray(row.customers) &&
row.customers.length > 0,
}"
:title="matchConditionSummary(row)"
>
{{ matchConditionSummary(row) }}
</span>
<a-button
type="text"
size="small"
class="match-condition-edit-btn"
@click="openMatchConditionEditor(row)"
>
<icon-edit />
{{ t('channel.salesProducts.table.providers.matchConditionEdit') }}
</a-button>
</div>
</td>
<td class="shipping-col-actions-cell">
<a-button
type="text"
size="small"
class="action-btn delete-btn"
@click="handleDeleteShippingProvider(index)"
:title="t('channel.salesProducts.actions.delete')"
>
<icon-delete />
</a-button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</a-spin>
</div>
<!-- 对客说明 tab -->
<div v-if="mountedTabs.customerGuide" v-show="activeTab === 'customerGuide'" class="customer-guide-section">
<MarkdownDocPanel
v-if="selectedProduct != null"
ref="customerGuidePanelRef"
:content="customerGuideMarkdown"
:saving="customerGuideSaving"
:template-content="customerGuideTemplate"
:empty-hint="t('channel.salesProducts.customerGuide.empty')"
@save="handleSaveCustomerGuide"
/>
<a-empty v-else :description="t('channel.salesProducts.customerGuide.selectProduct')" />
</div>
<!-- 发布记录tab内容 -->
<div v-if="mountedTabs.records" v-show="activeTab === 'records'" class="publish-records-section">
<div class="publish-records-toolbar">
<SlidingTabs
:model-value="publishRecordTab"
:items="publishRecordTabItems"
@change="handleChangePublishRecordTab"
/>
<span class="publish-records-hint">
{{ t('channel.salesProducts.publish.recordsHint') }}
</span>
</div>
<a-spin :loading="recordsLoading" class="tab-pane-spin">
<div class="publish-records-container">
<div class="publish-records-left">
<div v-if="currentListData.length" class="version-list">
<button
v-for="(item, index) in currentListData"
:key="item.id"
type="button"
:class="['version-item', { active: publishRecordActiveIndex === index }]"
@click="handleChangePublishRecordIndex(index)"
>
<div class="version-item-header">
<span class="version-item-number">
{{ t('channel.salesProducts.publish.versionLabel', { version: item.version }) }}
</span>
<span
:class="['version-item-badge', publishRecordStatusMeta(item.status).className]"
>
{{ publishRecordStatusMeta(item.status).label }}
</span>
</div>
<div class="version-item-footer">
<span class="version-item-user">{{ item.publishUser || '--' }}</span>
<span class="version-item-time">{{ item.publishTime || '--' }}</span>
</div>
</button>
</div>
<a-empty
v-else
class="publish-records-empty"
:description="t('channel.salesProducts.publish.emptyList')"
/>
</div>
<div class="publish-records-right">
<template v-if="hasCurrentPublishRecord">
<div class="right-header">
<div class="version-notes">
<span>{{ t('channel.salesProducts.publish.versionRemark') }}</span>
<a-popover placement="top-start">
<template #content>
{{ currentPublishRecord.description || t('channel.salesProducts.publish.noRemark') }}
</template>
<template #default>
<icon-question-circle-fill class="notes-icon notes-icon--remark" />
</template>
</a-popover>
<template v-if="publishRecordTab === 'price' && currentPublishRecord.aiAnalysisReport">
<span class="ai-report-notes-label">{{ t('channel.salesProducts.ai.historyReport') }}</span>
<a-popover placement="top-start">
<template #content>
<pre class="ai-history-pre">{{ currentPublishRecord.aiAnalysisReport }}</pre>
</template>
<template #default>
<icon-question-circle-fill class="notes-icon notes-icon--ai" />
</template>
</a-popover>
</template>
</div>
<a-button
size="small"
class="rollback-btn"
:disabled="!canRollbackPublishRecord"
@click="handleRollbackToVersion"
>
{{ t('channel.salesProducts.actions.rollback') }}
</a-button>
</div>
<div class="code-content">
<a-spin :loading="publishRecordContentLoading" class="publish-record-content-spin">
<pre class="code-pre">{{ publishRecordContentLoading ? '' : (formattedJsonContent || t('channel.salesProducts.publish.emptyContent')) }}</pre>
</a-spin>
</div>
</template>
<a-empty
v-else
class="publish-records-empty"
:description="t('channel.salesProducts.publish.emptyDetail')"
/>
</div>
</div>
</a-spin>
</div>
<!-- 表单内容 -->
<div v-if="mountedTabs.config" v-show="activeTab === 'config'" class="form-section">
<div class="form-container">
<!-- 第一行 -->
<div class="form-row">
<div class="form-item">
<label class="form-label label-with-tip">
{{ t('channel.salesProducts.form.productCode') }}
<a-tooltip>
<template #content>
<div style="white-space: pre-line; max-width: 320px; line-height: 1.5;">{{ t('channel.salesProducts.tip.productCode') }}</div>
</template>
<icon-question-circle class="tip-icon" />
</a-tooltip>
<button
type="button"
class="product-code-edit-icon"
:aria-label="t('channel.salesProducts.form.editProductCode')"
@click.stop="openProductCodeModal"
>
<icon-edit />
</button>
</label>
<a-input
v-model="formData.productCode"
:placeholder="t('channel.salesProducts.placeholder.productCode')"
class="form-input"
disabled
/>
</div>
<div class="form-item">
<label class="form-label label-with-tip">
{{ t('channel.salesProducts.form.productName') }}
<a-tooltip>
<template #content>
<div style="white-space: pre-line; max-width: 320px; line-height: 1.5;">{{ t('channel.salesProducts.tip.productName') }}</div>
</template>
<icon-question-circle class="tip-icon" />
</a-tooltip>
</label>
<a-input
v-model="formData.productName"
:placeholder="t('channel.salesProducts.form.placeholder.input')"
class="form-input"
/>
</div>
<div class="form-item">
<label class="form-label">{{ t('channel.salesProducts.form.group') }}</label>
<a-select
v-model="formData.group"
:placeholder="t('channel.salesProducts.form.placeholder.select')"
class="form-select"
>
<a-option
v-for="option in groupOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</a-option>
</a-select>
</div>
</div>
<!-- 第二行 -->
<div class="form-row">
<div class="form-item">
<label class="form-label">{{ t('channel.salesProducts.form.efficiency') }}</label>
<div class="timeliness-inputs">
<a-input
v-model="formData.minTimeliness"
:placeholder="t('channel.salesProducts.form.placeholder.min')"
class="timeliness-input"
/>
<span class="timeliness-separator">-</span>
<a-input
v-model="formData.maxTimeliness"
:placeholder="t('channel.salesProducts.form.placeholder.max')"
class="timeliness-input"
/>
</div>
</div>
<div class="form-item">
<label class="form-label">{{ t('channel.salesProducts.form.tradeTerms') }}</label>
<a-select
v-model="formData.tradeTerms"
allow-clear
:placeholder="t('channel.salesProducts.form.placeholder.select')"
class="form-select"
>
<a-option value="DDP">DDP</a-option>
<a-option value="DDU">DDU</a-option>
</a-select>
</div>
<div class="form-item">
<label class="form-label" :title="t('channel.salesProducts.form.routeSortTip')">
{{ t('channel.salesProducts.form.routeSort') }}
</label>
<a-input-number
v-model="formData.routeSort"
:min="0"
:precision="0"
:placeholder="t('channel.salesProducts.form.routeSortTip')"
class="form-select"
/>
</div>
<div class="form-item">
<label class="form-label">{{ t('channel.salesProducts.form.customerWaybill') }}</label>
<a-select
v-model="formData.labelTemplateId"
class="form-select"
allow-clear
allow-search
:placeholder="t('channel.salesProducts.form.placeholder.labelTemplate')"
>
<a-option
v-for="option in labelTemplateOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</a-option>
</a-select>
</div>
</div>
<!-- 第三行 -->
<div class="form-row">
<div class="form-item">
<FormLabelWithPreview
:label="t('channel.salesProducts.form.blacklistArea')"
:has-value="!!formData.blacklistArea"
@preview="openReferencePreview('kpi-blacklist', formData.blacklistArea, blacklistAreaOptions)"
/>
<a-select
v-model="formData.blacklistArea"
:placeholder="t('channel.salesProducts.form.placeholder.select')"
class="form-select"
>
<a-option
v-for="option in blacklistAreaOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</a-option>
</a-select>
</div>
<div class="form-item">
<FormLabelWithPreview
:label="t('channel.salesProducts.form.remoteAreaDivision')"
:has-value="!!formData.remoteAreaDivision"
@preview="openReferencePreview('kpi-remote', formData.remoteAreaDivision, remoteAreaDivisionOptions)"
/>
<a-select
v-model="formData.remoteAreaDivision"
:placeholder="t('channel.salesProducts.form.placeholder.select')"
class="form-select"
>
<a-option
v-for="option in remoteAreaDivisionOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</a-option>
</a-select>
</div>
<div class="form-item">
<FormLabelWithPreview
:label="t('channel.salesProducts.form.weightCalculationRule')"
:has-value="!!formData.weightCalculationRule"
@preview="openReferencePreview('weight-rule', formData.weightCalculationRule, weightCalculationRuleOptions)"
/>
<a-select
v-model="formData.weightCalculationRule"
:placeholder="t('channel.salesProducts.form.placeholder.select')"
class="form-select"
>
<a-option
v-for="option in weightCalculationRuleOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</a-option>
</a-select>
</div>
<div class="form-item">
<FormLabelWithPreview
:label="t('channel.salesProducts.form.weightRounding')"
:has-value="!!formData.weightRounding"
@preview="openReferencePreview('weight-rounding', formData.weightRounding, weightRoundingOptions)"
/>
<a-select
v-model="formData.weightRounding"
:placeholder="t('channel.salesProducts.form.placeholder.select')"
class="form-select"
>
<a-option
v-for="option in weightRoundingOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</a-option>
</a-select>
</div>
</div>
<!-- 附加服务单独一行 -->
<div class="form-row">
<div class="form-item full-width">
<label class="form-label">{{ t('channel.salesProducts.form.additionalServices') }}</label>
<a-select
v-model="formData.additionalServices"
multiple
allow-clear
:placeholder="t('channel.salesProducts.form.placeholder.select')"
class="form-select"
:loading="salesPriceDictLoading"
>
<a-option
v-for="option in additionalServiceOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</a-option>
</a-select>
</div>
</div>
<!-- 产品说明 -->
<div class="form-row">
<div class="form-item full-width">
<label class="form-label">{{ t('channel.salesProducts.form.productDescription') }}</label>
<a-textarea
v-model="formData.productDescription"
:placeholder="t('channel.salesProducts.form.productDescription')"
:rows="4"
class="form-textarea"
/>
</div>
</div>
<!-- 第五行 -->
<div class="form-row">
<div class="form-item full-width">
<PreScriptEditor
v-model="formData.preStorageScript"
:label="t('channel.salesProducts.form.preStorageScript')"
:label-tip="t('channel.salesProducts.tip.preStorageScript')"
:placeholder="t('channel.salesProducts.placeholder.preStorageScript')"
:rows="5"
:skill-scene="PRE_STORAGE_SCRIPT_AI_SCENE"
:default-skill-key="PRE_STORAGE_SCRIPT_AI_DEFAULT_SKILL_KEY"
:storage-key="PRE_STORAGE_SCRIPT_AI_STORAGE_KEY"
:chat-scene="PRE_STORAGE_SCRIPT_AI_CHAT_SCENE"
:quick-prompts="PRE_STORAGE_SCRIPT_AI_QUICK_PROMPTS"
:fallback-system-prompt="preStorageFallbackPrompt"
:short-system-prompt="preStorageShortPrompt"
:hint-text="t('channel.salesProducts.preStorageScript.hint')"
:field-hint-text="t('channel.salesProducts.preStorageScript.fieldHint')"
/>
</div>
</div>
</div>
</div>
</template>
</div>
<!-- 排货判断条件编辑 -->
<a-modal
v-model:visible="matchConditionModalVisible"
:title="t('channel.salesProducts.table.providers.matchConditionModalTitle')"
:width="720"
unmount-on-close
@ok="confirmMatchConditionEditor"
@cancel="closeMatchConditionEditor"
>
<p class="match-condition-modal-hint">
{{ t('channel.salesProducts.table.providers.matchConditionHint') }}
</p>
<BillingConditionEditor v-model="matchConditionDraft" />
</a-modal>
<!-- 发布日期选择弹窗 -->
<a-modal
v-model:visible="publishDateVisible"
:title="t('channel.salesProducts.modal.publishDateTitle')"
:footer="false"
width="400px"
>
<div class="publish-date-modal">
<a-date-picker
v-model="publishDate"
:placeholder="t('channel.salesProducts.modal.publishDate.placeholder')"
style="width: 100%"
show-time
@ok="handleConfirmPublishDate"
/>
<div class="publish-date-actions">
<a-button @click="publishDateVisible = false">
{{ t('channel.salesProducts.modal.actions.cancel') }}
</a-button>
<a-button type="primary" @click="handleConfirmPublishDate(publishDate)">
{{ t('channel.salesProducts.modal.actions.ok') }}
</a-button>
</div>
</div>
</a-modal>
<!-- 新增/编辑价格配置弹窗 -->
<a-modal
v-model:visible="priceModalVisible"
:title="isEditMode ? t('channel.salesProducts.actions.edit') : t('channel.salesProducts.actions.add')"
width="1400px"
:footer="false"
modal-class="sales-price-config-modal"
:body-style="{ overflow: 'visible' }"
@cancel="handleCancelPriceDrawer"
>
<div class="price-modal-content">
<!-- Tab切换 -->
<div class="drawer-title">
<div class="drawer-tabs">
<div
v-for="tab in priceDrawerTabList"
:key="tab.key"
:class="['drawer-tab-item', { active: priceDrawerActiveTab === tab.key }]"
@click="handlePriceDrawerTabSwitch(tab.key)"
>
{{ t(tab.labelKey) }}
</div>
</div>
</div>
<div class="price-modal-pane">
<!-- 基础信息tab -->
<div
v-show="priceDrawerActiveTab === 'basic'"
class="basic-info-content"
>
<!-- 表单部分 -->
<div class="form-section-drawer">
<a-form :model="basicInfoForm" layout="vertical" class="price-form">
<a-row :gutter="24">
<a-col :span="8">
<a-form-item required>
<template #label>
<span class="label-with-tip">
{{ t('channel.salesProducts.drawer.form.costItem') }}
<a-popover
v-if="costItemConfigHelpKey"
position="bottom"
:content-style="{ maxWidth: '360px', whiteSpace: 'pre-wrap', lineHeight: '1.55' }"
>
<template #content>
<div class="cost-item-help-title">
{{ t('channel.salesProducts.drawer.form.costItemHelpTitle') }}
</div>
<div class="cost-item-help-body">{{ t(costItemConfigHelpKey) }}</div>
</template>
<icon-question-circle class="tip-icon" />
</a-popover>
</span>
</template>
<a-select
v-model="basicInfoForm.costItem"
:placeholder="t('channel.salesProducts.form.placeholder.select')"
:loading="salesPriceDictLoading"
>
<a-option
v-for="option in costItemOptions"
:key="option.value"
:value="option.value"
:disabled="!!costItemOptionDisabledReason(option.value)"
:title="costItemOptionDisabledReason(option.value) || undefined"
>
{{ option.label }}
<span
v-if="isCostItemMissingAdditionalService(option.value)"
class="cost-item-option-hint"
>
({{
t('channel.salesProducts.drawer.form.costItemDisabled.needAdditionalService', {
service: additionalServiceLabel(
requiredAdditionalServiceCode(option.value) || '',
),
})
}})
</span>
</a-option>
</a-select>
</a-form-item>
</a-col>
<a-col :span="8">
<a-form-item required>
<template #label>
<span class="label-with-tip">
{{ t('channel.salesProducts.drawer.form.costUnit') }}
<a-tooltip :content="t('channel.salesProducts.drawer.tip.costUnit')">
<icon-question-circle class="tip-icon" />
</a-tooltip>
</span>
</template>
<a-select
v-model="basicInfoForm.costUnit"
:placeholder="t('channel.salesProducts.form.placeholder.select')"
:loading="salesPriceDictLoading"
>
<a-option
v-for="option in costUnitOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</a-option>
</a-select>
</a-form-item>
</a-col>
<a-col :span="8">
<a-form-item required>
<template #label>{{ t('channel.salesProducts.drawer.form.currency') }}</template>
<a-select
v-model="basicInfoForm.currency"
:placeholder="t('channel.salesProducts.form.placeholder.select')"
:loading="salesPriceDictLoading"
>
<a-option
v-for="option in currencyOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</a-option>
</a-select>
</a-form-item>
</a-col>
</a-row>
<a-row :gutter="24">
<a-col :span="24">
<a-form-item hide-label class="charging-condition-form-item">
<BillingConditionEditor
v-model="basicInfoForm.chargingCondition"
:label="t('channel.salesProducts.drawer.form.chargingCondition')"
:label-tip="t('channel.salesProducts.drawer.tip.chargingCondition')"
/>
</a-form-item>
</a-col>
</a-row>
</a-form>
</div>
<!-- 计费因素表格 -->
<div class="billing-factors-section">
<div class="billing-factors-header form-section-title--with-extra">
<div class="form-section-title label-with-tip" style="margin: 0; border: none; padding: 0">
{{ t('channel.salesProducts.drawer.section.billingFactors') }}
<a-tooltip :content="t('channel.salesProducts.drawer.tip.billingFactors')">
<icon-question-circle class="tip-icon" />
</a-tooltip>
</div>
<a-space>
<a-button
type="secondary"
size="small"
@click="handleAddBillingFactor"
>
<icon-plus />
{{ t('channel.salesProducts.drawer.actions.addFactor') }}
</a-button>
<a-button
type="primary"
size="small"
@click="handleGeneratePriceList"
>
<icon-sync />
{{ t('channel.salesProducts.drawer.footer.syncPriceList') }}
</a-button>
</a-space>
</div>
<div ref="billingFactorsTableWrapRef" class="billing-factors-table-wrap">
<TablePro
ref="billingFactorsTableRef"
v-bind="billingFactorsTableProps"
class="billing-factors-table-pro"
>
<template #sort>
<div class="billing-factor-sort-cell">
<icon-drag-arrow />
</div>
</template>
<template #factor="{ row }">
<a-select
v-model="row.factor"
:placeholder="t('channel.salesProducts.form.placeholder.select')"
:loading="salesPriceDictLoading"
size="mini"
style="width: 100%"
:fallback-option="pricingFactorFallbackOption"
@change="(val: string) => handleBillingFactorChange(row, val)"
>
<a-option
v-for="option in factorOptions"
:key="option.value"
:value="option.value"
:label="option.label"
:disabled="isBillingFactorOptionDisabled(option.value, row)"
>
{{ option.label }}
</a-option>
</a-select>
</template>
<template #factorValues="{ row }">
<div
v-for="preview in [getFactorValuePreview(row)]"
:key="row.id"
class="factor-values-cell"
>
<template v-if="preview.items.length">
<a-tag
v-for="item in preview.visible"
:key="`${row.id}-v-${item.index}`"
size="small"
closable
class="factor-value-tag"
:title="item.label"
@close="handleDeleteFactorValue(row, item.index)"
>
<span class="factor-value-tag__text">{{ item.label }}</span>
</a-tag>
<a-popover
v-if="preview.extraCount > 0"
trigger="click"
position="bl"
:content-style="{ padding: '10px 12px', maxWidth: '420px' }"
>
<a-tag size="small" class="factor-value-more" tabindex="0">
+{{ preview.extraCount }}
</a-tag>
<template #content>
<div class="factor-values-popover">
<div class="factor-values-popover__title">
已选 {{ preview.items.length }} 项
</div>
<div class="factor-values-popover__list">
<a-tag
v-for="item in preview.items"
:key="`${row.id}-all-${item.index}`"
size="small"
closable
class="factor-value-tag factor-value-tag--popover"
:title="item.label"
@close="handleDeleteFactorValue(row, item.index)"
>
<span class="factor-value-tag__text">{{ item.label }}</span>
</a-tag>
</div>
</div>
</template>
</a-popover>
</template>
<span v-else class="factor-values-empty">未配置</span>
<a-button
type="text"
size="mini"
class="add-value-btn"
@click="handleAddFactorValue(row)"
>
<icon-plus />
</a-button>
</div>
</template>
<template #action="{ row }">
<a-button
type="text"
size="mini"
status="danger"
class="row-action-btn"
@click="handleDeleteBillingFactor(row)"
>
<icon-delete />
</a-button>
</template>
</TablePro>
</div>
</div>
</div>
<!-- 价格表tab:Handsontable 虚拟渲染,高度跟基础信息对齐 -->
<div
v-if="priceDrawerActiveTab === 'priceList'"
class="price-list-content"
>
<div class="price-list-header">
<div class="price-list-header__meta">
<span class="price-list-badge">
{{
dictLabelByType('fee_item', basicInfoForm.costItem) ||
t('channel.salesProducts.drawer.section.priceListTitle')
}}
</span>
<span class="price-list-hint">{{ t('channel.salesProducts.drawer.priceList.hint') }}</span>
<span v-if="priceListData.length" class="price-list-count">
{{ priceListData.length }} 行
<template v-if="priceListSelectedIds.length"> · 已选 {{ priceListSelectedIds.length }}</template>
</span>
</div>
<div class="price-list-actions">
<label class="price-list-merge">
<span>合并相同值</span>
<a-switch v-model="priceListMergeSame" size="small" />
</label>
<span class="price-list-actions__sep" aria-hidden="true"></span>
<a-button
size="small"
:disabled="!priceListData.length"
@click="selectAllPriceListRows"
>
全选
</a-button>
<a-button
size="small"
:disabled="!priceListSelectedIds.length"
@click="clearAllPriceListRowsSelection"
>
取消全选
</a-button>
<span class="price-list-actions__sep" aria-hidden="true"></span>
<a-button
size="small"
:disabled="!priceListSelectedIds.length && !lastPriceListSelectedIds.length"
@mousedown.prevent="openBatchFillModal"
>
{{ t('channel.salesProducts.drawer.priceList.batchFill') }}
</a-button>
<span class="price-list-actions__sep" aria-hidden="true"></span>
<a-button size="small" @click="handleExportPriceList">导出</a-button>
<a-button size="small" @click="handleImportPriceList">导入</a-button>
<a-button
type="primary"
size="small"
class="app-btn-primary-soft"
@click="handleSavePriceList"
>
{{ t('channel.salesProducts.actions.save') }}
</a-button>
</div>
</div>
<div class="price-list-table-container">
<PriceListHotTable
ref="priceListHotRef"
:key="priceListHotTableKey"
:columns="priceListHotColumns"
:data="priceListData"
:height="PRICE_LIST_HOT_HEIGHT"
:merge-same-values="priceListMergeSame"
@selection-change="onPriceListSelectionChange"
/>
</div>
</div>
</div>
</div>
<!-- 自定义底部按钮 -->
<template #footer>
<div class="price-modal-footer">
<a-button @click="handleCancelPriceDrawer">
{{ t('channel.salesProducts.drawer.footer.cancel') }}
</a-button>
<a-button
v-if="priceDrawerActiveTab === 'basic'"
type="primary"
@click="handleGeneratePriceList"
>
<icon-sync />
{{ t('channel.salesProducts.drawer.footer.syncPriceList') }}
</a-button>
<a-button
v-if="priceDrawerActiveTab === 'priceList'"
type="primary"
@click="handleSavePriceList"
>
<icon-plus />
{{ t('channel.salesProducts.drawer.footer.save') }}
</a-button>
</div>
</template>
</a-modal>
<!-- 批量填价:须高于价格配置大弹窗,否则会被盖住看起来像没弹窗 -->
<a-modal
v-model:visible="batchFillModalVisible"
:title="t('channel.salesProducts.drawer.priceList.batchFill')"
width="420px"
:z-index="3200"
unmount-on-close
@ok="handleConfirmBatchFill"
@cancel="batchFillModalVisible = false"
>
<div class="batch-fill-form">
<div class="batch-fill-meta">
{{ t('channel.salesProducts.drawer.priceList.batchFillSelected', { count: batchFillTargetIds.length || priceListSelectedIds.length }) }}
</div>
<a-form-item :label="t('channel.salesProducts.drawer.priceList.batchFillValue')" required>
<a-input-number
v-model="batchFillValue"
:min="0"
:precision="2"
style="width: 100%"
:placeholder="t('channel.salesProducts.form.placeholder.input')"
/>
</a-form-item>
</div>
</a-modal>
<!-- 新增产品配置弹窗 -->
<a-modal
v-model:visible="addProductModalVisible"
:title="t('channel.salesProducts.actions.add')"
:width="900"
:mask-closable="false"
unmount-on-close
@cancel="handleCancelAddProduct"
>
<div class="add-product-modal-content">
<div class="form-container">
<div class="form-section-title">{{ t('channel.salesProducts.section.basic') }}</div>
<div class="form-row">
<div class="form-item">
<label class="form-label label-with-tip">
{{ t('channel.salesProducts.form.productCode') }}
<a-tooltip>
<template #content>
<div style="white-space: pre-line; max-width: 320px; line-height: 1.5;">{{ t('channel.salesProducts.tip.productCode') }}</div>
</template>
<icon-question-circle class="tip-icon" />
</a-tooltip>
</label>
<a-input
:model-value="addProductFormData.productCode"
:placeholder="t('channel.salesProducts.placeholder.productCode')"
class="form-input"
allow-clear
@update:model-value="(v) => (addProductFormData.productCode = normalizeBizCode(v))"
/>
</div>
<div class="form-item">
<label class="form-label label-with-tip">
{{ t('channel.salesProducts.form.productName') }}
<a-tooltip>
<template #content>
<div style="white-space: pre-line; max-width: 320px; line-height: 1.5;">{{ t('channel.salesProducts.tip.productName') }}</div>
</template>
<icon-question-circle class="tip-icon" />
</a-tooltip>
</label>
<a-input
v-model="addProductFormData.productName"
:placeholder="t('channel.salesProducts.placeholder.productName')"
class="form-input"
allow-clear
/>
</div>
<div class="form-item">
<label class="form-label label-with-tip">
{{ t('channel.salesProducts.form.group') }}
<a-tooltip :content="t('channel.salesProducts.tip.group')">
<icon-question-circle class="tip-icon" />
</a-tooltip>
</label>
<a-select
v-model="addProductFormData.group"
:placeholder="t('channel.salesProducts.form.placeholder.select')"
class="form-select"
>
<a-option
v-for="option in groupOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</a-option>
</a-select>
</div>
</div>
<div class="form-section-title">{{ t('channel.salesProducts.section.route') }}</div>
<div class="form-row">
<div class="form-item">
<label class="form-label label-with-tip">
{{ t('channel.salesProducts.form.efficiency') }}
<a-tooltip :content="t('channel.salesProducts.tip.efficiency')">
<icon-question-circle class="tip-icon" />
</a-tooltip>
</label>
<div class="timeliness-inputs">
<a-input
v-model="addProductFormData.minTimeliness"
:placeholder="t('channel.salesProducts.form.placeholder.min')"
class="timeliness-input"
/>
<span class="timeliness-separator">-</span>
<a-input
v-model="addProductFormData.maxTimeliness"
:placeholder="t('channel.salesProducts.form.placeholder.max')"
class="timeliness-input"
/>
</div>
</div>
<div class="form-item">
<label class="form-label">{{ t('channel.salesProducts.form.tradeTerms') }}</label>
<a-select
v-model="addProductFormData.tradeTerms"
allow-clear
:placeholder="t('channel.salesProducts.form.placeholder.select')"
class="form-select"
>
<a-option value="DDP">DDP</a-option>
<a-option value="DDU">DDU</a-option>
</a-select>
</div>
<div class="form-item">
<label class="form-label label-with-tip">
{{ t('channel.salesProducts.form.routeSort') }}
<a-tooltip :content="t('channel.salesProducts.form.routeSortTip')">
<icon-question-circle class="tip-icon" />
</a-tooltip>
</label>
<a-input-number
v-model="addProductFormData.routeSort"
:min="0"
:precision="0"
hide-button
:placeholder="t('channel.salesProducts.form.routeSortTip')"
class="form-select"
/>
</div>
<div class="form-item">
<label class="form-label label-with-tip">
{{ t('channel.salesProducts.form.customerWaybill') }}
<a-tooltip :content="t('channel.salesProducts.tip.labelTemplate')">
<icon-question-circle class="tip-icon" />
</a-tooltip>
</label>
<a-select
v-model="addProductFormData.labelTemplateId"
class="form-select"
allow-clear
allow-search
:placeholder="t('channel.salesProducts.form.placeholder.labelTemplate')"
>
<a-option
v-for="option in labelTemplateOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</a-option>
</a-select>
</div>
</div>
<div class="form-section-title">{{ t('channel.salesProducts.section.zoneWeight') }}</div>
<div class="form-row">
<div class="form-item">
<FormLabelWithPreview
:label="t('channel.salesProducts.form.blacklistArea')"
:has-value="!!addProductFormData.blacklistArea"
@preview="openReferencePreview('kpi-blacklist', addProductFormData.blacklistArea, blacklistAreaOptions)"
/>
<a-select
v-model="addProductFormData.blacklistArea"
:placeholder="t('channel.salesProducts.form.placeholder.select')"
class="form-select"
allow-clear
>
<a-option
v-for="option in blacklistAreaOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</a-option>
</a-select>
</div>
<div class="form-item">
<FormLabelWithPreview
:label="t('channel.salesProducts.form.remoteAreaDivision')"
:has-value="!!addProductFormData.remoteAreaDivision"
@preview="openReferencePreview('kpi-remote', addProductFormData.remoteAreaDivision, remoteAreaDivisionOptions)"
/>
<a-select
v-model="addProductFormData.remoteAreaDivision"
:placeholder="t('channel.salesProducts.form.placeholder.select')"
class="form-select"
allow-clear
>
<a-option
v-for="option in remoteAreaDivisionOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</a-option>
</a-select>
</div>
<div class="form-item">
<FormLabelWithPreview
:label="t('channel.salesProducts.form.weightCalculationRule')"
:has-value="!!addProductFormData.weightCalculationRule"
@preview="openReferencePreview('weight-rule', addProductFormData.weightCalculationRule, weightCalculationRuleOptions)"
/>
<a-select
v-model="addProductFormData.weightCalculationRule"
:placeholder="t('channel.salesProducts.form.placeholder.select')"
class="form-select"
allow-clear
>
<a-option
v-for="option in weightCalculationRuleOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</a-option>
</a-select>
</div>
<div class="form-item">
<FormLabelWithPreview
:label="t('channel.salesProducts.form.weightRounding')"
:has-value="!!addProductFormData.weightRounding"
@preview="openReferencePreview('weight-rounding', addProductFormData.weightRounding, weightRoundingOptions)"
/>
<a-select
v-model="addProductFormData.weightRounding"
:placeholder="t('channel.salesProducts.form.placeholder.select')"
class="form-select"
allow-clear
>
<a-option
v-for="option in weightRoundingOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</a-option>
</a-select>
</div>
</div>
<div class="form-row">
<div class="form-item full-width">
<label class="form-label">{{ t('channel.salesProducts.form.additionalServices') }}</label>
<a-select
v-model="addProductFormData.additionalServices"
multiple
allow-clear
:placeholder="t('channel.salesProducts.form.placeholder.select')"
class="form-select"
:loading="salesPriceDictLoading"
>
<a-option
v-for="option in additionalServiceOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</a-option>
</a-select>
</div>
</div>
<div class="form-section-title">{{ t('channel.salesProducts.section.desc') }}</div>
<div class="form-row">
<div class="form-item full-width">
<label class="form-label">{{ t('channel.salesProducts.form.productDescription') }}</label>
<a-textarea
v-model="addProductFormData.productDescription"
:placeholder="t('channel.salesProducts.placeholder.productDescription')"
:auto-size="{ minRows: 2, maxRows: 4 }"
class="form-textarea"
allow-clear
/>
</div>
</div>
<div class="add-product-advanced-toggle">
<a-button type="text" size="small" @click="addProductShowAdvanced = !addProductShowAdvanced">
{{
addProductShowAdvanced
? t('channel.salesProducts.form.hideAdvanced')
: t('channel.salesProducts.form.showAdvanced')
}}
</a-button>
</div>
<div v-if="addProductShowAdvanced" class="form-row">
<div class="form-item full-width">
<PreScriptEditor
v-model="addProductFormData.preStorageScript"
:label="t('channel.salesProducts.form.preStorageScript')"
:label-tip="t('channel.salesProducts.tip.preStorageScript')"
:placeholder="t('channel.salesProducts.placeholder.preStorageScript')"
:rows="4"
:skill-scene="PRE_STORAGE_SCRIPT_AI_SCENE"
:default-skill-key="PRE_STORAGE_SCRIPT_AI_DEFAULT_SKILL_KEY"
:storage-key="PRE_STORAGE_SCRIPT_AI_STORAGE_KEY"
:chat-scene="PRE_STORAGE_SCRIPT_AI_CHAT_SCENE"
:quick-prompts="PRE_STORAGE_SCRIPT_AI_QUICK_PROMPTS"
:fallback-system-prompt="preStorageFallbackPrompt"
:short-system-prompt="preStorageShortPrompt"
:hint-text="t('channel.salesProducts.preStorageScript.hint')"
:field-hint-text="t('channel.salesProducts.preStorageScript.fieldHint')"
/>
</div>
</div>
</div>
</div>
<template #footer>
<div class="modal-footer">
<a-button @click="handleCancelAddProduct">
{{ t('channel.salesProducts.modal.actions.cancel') }}
</a-button>
<a-button type="primary" @click="handleSaveAddProduct">
{{ t('channel.salesProducts.actions.save') }}
</a-button>
</div>
</template>
</a-modal>
<!-- 发布弹窗 -->
<ModalPro
modal-class="sales-product-publish-modal"
:align-center="true"
:title="
isPricePublishFlow
? t('channel.salesProducts.publish.priceFlowTitle')
: t('channel.salesProducts.publish.title')
"
:width="1280"
:footer="false"
:body-style="publishModalBodyStyle"
@register="registerPublishModal"
>
<a-spin
:loading="publishModalLoading"
tip="正在加载发布快照,大价格表可能需要几秒…"
class="publish-modal-spin"
>
<div class="release-content slim">
<!-- 价格:流程卡片 -->
<div v-if="isPricePublishFlow && publishDiffLength > 0" class="publish-flow">
<div
class="flow-card"
:class="{
'is-current': pricePublishStep === 1,
'is-done': pricePublishAiReady,
}"
@click="goPricePublishStep1"
>
<div class="flow-card-head">
<span class="flow-badge">01</span>
<div class="flow-card-titles">
<div class="flow-card-title">{{ t('channel.salesProducts.publish.step1Title') }}</div>
<div class="flow-card-desc">{{ t('channel.salesProducts.publish.step1Desc') }}</div>
</div>
<a-tag
size="small"
:color="pricePublishAiReady ? 'green' : pricePublishStep === 1 ? 'arcoblue' : 'gray'"
>
{{
pricePublishAiReady
? t('channel.salesProducts.publish.flowStatus.done')
: pricePublishStep === 1
? t('channel.salesProducts.publish.flowStatus.doing')
: t('channel.salesProducts.publish.flowStatus.todo')
}}
</a-tag>
</div>
<div class="flow-card-body">
<template v-if="pricePublishAiReady">
<div v-if="pricePublishAiSkipped" class="flow-result">
<a-tag size="small" color="gray">{{ t('channel.salesProducts.ai.statusSkipped') }}</a-tag>
<span v-if="pricePublishAiSummary" class="flow-result-summary">
{{ pricePublishAiSummary }}
</span>
</div>
<div v-else class="flow-result">
<span class="flow-result-label">{{ t('channel.salesProducts.publish.flowRisk') }}</span>
<a-tag
v-if="pricePublishAiLevel"
size="small"
:color="
pricePublishAiLevel === '高风险'
? 'red'
: pricePublishAiLevel === '中风险'
? 'orangered'
: 'arcoblue'
"
>
{{ pricePublishAiLevel }}
</a-tag>
<span v-if="pricePublishAiSummary" class="flow-result-summary">
{{ pricePublishAiSummary }}
</span>
</div>
</template>
<p v-else class="flow-card-hint">{{ t('channel.salesProducts.publish.step1Hint') }}</p>
</div>
<div class="flow-card-foot" @click.stop>
<a-button
type="primary"
long
:disabled="publishDiffStatus === 'synced'"
@click="openPricePublishAiAssist"
>
{{
pricePublishAiReady
? t('channel.salesProducts.ai.openAgain')
: t('channel.salesProducts.publish.startAi')
}}
</a-button>
</div>
</div>
<div class="flow-connector" aria-hidden="true">
<span class="flow-connector-line" />
<span class="flow-connector-arrow">›</span>
</div>
<div
class="flow-card"
:class="{
'is-current': pricePublishStep === 2,
'is-locked': !pricePublishAiReady,
'is-ready': pricePublishAiReady && pricePublishStep !== 2,
}"
@click="pricePublishAiReady ? goPricePublishStep2() : undefined"
>
<div class="flow-card-head">
<span class="flow-badge">02</span>
<div class="flow-card-titles">
<div class="flow-card-title">{{ pricePublishStep2Title }}</div>
<div class="flow-card-desc">{{ pricePublishStep2Desc }}</div>
</div>
<a-tag
size="small"
:color="
!pricePublishAiReady
? 'gray'
: pricePublishStep === 2
? 'arcoblue'
: 'orangered'
"
>
{{
!pricePublishAiReady
? t('channel.salesProducts.publish.flowStatus.locked')
: pricePublishStep === 2
? t('channel.salesProducts.publish.flowStatus.doing')
: t('channel.salesProducts.publish.flowStatus.ready')
}}
</a-tag>
</div>
<div class="flow-card-body">
<p class="flow-card-hint">
{{
pricePublishAiReady
? pricePublishStep2ReadyHint
: t('channel.salesProducts.publish.step2LockedHint')
}}
</p>
</div>
<div class="flow-card-foot" @click.stop>
<a-button
type="primary"
long
:disabled="!pricePublishAiReady"
@click="goPricePublishStep2"
>
{{ pricePublishGotoStep2Text }}
</a-button>
</div>
</div>
</div>
<div class="publish-scroll">
<!-- ===== 步骤 1:核对 Diff + AI 分析 ===== -->
<template v-if="!isPricePublishFlow || pricePublishStep === 1">
<PublishDiffPanel
:status="publishDiffStatus"
:rows="publishDiffRows"
:diff-length="publishDiffLength"
:status-title="
publishDiffStatus === 'synced'
? t('channel.salesProducts.publish.status.synced')
: publishDiffStatus === 'first'
? t('channel.salesProducts.publish.status.first')
: t('channel.salesProducts.publish.status.changed', {
count: publishDiffLength,
})
"
:status-desc="
publishDiffStatus === 'synced'
? t('channel.salesProducts.publish.noDiffDetail')
: undefined
"
filter-mode="checkbox"
v-model:show-only-diff="showOnlyDiff"
:show-only-diff-label="t('channel.salesProducts.publish.showOnlyDiff')"
:legend-labels="{
add: t('channel.salesProducts.publish.legend.add'),
remove: t('channel.salesProducts.publish.legend.remove'),
change: t('channel.salesProducts.publish.legend.change'),
same: t('channel.salesProducts.publish.legend.same'),
}"
:empty-text="t('channel.salesProducts.publish.noDiffDetail')"
:merged-title="t('channel.salesProducts.publish.changeSummary')"
:diff-count-text="
t('channel.salesProducts.publish.diffCount', {
count: publishDiffLength,
})
"
:raw-mode="isPricePublishFlow ? 'details' : 'always'"
:raw-summary-text="t('channel.salesProducts.publish.advancedJson')"
v-model:raw-details-open="pricePublishShowRawJson"
:original-title="t('channel.salesProducts.publish.onlineCache')"
:modified-title="
isPricePublishFlow
? t('channel.salesProducts.publish.pendingCache')
: `${t('channel.salesProducts.publish.pendingCache')} (${t(
'channel.salesProducts.publish.diffCount',
{ count: publishDiffLength },
)})`
"
:original-json="getOriginalValue"
:modified-json="getModifiedModel"
same-line-mark="space"
>
<template #header-actions>
<template v-if="!isPricePublishFlow">
<a-button
type="primary"
size="small"
:disabled="publishDiffStatus === 'synced'"
@click="handlePublishConfirm"
>
{{
publishDiffStatus === 'synced'
? t('channel.salesProducts.publish.noNeed')
: t('channel.salesProducts.publish.confirm')
}}
</a-button>
</template>
</template>
</PublishDiffPanel>
</template>
<!-- ===== 步骤 2:正式发布 ===== -->
<div v-else class="publish-step2">
<div class="step2-card">
<div class="step2-card-title">
{{ t('channel.salesProducts.ai.confirmReportLabel') }}
<a-tag v-if="pricePublishAiSkipped" size="small" color="gray">
{{ t('channel.salesProducts.ai.statusSkipped') }}
</a-tag>
<a-tag
v-else-if="pricePublishAiLevel"
size="small"
:color="
pricePublishAiLevel === '高风险'
? 'red'
: pricePublishAiLevel === '中风险'
? 'orangered'
: 'arcoblue'
"
>
{{ pricePublishAiLevel }}
</a-tag>
</div>
<p v-if="pricePublishAiSummary" class="step2-summary">{{ pricePublishAiSummary }}</p>
<details
class="step2-report-details"
:open="pricePublishReportExpanded"
@toggle="pricePublishReportExpanded = ($event.target as HTMLDetailsElement).open"
>
<summary>{{ t('channel.salesProducts.publish.expandReport') }}</summary>
<a-textarea
class="mt-8"
:model-value="pricePublishAiReport"
:readonly="true"
:auto-size="{ minRows: 4, maxRows: 8 }"
/>
</details>
<div class="step2-reanalyze">
<a-button size="small" @click="openPricePublishAiAssist">
{{ t('channel.salesProducts.ai.openAgain') }}
</a-button>
<span class="step2-reanalyze-hint">{{ t('channel.salesProducts.publish.reanalyzeHint') }}</span>
</div>
</div>
<div class="step2-form">
<div class="step2-field">
<label class="step2-label">{{ t('channel.salesProducts.publish.versionRemark') }}</label>
<a-input
v-model="publishDescription"
:placeholder="t('channel.salesProducts.publish.remarkPlaceholder')"
/>
</div>
<div v-if="pricePublishIsHighRisk" class="step2-high-risk">
<a-checkbox v-model="pricePublishHighRiskAck">
{{ t('channel.salesProducts.publish.highRiskAck') }}
</a-checkbox>
</div>
</div>
<div class="step2-actions">
<a-button @click="goPricePublishStep1">
{{ t('channel.salesProducts.publish.backToStep1') }}
</a-button>
<a-button
v-if="pricePublishIsHighRisk"
type="primary"
status="danger"
:loading="pricePublishSubmitting"
:disabled="!pricePublishCanFinalSubmit"
@click="handleConfirmPublish"
>
{{ pricePublishFinalConfirmHighRiskText }}
</a-button>
<a-button
v-else
type="primary"
:loading="pricePublishSubmitting"
:disabled="!pricePublishCanFinalSubmit"
@click="handleConfirmPublish"
>
{{ pricePublishFinalConfirmText }}
</a-button>
</div>
</div>
</div>
</div>
</a-spin>
</ModalPro>
<ApprovalDetailDrawer
v-model:visible="priceApprovalDrawerVisible"
:instance-id="priceApprovalInstanceId"
@changed="onPriceApprovalChanged"
/>
<PricePublishAiAssistDrawer
v-model:visible="pricePublishAiVisible"
:product-name="formData.productName || selectedProductContext?.productName"
:sales-product-id="selectedProduct"
:effective-version="effectiveVersion"
:online-json="getOriginalValue"
:pending-json="getModifiedModel"
:diff-rows="publishDiffRows"
:diff-length="publishDiffLength"
:has-online-snapshot="publishHasOnlineSnapshot"
@adopt="onPricePublishAiAdopt"
@skip="onPricePublishAiSkip"
/>
<BillingSimulateDrawer
v-model:visible="billingSimulateVisible"
:sales-product-id="selectedProduct"
:additional-services="formData.additionalServices"
/>
<!-- 发布确认弹窗(规则发布) -->
<a-modal
v-model:visible="publishConfirmVisible"
:title="t('channel.salesProducts.publish.title')"
@cancel="handleCancelPublishConfirm"
@ok="handleConfirmPublish"
>
<a-alert
v-if="publishOperatorType === 'rules'"
type="warning"
:show-icon="true"
style="margin-bottom: 12px"
>
{{ t('channel.salesProducts.publish.downstreamSyncTip') }}
</a-alert>
<div class="mb-15px">{{ t('channel.salesProducts.publish.effectiveTimeHint') }}</div>
<div class="mb-15px">
<a-input
v-model="publishDescription"
:placeholder="t('channel.salesProducts.publish.remarkPlaceholder')"
/>
</div>
<div>
<a-date-picker
v-model="publishConfirmDate"
:placeholder="t('channel.salesProducts.modal.publishDate.placeholder')"
style="width: 100%"
show-time
format="YYYY-MM-DD HH:mm:ss"
:disabled-date="disabledDate"
:disabled-time="disabledTime"
/>
</div>
</a-modal>
<!-- 删除产品确认弹窗 -->
<a-modal
v-model:visible="deleteProductModalVisible"
title="确认删除产品"
width="500px"
@cancel="handleCancelDeleteProduct"
@ok="handleConfirmDeleteProduct"
>
<div class="delete-confirm-modal">
<div class="delete-confirm-message">
<p>删除产品后无法恢复,请谨慎操作。</p>
<p style="margin-top: 12px; font-weight: 600; color: var(--color-text-1);">
请输入产品名称 <span style="color: #f53f3f;">"{{ deletingProduct?.name }}"</span> 以确认删除:
</p>
</div>
<div style="margin-top: 16px;">
<a-input
v-model="deleteProductInput"
placeholder="请输入产品名称"
@press-enter="handleConfirmDeleteProduct"
/>
</div>
</div>
</a-modal>
<!-- 删除价格配置确认弹窗 -->
<a-modal
v-model:visible="deletePriceModalVisible"
title="确认删除价格配置"
width="500px"
@cancel="handleCancelDeletePrice"
@ok="handleConfirmDeletePrice"
>
<div class="delete-confirm-modal">
<div class="delete-confirm-message">
<p>删除价格配置后无法恢复,请谨慎操作。</p>
<p style="margin-top: 12px; font-weight: 600; color: var(--color-text-1);">
请输入费用项名称 <span style="color: #f53f3f;">"{{ deletingPriceRecord?.priceName || deletingPriceRecord?.costItem || '' }}"</span> 以确认删除:
</p>
</div>
<div style="margin-top: 16px;">
<a-input
v-model="deletePriceInput"
placeholder="请输入费用项名称"
@press-enter="handleConfirmDeletePrice"
/>
</div>
</div>
</a-modal>
<!-- 添加因素值弹窗 -->
<a-modal
v-model:visible="addFactorValueModalVisible"
title="添加因素值"
width="400px"
@cancel="handleAddFactorValueModalCancel"
@ok="handleConfirmAddFactorValue"
>
<div class="add-factor-value-modal">
<div class="add-factor-value-actions">
<a-button
type="text"
size="small"
:disabled="currentFactorValueOptions.length === 0"
@click="handleSelectAllFactorValues"
>
{{ isAllFactorValuesSelected ? '清空' : '全选' }}
</a-button>
</div>
<a-select
:model-value="addFactorValueSelected"
:options="currentFactorValueOptions"
:placeholder="currentFactorValueOptions.length ? '请选择因素值' : '该因素暂无可选值'"
multiple
allow-clear
allow-search
style="width: 100%"
@change="handleAddFactorValueSelectedChange"
@press-enter="handleConfirmAddFactorValue"
/>
</div>
</a-modal>
<a-modal
v-model:visible="productCodeModalVisible"
:title="t('channel.salesProducts.modal.editProductCodeTitle')"
width="420px"
:mask-closable="false"
:ok-loading="savingProductCode"
@ok="handleSaveProductCode"
@cancel="productCodeModalVisible = false"
>
<p class="product-code-edit-hint">{{ t('channel.salesProducts.modal.editProductCodeHint') }}</p>
<a-input
:model-value="productCodeDraft"
:placeholder="t('channel.salesProducts.placeholder.productCode')"
allow-clear
@update:model-value="(v) => (productCodeDraft = normalizeBizCode(v))"
@press-enter="handleSaveProductCode"
/>
</a-modal>
<ChannelReferencePreviewModal ref="referencePreviewRef" :dict-label-fn="dictLabelByType" />
</div>
</template>
<style lang="less" scoped>
.sales-product-layout {
display: flex;
height: 100%;
padding: 16px;
gap: 16px;
background-color: var(--color-fill-2);
overflow: hidden;
}
/* 左侧使用 CustomLeftMenu,仅保留布局(参考应用列表) */
.left-sidebar {
width: 280px;
flex-shrink: 0;
height: 100%;
display: flex;
flex-direction: column;
}
/* 第二行:修改时间 + 开关(卡片高度由 CustomLeftMenu 固定,内容垂直居中) */
.product-second-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
width: 100%;
height: 16px;
padding-left: 24px;
box-sizing: border-box;
}
.modify-time {
flex: 1;
min-width: 0;
font-size: 10px;
line-height: 16px;
color: var(--color-text-3);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* 开关:启用-绿色,停用-红色(与应用列表一致) */
.left-sidebar :deep(.product-active-switch.arco-switch-checked) {
background-color: #00b42a !important;
}
.left-sidebar :deep(.product-active-switch:not(.arco-switch-checked)) {
background-color: #f53f3f !important;
}
:deep(.node-second-row-extra-slot) {
display: block;
width: 100%;
}
:deep(.node-second-row-extra-cell) {
text-align: left;
}
:deep(.tree-node.selected .modify-time) {
color: #86909c !important;
}
.right-content.content-panel {
flex: 1;
background-color: var(--color-bg-1);
border-radius: 24px;
display: flex;
flex-direction: column;
overflow: hidden;
}
.switch-swipe-wrapper {
display: inline-block;
}
.tabs-section {
border-bottom: 1px solid #e8e8e8;
padding: 10px 24px;
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
}
.tabs-toolbar {
display: flex;
align-items: center;
padding: 0;
}
.product-context-bar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 12px;
padding: 10px 24px;
background: var(--color-fill-1);
border-bottom: 1px solid #e8e8e8;
font-size: 13px;
color: #595959;
.context-label {
color: var(--color-text-3);
}
.context-value {
color: var(--color-text-1);
font-weight: 500;
}
.context-code {
margin-left: 4px;
color: var(--color-text-3);
}
.context-divider {
color: #d9d9d9;
}
.context-dirty-tag {
margin-left: auto;
}
}
.empty-state-panel {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
min-height: 240px;
}
.empty-state {
text-align: center;
color: var(--color-text-3);
font-size: 14px;
p {
margin: 0;
}
}
.form-section {
flex: 1;
padding: 24px;
overflow-y: auto;
}
.form-container {
max-width: 800px;
}
.form-row {
display: flex;
gap: 24px;
margin-bottom: 24px;
&:last-child {
margin-bottom: 0;
}
}
.form-item {
display: flex;
flex-direction: column;
gap: 8px;
flex: 1;
&.full-width {
flex: 1;
}
}
.form-label {
font-size: 14px;
font-weight: 500;
color: var(--color-text-1);
}
.label-with-tip {
display: inline-flex;
align-items: center;
gap: 4px;
}
.tip-icon {
color: var(--color-text-3);
cursor: help;
font-size: 14px;
}
.product-code-edit-icon {
display: inline-flex;
align-items: center;
justify-content: center;
margin: 0;
padding: 0;
border: none;
background: transparent;
color: var(--color-text-3);
font-size: 14px;
line-height: 1;
cursor: pointer;
&:hover {
color: var(--app-primary-color, #007979);
}
}
.product-code-edit-hint {
margin: 0 0 12px;
color: var(--color-text-3);
font-size: 12px;
line-height: 1.5;
}
.form-input,
.form-select,
.form-textarea {
width: 100%;
}
.timeliness-inputs {
display: flex;
align-items: center;
gap: 8px;
.timeliness-input {
flex: 1;
}
.timeliness-separator {
color: var(--color-text-3);
font-weight: 500;
}
}
.price-section {
flex: 1;
display: flex;
flex-direction: column;
padding: 24px;
overflow: hidden;
}
.price-approval-banner {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 12px;
padding: 12px 14px;
border-radius: 6px;
border: 1px solid var(--color-border-2);
&.is-waiting {
background: #e8f7f7;
border-color: color-mix(in srgb, var(--app-primary-color, #1d7281) 35%, #fff);
}
&.is-failed {
background: #fff7f0;
border-color: #ffd0a8;
}
}
.price-approval-banner-main {
min-width: 0;
flex: 1;
}
.price-approval-banner-title {
font-size: 14px;
font-weight: 600;
color: var(--color-text-1);
line-height: 1.4;
}
.price-approval-banner-desc {
margin-top: 4px;
font-size: 13px;
color: var(--color-text-2);
line-height: 1.5;
}
.price-approval-banner-actions {
display: flex;
flex-shrink: 0;
align-items: center;
gap: 8px;
}
.customer-guide-section {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
.price-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
.version-info {
font-size: 14px;
color: var(--color-text-1);
.price-sync-tag {
margin-left: 12px;
vertical-align: middle;
}
.price-approval-tag {
cursor: pointer;
}
}
.price-header-actions {
display: flex;
align-items: center;
gap: 12px;
}
.add-price-btn {
display: flex;
align-items: center;
gap: 6px;
.btn-icon {
font-size: 14px;
}
}
}
.price-table-container {
flex: 1;
min-height: 0;
overflow: hidden;
.price-list-spin {
display: block;
width: 100%;
height: 100%;
}
.price-list-table-pro {
width: 100%;
min-height: 0;
:deep(.table-pro),
:deep(.table-pro-surface) {
height: 100%;
}
:deep(.vxe-toolbar) {
display: none !important;
height: 0 !important;
min-height: 0 !important;
padding: 0 !important;
overflow: hidden !important;
}
:deep(.vxe-grid) {
padding-left: 0 !important;
padding-right: 0 !important;
}
.action-btn {
color: var(--app-primary-color);
&:hover {
color: var(--app-primary-color);
background: color-mix(in srgb, var(--app-primary-color) 8%, #fff);
}
&.delete-btn {
color: #f53f3f;
&:hover {
color: #d32f2f;
background-color: #fff1f0;
}
}
}
:deep(.product-active-switch.arco-switch-checked) {
background-color: #00b42a !important;
}
:deep(.product-active-switch:not(.arco-switch-checked)) {
background-color: #f53f3f !important;
}
}
}
// 抽屉相关样式:胶囊 Tab
.drawer-title {
width: 100%;
margin: 0 0 10px;
.drawer-tabs {
display: flex;
align-items: center;
gap: 0;
width: 100%;
border-bottom: 1px solid var(--color-border-2);
.drawer-tab-item {
height: 40px;
padding: 0 20px;
margin-bottom: -1px;
border: none;
border-bottom: 2px solid transparent;
border-radius: 0;
background: transparent;
cursor: pointer;
color: var(--color-text-2);
font-size: 14px;
font-weight: 500;
line-height: 40px;
white-space: nowrap;
transition: color 0.2s ease, border-color 0.2s ease;
&:hover {
color: var(--app-primary-color);
}
&.active {
background: transparent;
color: var(--app-primary-color);
font-weight: 600;
border-bottom-color: var(--app-primary-color);
box-shadow: none;
}
}
}
}
.basic-info-content {
display: flex;
flex-direction: column;
gap: 12px;
height: 100%;
padding: 0;
overflow: hidden;
.form-section-drawer {
flex-shrink: 0;
}
.form-section-title {
margin: 0 0 12px;
padding: 0 0 8px;
font-size: 13px;
font-weight: 600;
color: var(--color-text-2);
border-bottom: 1px solid var(--color-border-2);
}
.form-section-title--with-extra {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
padding-bottom: 8px;
border-bottom: 1px solid var(--color-border-2);
}
.label-with-tip {
display: inline-flex;
align-items: center;
gap: 4px;
}
.tip-icon {
color: var(--color-text-3);
cursor: help;
font-size: 14px;
}
}
.form-section-drawer {
.price-form {
:deep(.arco-form-item) {
margin-bottom: 16px;
}
:deep(.arco-form-item-label) {
font-weight: 500;
}
:deep(.charging-condition-form-item) {
margin-bottom: 12px;
.arco-form-item-label-col {
display: none;
}
.arco-form-item-wrapper-col {
flex: 1 1 100%;
width: 100%;
}
}
}
}
.cost-item-field {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
.arco-select {
flex: 1;
min-width: 0;
}
}
.cost-item-help-icon {
flex-shrink: 0;
color: #faad14;
font-size: 18px;
cursor: pointer;
line-height: 1;
}
.cost-item-help-title {
margin-bottom: 8px;
font-weight: 600;
color: var(--color-text-1);
}
.cost-item-help-body {
white-space: pre-wrap;
font-size: 13px;
color: var(--color-text-2);
line-height: 1.55;
}
.cost-item-option-hint {
margin-left: 4px;
color: var(--color-text-3);
font-size: 12px;
}
.billing-factors-section {
display: flex;
flex-direction: column;
min-height: 0;
flex: 1;
.billing-factors-header {
flex-shrink: 0;
margin-bottom: 8px;
}
.billing-factors-table-wrap {
flex: 1 1 auto;
min-height: 0;
width: 100%;
overflow: hidden;
}
.billing-factors-table-pro {
width: 100%;
min-height: 0;
:deep(.vxe-toolbar) {
display: none;
}
}
.billing-factor-sort-cell {
display: flex;
align-items: center;
justify-content: center;
color: var(--color-text-3);
cursor: move;
font-size: 18px;
&:hover {
color: var(--app-primary-color);
}
}
.factor-values-cell {
display: flex;
flex-wrap: nowrap;
align-items: center;
gap: 4px;
max-width: 100%;
min-width: 0;
overflow: hidden;
.factor-value-tag {
display: inline-flex;
align-items: center;
flex: 0 1 auto;
max-width: 148px;
min-width: 0;
overflow: hidden;
vertical-align: middle;
.factor-value-tag__text {
display: block;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
:deep(.arco-tag-close-btn) {
flex-shrink: 0;
margin-left: 4px;
}
}
.factor-value-more {
flex-shrink: 0;
cursor: pointer;
color: var(--app-primary-color);
background: color-mix(in srgb, var(--app-primary-color) 10%, #fff);
border-color: color-mix(in srgb, var(--app-primary-color) 28%, #fff);
&:hover {
background: color-mix(in srgb, var(--app-primary-color) 16%, #fff);
}
}
.factor-values-empty {
flex-shrink: 0;
color: var(--color-text-4);
font-size: 12px;
}
.add-value-btn {
flex-shrink: 0;
margin-left: auto;
color: var(--app-primary-color);
&:hover {
color: var(--app-primary-color);
background: color-mix(in srgb, var(--app-primary-color) 8%, #fff);
}
}
}
.row-action-btn {
color: var(--color-text-3);
&:hover {
color: rgb(var(--danger-6));
}
}
}
.factor-value-tag--popover {
max-width: 100%;
.factor-value-tag__text {
white-space: normal;
overflow: visible;
text-overflow: unset;
}
}
.factor-values-popover {
display: flex;
flex-direction: column;
gap: 8px;
max-width: 400px;
&__title {
color: var(--color-text-3);
font-size: 12px;
line-height: 1.2;
}
&__list {
display: flex;
flex-wrap: wrap;
gap: 6px;
max-height: 220px;
overflow: auto;
}
}
.price-modal-pane {
box-sizing: border-box;
height: 598px; // 表头区 48 + 列表 550,两个 tab 同高
overflow: hidden;
}
.price-list-content {
display: flex;
flex-direction: column;
box-sizing: border-box;
height: 100%;
min-height: 0;
overflow: hidden;
padding: 0;
.price-list-header {
display: flex;
flex-wrap: nowrap;
align-items: center;
justify-content: space-between;
gap: 12px;
height: 40px;
flex-shrink: 0;
margin-bottom: 8px;
padding: 0 2px;
}
.price-list-header__meta {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
flex: 1 1 auto;
overflow: hidden;
}
.price-list-badge {
flex-shrink: 0;
height: 24px;
padding: 0 10px;
border-radius: 4px;
background: color-mix(in srgb, var(--app-primary-color) 12%, #fff);
color: var(--app-primary-color);
font-size: 13px;
font-weight: 600;
line-height: 24px;
white-space: nowrap;
}
.price-list-hint {
min-width: 0;
color: var(--color-text-3);
font-size: 12px;
font-weight: 400;
line-height: 1.2;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.price-list-count {
flex-shrink: 0;
color: var(--color-text-3);
font-size: 12px;
white-space: nowrap;
}
.price-list-merge {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--color-text-2);
font-size: 12px;
white-space: nowrap;
cursor: pointer;
user-select: none;
}
.price-list-actions {
display: flex;
flex-wrap: nowrap;
align-items: center;
justify-content: flex-end;
gap: 6px;
flex: 0 0 auto;
&__sep {
width: 1px;
height: 16px;
margin: 0 2px;
background: var(--color-border-2);
}
:deep(.arco-btn) {
height: 28px;
padding: 0 10px;
border-radius: 4px;
font-size: 12px;
}
}
.price-list-table-container {
box-sizing: border-box;
flex: 1 1 auto;
width: 100%;
height: 500px;
min-width: 0;
min-height: 0;
overflow: hidden;
border: 1px solid var(--color-border-2);
border-radius: 6px;
background: #fff;
}
}
.price-modal-content {
padding: 0;
overflow: visible;
}
.price-modal-steps {
margin-bottom: 24px;
:deep(.arco-steps-item) {
flex: 0 0 auto;
padding-right: 20px;
cursor: pointer;
&:last-child {
padding-right: 0;
}
}
:deep(.arco-steps-item-title) {
font-size: 14px;
color: #262626 !important;
font-weight: 400;
}
:deep(.arco-steps-item-process .arco-steps-item-title) {
color: var(--app-primary-color) !important;
font-weight: 600;
}
:deep(.arco-steps-item-finish .arco-steps-item-title) {
color: var(--app-primary-color) !important;
}
.step-title {
color: var(--color-text-1);
font-weight: 400;
cursor: pointer;
user-select: none;
&:hover {
color: var(--app-primary-color);
}
&.step-title-active {
color: var(--app-primary-color) !important;
font-weight: 600 !important;
}
}
}
.price-modal-footer {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
}
// 排货规则样式
.shipping-rules-section {
flex: 1;
display: flex;
flex-direction: column;
padding: 24px;
overflow: hidden;
}
.tab-pane-spin {
flex: 1;
min-height: 0;
width: 100%;
overflow: hidden;
display: flex !important;
flex-direction: column;
:deep(.arco-spin-children) {
flex: 1;
min-height: 0;
overflow: hidden;
display: flex;
flex-direction: column;
}
}
.shipping-rules-header {
margin-bottom: 24px;
display: flex;
justify-content: space-between;
align-items: center;
.scheme-selection {
display: flex;
align-items: center;
gap: 16px;
.scheme-title {
font-size: 16px;
font-weight: 600;
color: var(--color-text-1);
}
.scheme-radio-group {
display: flex;
gap: 24px;
}
.scheme-explanation {
font-size: 14px;
color: var(--color-text-3);
margin-left: 8px;
}
}
.shipping-rules-header-actions {
display: flex;
align-items: center;
gap: 12px;
.add-provider-btn {
display: flex;
align-items: center;
gap: 6px;
}
}
}
.shipping-rules-content {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
.shipping-provider-table-container {
flex: 1;
overflow: auto;
border: 1px solid #e8e8e8;
border-radius: 6px;
.shipping-provider-table {
width: 100%;
table-layout: fixed;
border-collapse: collapse;
/* 权重固定 100px;服务渠道 : 判断条件 = 3 : 7 */
--shipping-fixed-cols: 280px;
col.shipping-col-serial {
width: 80px;
}
col.shipping-col-weight {
width: 100px;
}
col.shipping-col-actions {
width: 100px;
}
col.shipping-col-channel {
width: calc((100% - var(--shipping-fixed-cols)) * 3 / 10);
}
col.shipping-col-match-condition {
width: calc((100% - var(--shipping-fixed-cols)) * 7 / 10);
}
.shipping-col-channel-cell,
.shipping-col-weight-cell,
.shipping-col-match-condition-cell {
min-width: 0;
}
thead {
background-color: var(--color-fill-1);
th {
padding: 12px 16px;
text-align: left;
font-weight: 600;
color: var(--color-text-1);
border-bottom: 1px solid #e8e8e8;
border-right: 1px solid #e8e8e8;
&:last-child {
border-right: none;
}
}
}
tbody {
tr {
border-bottom: 1px solid var(--color-border-2);
&:last-child {
border-bottom: none;
}
&:hover {
background-color: var(--color-fill-1);
}
td {
padding: 12px 16px;
vertical-align: middle;
border-right: 1px solid var(--color-border-2);
&:last-child {
border-right: none;
}
&.shipping-service-channel-cell {
text-align: left;
.shipping-service-channel-select {
width: 100%;
}
}
}
}
}
.match-condition-cell {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
.match-condition-summary {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 13px;
color: var(--color-text-1);
font-family: var(--app-font-mono);
&.is-empty {
color: var(--color-text-3);
font-family: inherit;
}
&.is-legacy {
color: var(--h5-warning, #ff7d00);
font-family: inherit;
}
}
.match-condition-edit-btn {
flex-shrink: 0;
color: var(--app-primary-color);
}
}
.action-btn {
color: var(--app-primary-color);
&:hover {
color: #1a6b6b;
background-color: #f0f9f9;
}
&.delete-btn {
color: #f53f3f;
&:hover {
color: #d32f2f;
background-color: #fff1f0;
}
}
}
}
}
}
.match-condition-modal-hint {
margin: 0 0 12px;
font-size: 13px;
line-height: 1.5;
color: var(--color-text-2);
}
// 发布记录样式
.publish-records-section {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
padding: 16px 24px 24px;
overflow: hidden;
gap: 12px;
}
.publish-record-content-spin {
display: block;
width: 100%;
/* 高度随正文,由外层 .code-content 滚动,避免 spin 把面板撑破 */
height: auto;
min-height: 80px;
:deep(.arco-spin-children) {
height: auto;
}
}
.publish-records-toolbar {
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
min-height: 32px;
}
.publish-records-hint {
font-size: 12px;
line-height: 18px;
color: var(--color-text-3);
white-space: nowrap;
}
.publish-records-container {
flex: 1;
min-height: 0;
height: 100%;
display: flex;
gap: 0;
border: 1px solid var(--color-border-2, #e8e8e8);
border-radius: 8px;
overflow: hidden;
background: var(--app-card-bg, #fff);
}
.publish-records-left {
width: 320px;
flex-shrink: 0;
min-height: 0;
align-self: stretch;
border-right: 1px solid var(--color-border-2, #e8e8e8);
display: flex;
flex-direction: column;
padding: 12px;
overflow: hidden;
background-color: var(--app-card-bg, #fff);
.version-list {
flex: 1;
min-height: 0;
overflow-x: hidden;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 8px;
padding-right: 2px;
}
.version-item {
--vr-hover: rgba(15, 16, 17, 0.04);
--vr-selected: var(--app-primary-color-light);
--vr-selected-text: var(--app-primary-color);
--vr-selected-border: color-mix(in srgb, var(--app-primary-color) 32%, transparent);
--vr-muted: var(--color-text-3);
appearance: none;
-webkit-appearance: none;
width: 100%;
border: 1px solid rgba(15, 16, 17, 0.07);
text-align: left;
padding: 10px 12px;
background-color: var(--color-fill-1);
border-radius: 8px;
cursor: pointer;
box-shadow: none;
transition:
background-color 0.2s ease,
border-color 0.2s ease;
&:hover {
background-color: var(--vr-hover);
border-color: rgba(15, 16, 17, 0.1);
}
&.active {
background: var(--vr-selected);
border-color: var(--vr-selected-border);
box-shadow: none;
.version-item-number {
color: var(--vr-selected-text);
font-weight: 560;
}
.version-item-footer,
.version-item-user,
.version-item-time {
color: var(--vr-muted);
}
}
.version-item-header {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
margin-bottom: 8px;
}
.version-item-number {
min-width: 0;
font-size: 13px;
font-weight: 500;
color: var(--color-text-1);
line-height: 18px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.version-item-footer {
display: flex;
justify-content: space-between;
align-items: center;
gap: 8px;
font-size: 12px;
color: var(--color-text-3);
line-height: 18px;
}
.version-item-user,
.version-item-time {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.version-item-time {
flex-shrink: 0;
max-width: 58%;
}
}
}
.version-item-badge {
flex-shrink: 0;
display: inline-flex;
align-items: center;
height: 20px;
padding: 0 8px;
border-radius: 10px;
font-size: 12px;
line-height: 20px;
font-weight: 500;
&.type-effective {
color: #508a24;
background: color-mix(in srgb, #508a24 12%, #fff);
}
&.type-rollback {
color: #d48806;
background: color-mix(in srgb, #faad14 16%, #fff);
}
&.type-invalid {
color: #cf1322;
background: color-mix(in srgb, #f53f3f 12%, #fff);
}
}
.publish-records-right {
flex: 1;
min-width: 0;
min-height: 0;
align-self: stretch;
display: flex;
flex-direction: column;
padding: 16px 20px;
background-color: var(--app-card-bg, #fff);
overflow: hidden;
.right-header {
flex-shrink: 0;
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
margin-bottom: 12px;
padding-bottom: 12px;
border-bottom: 1px solid var(--color-border-2, #e8e8e8);
}
.rollback-btn {
color: var(--app-primary-color);
&:hover:not(:disabled) {
color: var(--app-primary-color);
border-color: color-mix(in srgb, var(--app-primary-color) 45%, #fff);
background: color-mix(in srgb, var(--app-primary-color) 8%, #fff);
}
}
.version-notes {
display: flex;
align-items: center;
gap: 6px;
color: var(--color-text-2);
font-size: 12px;
}
.notes-icon {
cursor: pointer;
font-size: 16px;
vertical-align: middle;
&--remark {
color: #faad14;
}
&--ai {
color: var(--app-primary-color, #1d7281);
}
}
.code-content {
flex: 1;
min-height: 0;
overflow: auto;
border: 1px solid var(--color-border-2, #e8e8e8);
border-radius: 6px;
background: var(--color-fill-1, #f7f8fa);
}
.code-pre {
margin: 0;
padding: 12px 14px;
font-family: var(--app-font-mono);
font-size: 12px;
line-height: 1.55;
color: var(--color-text-1);
white-space: pre-wrap;
word-break: break-word;
}
}
.publish-records-empty {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
padding: 24px 12px;
}
.publish-date-modal {
padding: 8px 0;
.publish-date-actions {
display: flex;
justify-content: flex-end;
gap: 12px;
margin-top: 16px;
}
}
// 新增产品弹窗样式
.add-product-modal-content {
padding: 8px 0;
.form-container {
max-width: 100%;
}
.form-section-title {
margin: 0 0 12px;
padding: 0 0 8px;
font-size: 13px;
font-weight: 600;
color: var(--color-text-2);
border-bottom: 1px solid var(--color-border-2);
&:not(:first-child) {
margin-top: 4px;
}
}
.label-with-tip {
display: inline-flex;
align-items: center;
gap: 4px;
}
.tip-icon {
color: var(--color-text-3);
cursor: help;
font-size: 14px;
}
.add-product-advanced-toggle {
margin: -8px 0 8px;
}
.form-row {
margin-bottom: 16px;
}
}
.modal-footer {
display: flex;
justify-content: flex-end;
gap: 12px;
}
// 保存确认弹窗样式
.save-confirm-modal {
padding: 8px 0;
.save-confirm-message {
font-size: 14px;
color: var(--color-text-1);
line-height: 1.6;
p {
margin: 0;
}
}
}
// 发布弹窗样式
.publish-modal-spin {
display: block;
width: 100%;
min-height: 240px;
:deep(.arco-spin-container),
:deep(.arco-spin) {
width: 100%;
height: 100%;
}
}
.release-content.slim {
display: flex;
flex-direction: column;
gap: 12px;
flex: 1;
min-height: 0;
height: 100%;
overflow: hidden;
}
.publish-scroll {
flex: 1;
min-height: 0;
overflow: auto;
display: flex;
flex-direction: column;
gap: 12px;
padding-right: 2px;
}
.publish-flow {
display: grid;
grid-template-columns: 1fr 48px 1fr;
align-items: stretch;
gap: 0;
flex-shrink: 0;
}
.flow-connector {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 0;
color: #c9cdd4;
padding: 0 4px;
.flow-connector-line {
width: 100%;
height: 2px;
background: linear-gradient(90deg, #e5e6eb, var(--app-primary-color, #2d8c8c), var(--color-border-2));
border-radius: 1px;
}
.flow-connector-arrow {
margin-top: -11px;
font-size: 22px;
line-height: 1;
color: var(--app-primary-color, #2d8c8c);
font-weight: 600;
}
}
.flow-card {
display: flex;
flex-direction: column;
min-height: 0;
padding: 12px 14px;
border: 1px solid var(--color-border-2);
border-radius: 8px;
background: var(--app-card-bg);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
cursor: pointer;
transition: border-color 0.15s, box-shadow 0.15s, background 0.15s;
&:hover:not(.is-locked) {
border-color: #c9cdd4;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}
&.is-current {
border-color: var(--app-primary-color, #2d8c8c);
box-shadow: 0 0 0 1px var(--app-primary-color, #2d8c8c), 0 2px 8px rgba(45, 140, 140, 0.12);
background: var(--app-card-bg);
}
&.is-done {
border-color: #b7eb8f;
background: #fcfffc;
}
&.is-ready:not(.is-current) {
border-color: #ffd591;
background: #fffdf8;
}
&.is-locked {
cursor: not-allowed;
background: var(--color-fill-2);
opacity: 0.78;
.flow-badge {
background: #c9cdd4;
}
}
}
.flow-card-head {
display: flex;
align-items: flex-start;
gap: 10px;
}
.flow-badge {
width: 36px;
height: 36px;
border-radius: 8px;
display: inline-flex;
align-items: center;
justify-content: center;
font-size: 13px;
font-weight: 700;
letter-spacing: 0.02em;
color: #fff;
background: var(--app-primary-color, #2d8c8c);
flex-shrink: 0;
}
.flow-card-titles {
flex: 1;
min-width: 0;
}
.flow-card-title {
font-size: 15px;
font-weight: 600;
color: var(--color-text-1);
line-height: 1.35;
}
.flow-card-desc {
margin-top: 2px;
font-size: 12px;
color: var(--color-text-3);
line-height: 1.4;
}
.flow-card-body {
flex: 1;
margin-top: 8px;
min-height: 0;
}
.flow-card-hint {
margin: 0;
font-size: 12px;
color: var(--color-text-3);
line-height: 1.5;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.flow-result {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px 8px;
}
.flow-result-label {
font-size: 12px;
color: var(--color-text-2);
font-weight: 500;
}
.flow-result-summary {
flex: 1 1 100%;
font-size: 12px;
color: var(--color-text-2);
line-height: 1.5;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.flow-card-foot {
margin-top: 10px;
}
.publish-step2 {
display: flex;
flex-direction: column;
gap: 16px;
}
.step2-card {
border: 1px solid var(--color-border-2);
border-radius: 8px;
background: var(--color-fill-2);
padding: 14px 16px;
display: flex;
flex-direction: column;
gap: 10px;
}
.step2-card-title {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
font-weight: 600;
color: var(--color-text-1);
}
.step2-summary {
margin: 0;
font-size: 13px;
color: var(--color-text-2);
line-height: 1.5;
}
.step2-reanalyze {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
}
.step2-reanalyze-hint {
font-size: 12px;
color: var(--color-text-3);
}
.step2-form {
display: flex;
flex-direction: column;
gap: 14px;
}
.step2-field {
display: flex;
flex-direction: column;
gap: 6px;
}
.step2-label {
font-size: 13px;
font-weight: 500;
color: var(--color-text-2);
}
.step2-time-hint {
font-size: 12px;
color: var(--color-text-3);
}
.step2-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
padding-top: 4px;
}
.ai-report-brief {
font-size: 12px;
color: var(--color-text-2);
line-height: 1.5;
padding: 6px 10px;
background: var(--color-fill-2);
border: 1px solid var(--color-border-2);
border-radius: 4px;
}
.ai-confirm-report {
.ai-confirm-label {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
font-size: 13px;
color: var(--color-text-2);
font-weight: 500;
}
}
.ai-report-notes-label {
margin-left: 8px;
}
.ai-history-pre {
margin: 0;
max-width: 420px;
max-height: 280px;
overflow: auto;
white-space: pre-wrap;
word-break: break-word;
font-size: 12px;
line-height: 1.5;
}
.step2-report-details {
border: 1px solid var(--color-border-2);
border-radius: 6px;
background: var(--color-fill-1);
padding: 8px 12px;
summary {
cursor: pointer;
user-select: none;
font-size: 13px;
color: var(--color-text-2);
font-weight: 500;
}
.mt-8 {
margin-top: 8px;
}
}
.step2-high-risk {
padding: 10px 12px;
border-radius: 6px;
background: #ffece8;
border: 1px solid #fdcdc5;
color: #cb272d;
font-size: 13px;
}
.mb-15px {
margin-bottom: 15px;
}
.add-factor-value-modal {
.add-factor-value-actions {
display: flex;
justify-content: flex-end;
margin-bottom: 8px;
}
}
.batch-fill-form {
.batch-fill-meta {
margin-bottom: 12px;
color: var(--color-text-2);
font-size: 13px;
}
}
// 响应式设计
@media (max-width: 768px) {
.sales-product-layout {
flex-direction: column;
}
.left-sidebar {
width: 100%;
height: 300px;
}
.form-row {
flex-direction: column;
gap: 16px;
}
.timeliness-inputs {
flex-direction: column;
gap: 8px;
}
}
</style>
<style lang="less">
/* ModalPro 挂到 body:限高 + 垂直水平居中 */
.arco-modal-wrapper:has(.sales-product-publish-modal) {
display: flex;
align-items: center;
justify-content: center;
}
.arco-modal.sales-product-publish-modal {
top: auto !important;
margin: 0 auto;
max-height: 85vh;
display: flex;
flex-direction: column;
.arco-modal-header {
flex-shrink: 0;
}
.arco-modal-body {
flex: 1;
min-height: 0;
}
}
/* 价格配置弹窗:允许 Handsontable 下拉层溢出 */
.arco-modal.sales-price-config-modal {
.arco-modal-body {
overflow: visible !important;
}
}
.arco-modal.sales-price-config-modal .handsontable.listbox,
.arco-modal.sales-price-config-modal .autocompleteEditor.handsontable.listbox {
z-index: 5600 !important;
}
</style>