import { ssIcon, commonIcon } from "./icon-config.js";
import * as IndexComponents from "./ss-index-components.js";
import * as EchartComponents from "./ss-echarts-compnents.js";
import {
isNum,
toStyleStr,
buildThumbUrl,
openServiceDialog,
pickSearchParams,
} from "./tools.js"; // 功能说明:组件内统一构建缩略图URL、打开服务弹窗,减少 JSP 层字段转换 by xu 20260122
import { EVEN_VAR } from "./EventBus.js";
// import * as elements from "../lib/element-plus.js";
(function () {
const {
createApp,
ref,
reactive,
watch,
onMounted,
onBeforeUnmount,
h,
computed,
resolveComponent,
watchEffect,
nextTick,
onVnodeMounted,
Teleport,
inject,
provide,
} = Vue;
// 弹窗默认遮罩z-index
let currentZIndex = 100;
// 目前已存在的弹窗
const topWindow = window.top;
topWindow.dialogInstances = topWindow.dialogInstances || [];
// 新建弹窗
function createSsDialogInstance(setting, callbackEvent) {
currentZIndex += 10; // 动态提升 z-index
const container = document.createElement("div");
document.body.appendChild(container);
const app = Vue.createApp({
render() {
return h(SsDialog, {
...setting,
zIndex: currentZIndex,
onClose() {
document.body.removeChild(container); // 仅移除弹窗容器
const index = topWindow.dialogInstances.indexOf(app);
if (index > -1) {
topWindow.dialogInstances.splice(index, 1); // 移除实例
}
// 关闭后的回调
if (callbackEvent && typeof callbackEvent === "function") {
callbackEvent();
}
app.unmount(); // 仅卸载弹窗实例
if (container.parentNode) {
container.parentNode.removeChild(container); // 确保移除容器
}
},
});
},
});
topWindow.dialogInstances.push({ app, callbackEvent, container });
app.component("ss-mark", SsMark); // 注册 ss-mark 组件
app.component("ss-icon", SsIcon);
app.component("ss-full-style-header", SsFullStyleHeader); // 注册 ss-full-style-header 组件
app.mount(container);
}
// ss-breadcrumb 一级菜单页面面包屑
const SsBreadcrumb = {
name: "SsBreadcrumb",
props: {
level: {
type: Object,
default: null,
},
},
setup(props) {
const currentMenu = ref(null);
const folderPath = ref([]);
const eventBus = window.parent.sharedEventBus;
// 监听页面变化
onMounted(() => {
// 获取初始页面
currentMenu.value = eventBus.getState(EVEN_VAR.currentPage);
folderPath.value = eventBus.getState("folderPath") || [];
// 订阅页面变化
eventBus.subscribe(EVEN_VAR.currentPage, (page) => {
currentMenu.value = page;
});
eventBus.subscribe("folderPath", (path) => {
folderPath.value = path || [];
});
});
// 修改点击处理函数
const handlePathClick = (index) => {
if (props.level?.onBack) {
// 截取到点击的位置,后面的路径会被销毁
const newPath = folderPath.value.slice(0, index + 1);
eventBus.publish("folderPath", newPath);
// 返回到对应层级
const targetFolder = newPath[newPath.length - 1]?.folder || null;
props.level.onBack(targetFolder);
}
};
const SsCommonIcon = resolveComponent("SsCommonIcon");
return () =>
h("div", { class: "bread-crumb" }, [
currentMenu.value &&
h(
"div",
{
onClick: () => {
if (props.level?.onBack) {
eventBus.publish("folderPath", []);
props.level.onBack(null); // 返回到根目录
} else {
eventBus.publish(EVEN_VAR.currentPage, currentMenu.value);
}
},
},
currentMenu.value.label || currentMenu.value.name
),
...(folderPath.value || [])
.map((folder, index) => [
h(SsCommonIcon, { class: "common-icon-arrow-right" }),
h(
"div",
{
class: "bread-crumb-item",
onClick: () => handlePathClick(index),
style: { cursor: "pointer" },
},
folder.title
),
])
.flat(),
]);
},
};
// ss-input form表单的输入
const SsInput = {
name: "SsInp", //把SsInput改为SsInp Ben(20251225)
inheritAttrs: false, // 不直接继承属性到组件根元素
props: {
name: {
type: String,
required: true,
default: "",
},
// 接收 v-model 绑定的值
errTip: {
type: String,
},
required: {
type: Boolean,
default: false,
},
placeholder: {
type: String,
default: "请输入",
},
defaultValue: [String, Number],
modelValue: [String, Number],
// 新增:附件配置
fj: {
type: Object,
default: null,
},
// 新增:param 配置(用于附件功能)
param: {
type: Object,
default: null,
},
// 新增:高度配置
height: {
type: String,
default: "",
},
// 功能说明:传 height 时允许回车换行(多行输入);未传 height 默认单行 by xu 20260204
// 功能说明:onChange 全局回调 prop,桥接 API 赋值时自动触发 by xu 20260416
onchange: {
type: String,
required: false,
},
},
emits: ["update:modelValue", "input", "blur", "change"], // 允许更新 v-model 绑定的值
setup(props, { emit }) {
const errMsg = ref("");
const inputRef = ref(null);
const textareaRef = ref(null);
const inputValue = ref(props.modelValue || props.defaultValue || "");
const contentFloatingDiv = ref(false); // 控制浮动 DIV 的显示
const floatingDivPosition = ref("bottom"); // 'bottom' 或 'top'
const isFocused = ref(false); // 跟踪焦点状态
// 附件相关变量(仅在传入 param 时初始化)
const buttonConfigRaw = props.param && props.param.button ? props.param.button : null;
const buttonArray = Array.isArray(buttonConfigRaw)
? buttonConfigRaw
: buttonConfigRaw
? [buttonConfigRaw]
: [];
const attachmentButton =
buttonArray.find((btn) => btn && btn.cmsAddUrl && btn.cmsUpdUrl) || null;
const hasAttachmentButton = !!attachmentButton;
const attachmentFieldName =
attachmentButton?.name || (props.fj && props.fj.name) || "fjid";
const attachmentButtonText =
attachmentButton?.desc ||
attachmentButton?.text ||
props.fj?.desc ||
props.fj?.text ||
"附件";
const resolvePageSearchParam = (key) => {
try {
return new URL(window.location.href).searchParams.get(key) || "";
} catch (error) {
return "";
}
};
const resolveAttachmentObjName = () =>
props.param?.obj ||
props.param?.ssObjName ||
document.querySelector("[name='ssObjName']")?.value ||
window?.ss?.dom?.ssObjName ||
resolvePageSearchParam("ssObjName") ||
"";
const resolveAttachmentObjId = () =>
props.param?.ssObjId ||
props.param?.objId ||
document.querySelector("[name='ssObjId']")?.value ||
resolvePageSearchParam("ssObjId") ||
"";
const buildAttachmentCreatePayload = () => ({
name: attachmentFieldName,
ssNrObjName: resolveAttachmentObjName(),
ssNrObjId: resolveAttachmentObjId(),
});
const buildAttachmentDialogQuery = () =>
"&nrid=T-" +
fjid.value +
"&objectId=" +
fjid.value +
"&objectName=" +
attachmentFieldName +
"&callback=" +
(window[attachmentFieldName + "CallbackName"] || "");
let fjid = ref(attachmentButton?.val || null);
let mode = props.param ? props.param.mode : null;
// 功能说明:只有存在非空校验(notNull)且值为空时,才显示红线 by xu 20260402
const hasNotNullRule = () => {
const validations = window.ssVm?.validations?.get(props.name);
if (!validations || validations.length === 0) return false;
return validations.some(v => v.ruleName && v.ruleName.includes('notNull'));
};
const showRequired = computed(() => {
const validations = window.ssVm?.validations?.get(props.name);
if (!validations || validations.length === 0) return false;
// 检查是否存在 notNull 规则
const hasNotNull = validations.some(v => v.ruleName && v.ruleName.includes('notNull'));
// 有非空规则且值为空时显示红线
if (hasNotNull && !inputValue.value) {
return true;
}
return false;
});
// 计算floatdiv应该向上还是向下展开
const calculateFloatingDivPosition = () => {
nextTick(() => {
const textarea = inputRef.value;
if (!textarea) return;
const rect = textarea.getBoundingClientRect();
const viewportHeight = window.innerHeight;
// 预估floatdiv的高度(最多5行 * 20px + 上下padding + border)
const estimatedFloatDivHeight = 20 * 5 + 10 + 2; // 5行 + padding + border = 112px
// 检查下方空间
const spaceBelow = viewportHeight - rect.bottom;
// 如果下方空间不足,且上方空间足够,则向上展开
if (
spaceBelow < estimatedFloatDivHeight &&
rect.top > estimatedFloatDivHeight
) {
floatingDivPosition.value = "top";
} else {
floatingDivPosition.value = "bottom";
}
});
};
// 计算floatdiv的top偏移量
const getFloatingDivTop = computed(() => {
if (props.height) {
// 有height时,padding是5px
return "5px";
} else {
// 没有height时是单行居中,需要计算居中位置
// 假设input-container高度是32px(或者从CSS读取),单行20px
// 居中偏移 = (容器高度 - 行高) / 2 = (32 - 20) / 2 = 6px
return "6px";
}
});
const validate = () => {
if (window.ssVm) {
const result = window.ssVm.validateField(props.name);
errMsg.value = result.valid ? "" : result.message;
}
};
// 功能说明:调用全局 onChange 回调 by xu 20260416
const callGlobalOnchg = (value) => {
if (props.onchange && typeof props.onchange === "string") {
if (
typeof window !== "undefined" &&
window[props.onchange] &&
typeof window[props.onchange] === "function"
) {
try {
window[props.onchange](value);
} catch (error) {
console.error(`调用全局函数 ${props.onchange} 时出错:`, error);
}
}
}
};
// 使用 watch 监听 props.errTip 和 props.modelValue 的变化
watch(
() => props.errTip,
(newVal) => {
errMsg.value = newVal;
},
{ immediate: true }
);
watch(
() => props.modelValue,
(newVal) => {
inputValue.value = newVal;
// 桥接 API 赋值时触发全局 onChange by xu 20260416
callGlobalOnchg(newVal);
}
);
// 挂载时的逻辑
onMounted(() => {
errMsg.value = props.errTip;
inputValue.value = props.modelValue || props.defaultValue || "";
});
// 计算并调整textarea的高度
const adjustHeight = () => {
nextTick(() => {
const textarea = textareaRef.value;
if (!textarea) return;
// floatDiv的textarea始终自动计算高度,不受props.height影响
// 重置高度以获得正确的scrollHeight
textarea.style.height = "auto";
// 计算新高度 - 统一限制为5行
const lineHeight = parseInt(
getComputedStyle(textarea).lineHeight,
10
);
const maxHeight = lineHeight * 5; // 统一为5行
const newHeight = Math.min(textarea.scrollHeight, maxHeight);
textarea.style.height = `${newHeight}px`;
});
};
// 检查是否应该显示浮动窗口(需要同时满足:有焦点 + 内容超出)
// 修复新增页面点击就出现floatdiv的问题 by xu 20251212
const checkShouldShowFloatingDiv = () => {
const textarea = inputRef.value;
if (!textarea) return false;
// 首先检查是否有内容,没有内容时不显示floatdiv by xu 20251212
if (!inputValue.value || inputValue.value.toString().trim() === "") {
console.log("[floatdiv] 内容为空,不显示floatdiv");
return false;
}
// 判断内容是否超出 by xu 20251212
// 同时检查横向和纵向溢出,任一方向溢出都应显示floatdiv
// 纵向溢出需要加容差值,避免padding/border导致的误判 by xu 20251212
const verticalTolerance = 5; // 容差值5px
const isHorizontalOverflow =
textarea.scrollWidth > textarea.clientWidth;
const isVerticalOverflow =
textarea.scrollHeight > textarea.clientHeight + verticalTolerance;
const isOverflow = isHorizontalOverflow || isVerticalOverflow;
console.log(
"[floatdiv] 溢出检测 - scrollWidth:",
textarea.scrollWidth,
"clientWidth:",
textarea.clientWidth,
"horizontalOverflow:",
isHorizontalOverflow
);
console.log(
"[floatdiv] 溢出检测 - scrollHeight:",
textarea.scrollHeight,
"clientHeight:",
textarea.clientHeight,
"tolerance:",
verticalTolerance,
"verticalOverflow:",
isVerticalOverflow
);
const shouldShow = isFocused.value && isOverflow;
console.log(
"[floatdiv] 最终判断 - isFocused:",
isFocused.value,
"isOverflow:",
isOverflow,
"shouldShow:",
shouldShow
);
// 需要同时满足:有焦点 + 内容超出
return shouldShow;
};
// 定义事件处理函数
const onInput = (event) => {
const newValue = event.target.value;
inputValue.value = newValue;
emit("update:modelValue", newValue);
validate(); // 输入时验证
nextTick(() => {
// 检查是否需要显示浮动div
contentFloatingDiv.value = checkShouldShowFloatingDiv();
// 如果需要显示floatdiv,计算其位置
if (contentFloatingDiv.value) {
calculateFloatingDivPosition();
}
});
adjustHeight();
};
const onFocus = (event) => {
// 设置焦点状态为true
isFocused.value = true;
adjustHeight();
// 检查是否应该显示浮动窗口
nextTick(() => {
contentFloatingDiv.value = checkShouldShowFloatingDiv();
if (contentFloatingDiv.value) {
calculateFloatingDivPosition();
}
});
};
// 失去焦点时进行验证
const onBlur = (event) => {
emit("blur", event.target);
validate(); // 失焦时验证
nextTick(() => {
// 如果焦点不在 textarea 上,则隐藏浮动 div
if (!document.activeElement.classList.contains("input-control")) {
isFocused.value = false;
contentFloatingDiv.value = false;
}
});
};
const onChange = (event) => {
inputValue.value = event.target.value || "";
emit("change", inputValue.value);
};
const onMouseover = (event) => {
nextTick(() => {
// setTimeout(contentFloatingDiv.value = true, 500)
});
};
const onMouseleave = (event) => {
// contentFloatingDiv.value = false
};
// 功能说明:传了 height 视为多行允许回车;未传 height 拦截回车(单行表现) by xu 20260204
const onKeydown = (event) => {
const allowMultiline =
typeof props.height === "string" && props.height.trim() !== "";
if (!allowMultiline && event.key === "Enter") {
event.preventDefault();
}
};
// 附件按钮点击处理(从 SsEditor 搬运)
const onAttachmentClick = (e) => {
e.preventDefault();
if (!hasAttachmentButton || !attachmentButton) {
console.warn("未配置 param 参数");
return;
}
console.log("附件点击了");
console.log("param", props.param);
console.log("cmsAddUrl", attachmentButton.cmsAddUrl);
// 如果 fjid 为空,先调用 cmsAddUrl 创建
if (fjid.value == null || fjid.value == "") {
$.ajax({
type: "post",
url: attachmentButton.cmsAddUrl,
async: false,
data: buildAttachmentCreatePayload(),
success: function (_fjid) {
console.log("cmsAddUrl success", _fjid);
fjid.value = _fjid;
},
});
}
// 构建参数字符串
const str = buildAttachmentDialogQuery();
console.log("str", str);
// 打开附件编辑对话框
SS.openDialog({
src: attachmentButton.cmsUpdUrl + str,
headerTitle: "编辑",
width: 900,
high: 664,
zIndex: 51,
});
};
return {
errMsg,
inputValue,
showRequired,
onInput,
onBlur,
onChange,
onMouseover,
onMouseleave,
onKeydown, // 新增:键盘事件处理 by xu 20251212
contentFloatingDiv,
floatingDivPosition,
getFloatingDivTop,
inputRef,
textareaRef,
onFocus,
onAttachmentClick,
attachmentFieldName,
attachmentButtonText,
hasAttachmentButton,
fjid, // 附件 ID,用于隐藏字段
};
},
render() {
const { resolveComponent, h } = Vue;
const SsIcon = resolveComponent("ss-icon");
const SsEditorIcon = resolveComponent("SsEditorIcon");
// 构建主textarea的样式
const mainTextareaStyle = {};
if (this.height) {
mainTextareaStyle.height = "auto";
// mainTextareaStyle.paddingTop = '5px'; // 有高度时加上padding-top
// mainTextareaStyle.paddingBottom = '5px'; // 有高度时加上padding-bottom
} else {
// 没有指定height时,固定为单行高度
mainTextareaStyle.height = "20px"; // 行高20px
mainTextareaStyle.lineHeight = "20px"; // 确保单行垂直居中
mainTextareaStyle.display = "flex";
mainTextareaStyle.marginBottom = "5px";
}
// 如果有附件按钮,为按钮留出空间
if (this.fj || this.hasAttachmentButton) {
//加上&&this.param.button条件 Ben(20251221)
mainTextareaStyle.paddingRight = "75px";
}
const mainTextareaRows = this.height
? Math.floor(parseFloat("80px") / 20)
: 1;
return h("div", { class: "input" }, [
h("div", { class: "input-container" }, [
h("div", { class: "input", style: "padding:5px 0" }, [
h("textarea", {
ref: "inputRef",
class: "input-control",
name: this.name,
value: this.inputValue,
onInput: this.onInput,
onFocus: this.onFocus,
onBlur: this.onBlur,
onChange: this.onChange,
onKeydown: this.onKeydown, // 新增:禁止回车换行 by xu 20251212
placeholder: this.placeholder,
onMouseover: this.onMouseover, // 监听鼠标悬停
onMouseleave: this.onMouseleave, // 监听鼠标离开
rows: mainTextareaRows,
...this.$attrs,
style: mainTextareaStyle,
autocomplete: "off",
}),
// 附件按钮(优先使用 param,兼容旧的 fj)
this.fj || this.hasAttachmentButton //加上&&this.param.button条件 Ben(20251221)
? h(
"button",
{
type: "button",
class: "fj-button",
onClick: this.hasAttachmentButton
? this.onAttachmentClick
: (e) => {
e.preventDefault();
console.log("附件配置:", this.fj);
},
},
[
h(SsEditorIcon, {
class: "editor-icon-link",
}),
h("span", { class: "fj-button-text" }, this.attachmentButtonText || "附件"),
]
)
: null,
]),
this.contentFloatingDiv || ""
? h(
"div",
{
class: "floating-div",
style:
this.floatingDivPosition === "bottom"
? {
// 向下展开: 覆盖原输入框,top对齐首行
top: this.getFloatingDivTop,
bottom: "auto",
}
: {
// 向上展开: 同样覆盖原输入框,但从底部开始计算
top: "auto",
bottom: this.height ? "5px" : "6px", // 对齐到原textarea的底部padding位置
},
},
[
h("textarea", {
ref: "textareaRef",
class: "input-control",
value: this.inputValue,
onInput: this.onInput,
onBlur: this.onBlur,
onFocus: this.onFocus,
onKeydown: this.onKeydown, // 新增:禁止回车换行 by xu 20251212
onMouseover: this.onMouseover, // 监听鼠标悬停
onMouseleave: this.onMouseleave, // 监听鼠标离开
autocomplete: "off",
onVnodeMounted: (vnode) => {
vnode.el.focus();
},
}),
]
)
: null,
// this.errMsg ? h(SsValidate, { errMsg: this.errMsg }) : null,
]),
// 附件相关的隐藏字段(仅在有 param 时才渲染)
this.param && [
// fjid 隐藏字段(只有当 fjid 有值时才渲染)
this.fjid &&
h("input", {
type: "hidden",
name: this.attachmentFieldName || "fjid",
value: this.fjid,
}),
// 其他隐藏字段根据 name 生成
/* 去掉。文本框不需要(这是富文本才有的) Ben 20251205
h("input", {
type: "hidden",
name: this.name.replace(/wj$/, "") + "Edit",
value: this.inputValue
}),
*/
// h("input", {
// type: "hidden",
// name: this.name.replace(/wj$/, "") + "wj",
// value: this.inputValue
// }),
/* 去掉。文本框不需要(这是富文本才有的) Ben 20251205
h("input", {
type: "hidden",
name: "ueditorpath",
value: this.name
}),
*/
],
]);
},
};
// ss-normal-input 登录输入
const SsLoginInput = {
name: "SsLoginInput",
inheritAttrs: false,
props: {
errTip: {
type: String,
},
type: {
type: String,
default: "text",
},
required: {
type: Boolean,
default: false,
},
placeholder: {
type: String,
default: "请输入",
},
name: {
type: String,
default: "",
},
defaultValue: [String, Number],
modelValue: [String, Number],
},
emits: ["update:modelValue", "input", "blur", "change"], // 允许更新 v-model 绑定的值
setup(props, { emit }) {
const errMsg = ref("");
const inputRef = ref(null);
const textareaRef = ref(null);
const inputValue = ref(props.modelValue || props.defaultValue || "");
// 使用 watch 监听 props.errTip 和 props.modelValue 的变化
watch(
() => props.errTip,
(newVal) => {
errMsg.value = newVal;
},
{ immediate: true }
);
watch(
() => props.modelValue,
(newVal) => {
inputValue.value = newVal;
}
);
// 挂载时的逻辑
onMounted(() => {
errMsg.value = props.errTip;
inputValue.value = props.modelValue || props.defaultValue || "";
});
// 定义事件处理函数
const onInput = (event) => {
const newValue = event.target.value;
inputValue.value = newValue;
emit("update:modelValue", newValue);
};
return { inputValue, onInput, inputRef, textareaRef };
},
render() {
return h("div", { class: "input" }, [
h("div", { class: "input-container" }, [
h("div", { class: "input" }, [
h("input", {
ref: "inputRef",
class: "input-control",
name: this.name,
value: this.inputValue,
onInput: this.onInput,
type: this.type,
placeholder: this.placeholder,
required: this.required,
...this.$attrs,
autocomplete: "off",
}),
]),
]),
]);
},
};
// ss-login-button
const SsLoginButton = {
name: "SsLoginButton",
inheritAttrs: false,
props: {
class: {
type: String,
default: "",
},
text: {
type: String,
default: "",
},
type: {
type: String,
default: "button",
},
},
emits: ["click"],
setup(props, { emit }) {
// 定义事件处理函数
const onClick = (event) => {
// 发射一个 'click' 事件,你可以传递所需的参数
emit("click", event);
};
return { props, onClick };
},
render() {
const SsIcon = resolveComponent("ss-icon");
const SsLoginIcon = resolveComponent("ss-login-icon");
return h(
"button",
{ class: "login-button", type: this.type, onClick: this.onClick },
[
h("span", [h(SsLoginIcon, { class: this.class })]),
h("span", {}, this.text),
]
);
},
};
// ss-objp 下拉选择
const SsObjp = {
name: "SsObjp",
inheritAttrs: false,
props: {
onchange: {
//在此属性传入onChange的window全局回调函数,函数唯一参数是当前选中值 Ben(20251217)
type: String,
required: false,
},
filter: {
type: String,
required: false,
},
filterfield: {
type: String,
required: false,
},
// filterField: {
// //此属性为页面表单元素的name用逗号分隔,作用为在向后台查询下拉菜单选项时,会带上这些name的表单元素的value值 Ben(20260313)
// type: String,
// required: false,
// },
cb: {
type: String,
required: true,
},
url: {
type: String,
required: true,
},
name: {
type: String,
required: true,
},
width: {
type: String,
default: "100%",
},
placeholder: {
type: String,
default: "请选择",
},
inp: {
type: Boolean,
default: false,
},
opt: {
type: Array,
default: () => [],
},
errTip: String,
defaultValue: [String, Number],
modelValue: [String, Number],
direction: {
type: String,
default: "bottom",
},
},
emits: ["update:modelValue", "input", "blur", "change"],
setup(props, { emit }) {
const canInput = props.inp;
const errMsg = Vue.ref(props.errTip);
const selectItem = Vue.ref({});
let inputText = Vue.ref(""); // 用于存储输入框的文本
const popupWinVisible = Vue.ref(false);
const filteredOptions = Vue.ref(props.opt);
const popupDirection = Vue.ref("bottom");
const popupMaxHeight = Vue.ref("none"); // popup最大高度,用于空间不足时限制高度并出滚动条 by xu 20251212
const popupContentAreaMaxHeight = Vue.computed(() => {
if (!popupMaxHeight.value || popupMaxHeight.value === "none")
return null;
const maxHeightNum = Number.parseFloat(popupMaxHeight.value);
if (!Number.isFinite(maxHeightNum)) return null;
// 功能说明:滚动条统一落在 .content-area(CSS 默认如此),因此需要扣掉 popup-win padding-top(10) 与 popup-content padding(15*2) by xu 20260126
const contentAreaMaxHeight = Math.max(60, maxHeightNum - 40);
return `${contentAreaMaxHeight}px`;
});
// 修复表格内下拉弹层被 overflow 截断:popup 使用 Teleport 到 body + fixed 定位 by xu 20260126
const selectContainerRef = Vue.ref(null);
const popupRef = Vue.ref(null);
const teleportRootStyle = Vue.ref({
position: "fixed",
left: "0",
top: "0",
width: "0",
height: "0",
zIndex: 9999,
pointerEvents: "none",
});
const popupLayerStyle = Vue.ref({
position: "fixed",
left: "0",
top: "0",
bottom: "auto", // 功能说明:覆盖 .popup-win.top 的 bottom 定位,避免 fixed 场景被撑高/错位 by xu 20260126
minWidth: "0",
zIndex: 9999,
pointerEvents: "auto",
});
// const showRequired = Vue.computed(() => {
// const hasValidationRule = window.ssVm?.validations?.has(props.name);
// if (!hasValidationRule) return false;
// if (errMsg.value) return true;
// if (!selectItem.value?.value) return true;
// return false;
// });
const validate = () => {
if (window.ssVm) {
const result = window.ssVm.validateField(props.name);
// console.log("validate", window.ssVm.validateField(props.name));
errMsg.value = result.valid ? "" : result.message;
}
};
//在objPicker界面,选中value对应的项
const updateSelectItem = () => {
// console.log(props.opt);
const item = props.opt.find((it) => it.value === props.modelValue);
if (item) {
selectItem.value = item;
inputText.value = item.label;
} else {
selectItem.value = { label: "", value: "" };
inputText.value = "";
}
// validate();
};
Vue.watch(
() => props.errTip,
(newVal) => {
errMsg.value = newVal;
}
);
// 功能说明:调用全局 onChange 回调,必须在 handleModelValueChange 之前定义 by xu 20260416
const callGlobalOnchg = (value, desc) => {
if (props.onchange && typeof props.onchange === "string") {
if (
typeof window !== "undefined" &&
window[props.onchange] &&
typeof window[props.onchange] === "function"
) {
try {
window[props.onchange](value, desc);
} catch (error) {
console.error(`调用全局函数 ${props.onchange} 时出错:`, error);
}
}
}
};
const normalizeObjpResult = (result) => {
const normalized = [];
if (!result) return normalized;
if (Array.isArray(result)) {
result.forEach((item) => {
if (!item || typeof item !== "object") return;
const entry = Object.entries(item)[0];
if (!entry) return;
normalized.push({ label: entry[1], value: entry[0] });
});
return normalized;
}
Object.keys(result).forEach((key) => {
normalized.push({ label: result[key], value: key });
});
return normalized;
};
// 功能说明:封装 modelValue 变化后的联动逻辑,兼容用户点击和桥接 API 赋值 by xu 20260416
const handleModelValueChange = (newValue) => {
updateSelectItem();
if (newValue) {
// 如果当前 options 里没有对应项,去服务端请求回显
const exists = props.opt.some((it) => it.value === newValue);
if (!exists && props.url && props.cb) {
let url = props.url;
if (props.filter) {
const filterObj = props.filter;
for (let k in filterObj) {
url += "&" + k + "=" + filterObj[k];
}
}
const params = new URLSearchParams();
params.append("objectpickerparam", JSON.stringify({ input: props.inp, codebook: props.cb }));
params.append("objectpickertype", "2");
params.append("objectpickervalue", newValue);
axios.post(url, params, {
headers: { "Content-Type": "application/x-www-form-urlencoded" }
}).then((response) => {
if ("timeout" == response.data.statusText) {
alert("网络超时!");
return;
}
if (response.data.result) {
const normalizedResult = normalizeObjpResult(response.data.result);
if (normalizedResult.length === 1) {
let code = normalizedResult[0].value;
let desc = normalizedResult[0].label;
props.opt.length = 0;
props.opt.push({ label: desc, value: code });
updateSelectItem();
callGlobalOnchg(code, desc);
}
}
});
} else if (selectItem.value && selectItem.value.value) {
// options 里有对应项,触发 onChange
callGlobalOnchg(selectItem.value.value, selectItem.value.label);
}
} else {
// 值为空时清空选中
callGlobalOnchg("", "");
}
};
Vue.watch(() => props.modelValue, handleModelValueChange, { immediate: true });
Vue.watch(
() => props.opt,
(newVal) => {
updateSelectItem();
filteredOptions.value = [...newVal];
// console.log("filteredOptions", filteredOptions.value);
}
);
//初始化objPicker在页面刚打开时的默认值
async function initDefaultValue() {
try {
if (props.url && props.cb && props.modelValue) {
let objectPickerParam;
let url = props.url;
//如果有定义过滤器
if (props.filter) {
//包含HTML实体的JSON字符串转为JSON对象,如原字符串是{"dwid":"88"},注意key也必需用单引号包着
// const decodedString = props.filter.replace(/"/g, '"'); // 转换为: {"dwid":"88"}
// objectPickerParam = JSON.parse(decodedString); // 转为json对象
const filterObj = props.filter; // 转为json对象
for (let k in filterObj) {
let v = filterObj[k];
url += "&" + k + "=" + v;
}
objectPickerParam = props.filter; // 转为json对象
objectPickerParam["input"] = props.inp;
objectPickerParam["codebook"] = props.cb;
// alert(url);
} else {
objectPickerParam = { input: props.inp, codebook: props.cb };
}
const objectPickerParamStr = JSON.stringify(objectPickerParam);
const params = new URLSearchParams();
params.append("objectpickerparam", objectPickerParamStr);
params.append("objectpickertype", "2");
params.append("objectpickervalue", props.modelValue); //需回显的值
// alert("1params:"+JSON.stringify(params));
axios
.post(props.url, params, {
headers: {
"Content-Type": "application/x-www-form-urlencoded", // 必须手动设置!
},
})
.then((response) => {
// alert(JSON.stringify(response.data));
if ("timeout" == response.data.statusText) {
alert("网络超时!");
return;
}
if (response.data.result) {
const normalizedResult = normalizeObjpResult(response.data.result);
if (normalizedResult.length === 1) {
let code = normalizedResult[0].value;
let desc = normalizedResult[0].label;
if (props.opt)
props.opt.length = 0; //通过修改数组的length属性,直接清空数组元素,内存会被自动释放。这是性能最优的方式
else {
props.opt = [];
}
props.opt.push({ label: desc, value: code });
updateSelectItem();
// alert('props.opt:'+JSON.stringify(props.opt));
}
}
});
}
} catch (error) {
// callback(null, error.message); // 失败回调,传递错误
}
}
// Vue.onMounted(updateSelectItem);
const doSelectItem = (item) => {
emit("update:modelValue", item.value);
selectItem.value = item;
inputText.value = item.label;
hidePopup();
nextTick(() => {
console.log(item.value + "@@@props.modelValue:" + props.modelValue);
validate();
if (window.ssVm) {
// 遍历所有验证规则,找到依赖当前字段的规则
for (const [field, rules] of window.ssVm.validations.entries()) {
for (const rule of rules) {
if (rule.opt?.relField === props.name) {
// console.log("Found dependent field:", field); // 调试日志
window.ssVm.validateField(field);
}
}
}
}
});
// callGlobalOnchg 已移到 handleModelValueChange 统一处理,避免用户点击和桥接 API 赋值行为不一致 by xu 20260416
};
//可录入的objPicker,更新下拉菜单选项
async function updateOptionBYInputText(inpTxt) {
try {
let objectPickerParam;
let url = props.url;
if (props.url && props.cb) {
//如果有定义过滤器
if (props.filter || props.filterfield) {
let filterObj = props.filter;
if (!props.filter) filterObj = {};
if (props.filter) {
const filterObj = props.filter; // 转为json对象
for (let k in filterObj) {
let v = filterObj[k];
url += "&" + k + "=" + v;
}
}
if (props.filterfield) {
//加上filterfield的值过滤
let filterfieldArr = props.filterfield.split(",");
for (var i = 0; i < filterfieldArr.length; i++) {
let fieldName = filterfieldArr[i];
let fields = document.getElementsByName(fieldName);
if (!fields || fields.length < 1) {
alert("下拉菜单配置的过滤条件" + fieldName + "不存在!");
continue;
}
let v = null;
for (let j = 0; j < fields.length; j++) {
if (fields[j].value) {
v = fields[j].value;
break;
}
}
// let field = document.getElementsByName(fieldName)[0];
// let v = field.value;
if (v) {
url += "&" + fieldName + "=" + v;
filterObj[fieldName] = v;
}
}
console.log("filterfield url:" + url);
}
//包含HTML实体的JSON字符串转为JSON对象,如原字符串是{"dwid":"88"},注意key也必需用单引号包着
// const decodedString = props.filter.replace(/"/g, '"'); // 转换为: {"dwid":"88"}
// objectPickerParam = JSON.parse(decodedString); // 转为json对象
objectPickerParam = filterObj;
objectPickerParam["input"] = props.inp;
objectPickerParam["codebook"] = props.cb;
// alert(url);
} else {
objectPickerParam = { input: props.inp, codebook: props.cb };
}
const objectPickerParamStr = JSON.stringify(objectPickerParam);
const params = new URLSearchParams();
params.append("objectpickerparam", objectPickerParamStr);
params.append("objectpickertype", "1");
if (props.inp && props.inp === true) {
//把"true"改为true Ben(20251209)
params.append("objectpickersearchAll", 0); //只查录入的值
params.append("objectpickerinput", inpTxt); //录入的值
// 功能说明:将输入值也加到 URL 参数,避免后端只读 URL 不读 body by xu 20250408
if (inpTxt) {
url += "&objectpickerinput=" + encodeURIComponent(inpTxt);
}
} else {
params.append("objectpickersearchAll", 1);
}
axios
.post(url, params, {
headers: {
"Content-Type": "application/x-www-form-urlencoded", // 必须手动设置!
},
})
.then((response) => {
if ("timeout" == response.data.statusText) {
alert("网络超时!");
return;
}
// 先清空选项 by xu 20251212
if (props.opt) {
props.opt.length = 0;
} else {
props.opt = [];
}
if (response.data.result) {
const normalizedResult = normalizeObjpResult(response.data.result);
// console.log("params:"+params+"@@response.data:"+JSON.stringify(response.data));
if (normalizedResult.length > 0) {
normalizedResult.forEach((option) => {
props.opt.push(option);
});
// console.log('###inpTxt:'+inpTxt+';');
if (
props.inp &&
props.inp === true && //把"true"改为true Ben(20251209)
inpTxt.length > 0
) {
//对于可录入的,用已录入的值作过滤
filteredOptions.value = props.opt.filter((option) =>
option.label
.toLowerCase()
.includes(inputText.value.toLowerCase())
);
// 可录入的objPicker,当搜索结果只有一项时,自动选中这一项 by xu 20251212
if (filteredOptions.value.length === 1) {
const autoSelectItem = filteredOptions.value[0];
console.log(
"[objp] 搜索结果只有一项,自动选中:",
autoSelectItem
);
doSelectItem(autoSelectItem);
return; // 自动选中后直接返回,不需要显示popup
}
filteredOptions.value.unshift({ label: "", value: "" });
// console.log('###做了过滤:'+inputText.value.toLowerCase()+';');
} else {
filteredOptions.value = props.opt;
filteredOptions.value.unshift({ label: "", value: "" });
}
console.log("props.opt11:" + JSON.stringify(props.opt));
} else {
// 没有数据时,清空过滤选项 by xu 20251212
filteredOptions.value = [];
console.log("[objp] 接口返回空数据");
}
} else {
// result不存在时,清空过滤选项 by xu 20251212
filteredOptions.value = [];
console.log("[objp] 接口返回无result");
}
// 无论是否有数据,都显示popup by xu 20251212
openPopup(); // Teleport 场景下统一打开并重定位 by xu 20260126
});
}
} catch (error) {
// callback(null, error.message); // 失败回调,传递错误
}
}
// 计算弹出方向和最大高度的方法 by xu 20251212
// 当空间不足时限制popup高度并显示滚动条
const calculatePopupDirection = () => {
const triggerEl =
selectContainerRef.value?.querySelector(".input") ||
selectContainerRef.value;
if (!triggerEl) return;
const selectRect = triggerEl.getBoundingClientRect();
const viewportHeight = window.innerHeight;
// 3. 计算上下可用空间
const spaceBelow = viewportHeight - selectRect.bottom - 10; // 减10px留边距
const spaceAbove = selectRect.top - 10; // 减10px留边距
// 4. popup预估高度(假设每项36px,最多显示8项 + padding)
const estimatedPopupHeight = 300;
const minPopupHeight = 100; // 最小高度
console.log(
"[popup] 空间计算 - spaceAbove:",
spaceAbove,
"spaceBelow:",
spaceBelow,
"estimatedHeight:",
estimatedPopupHeight
);
// 5. 判断方向和最大高度 by xu 20251212
if (spaceBelow >= estimatedPopupHeight) {
// 下方空间足够,向下展开,不限制高度
popupDirection.value = "bottom";
popupMaxHeight.value = "none";
console.log("[popup] 向下展开,空间充足");
} else if (spaceAbove >= estimatedPopupHeight) {
// 上方空间足够,向上展开,不限制高度
popupDirection.value = "top";
popupMaxHeight.value = "none";
console.log("[popup] 向上展开,空间充足");
} else {
// 上下空间都不足,选择空间大的方向,并限制高度出滚动条
if (spaceBelow >= spaceAbove) {
popupDirection.value = "bottom";
popupMaxHeight.value = Math.max(spaceBelow, minPopupHeight) + "px";
console.log(
"[popup] 向下展开,空间不足,限制高度:",
popupMaxHeight.value
);
} else {
popupDirection.value = "top";
popupMaxHeight.value = Math.max(spaceAbove, minPopupHeight) + "px";
console.log(
"[popup] 向上展开,空间不足,限制高度:",
popupMaxHeight.value
);
}
}
};
// Teleport popup 的定位(fixed) by xu 20260126
const updatePopupPosition = () => {
const triggerEl =
selectContainerRef.value?.querySelector(".input") ||
selectContainerRef.value;
if (!triggerEl) return;
const triggerRect = triggerEl.getBoundingClientRect();
const margin = 10;
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
const popupGap = 0; // 功能说明:定位不再做 -10 重叠,让 padding-top 自然形成间距 by xu 20260126
// 先给一个初始位置,确保下一帧可以测量弹层尺寸 by xu 20260126
popupLayerStyle.value = {
position: "fixed",
left: `${Math.max(margin, triggerRect.left)}px`,
top: `${Math.max(margin, triggerRect.bottom + popupGap)}px`, // 功能说明:与输入框底部对齐 by xu 20260126
bottom: "auto", // 功能说明:fixed 场景显式取消 bottom,避免与 top 同时生效 by xu 20260126
minWidth: `${Math.max(0, triggerRect.width)}px`,
zIndex: 9999,
pointerEvents: "auto",
};
Vue.nextTick(() => {
const popupEl = popupRef.value;
if (!popupEl) return;
const popupRect = popupEl.getBoundingClientRect();
const maxLeft = viewportWidth - popupRect.width - margin;
const left = Math.min(
Math.max(margin, triggerRect.left),
Math.max(margin, maxLeft)
);
let top;
if (popupDirection.value === "top") {
top = triggerRect.top - popupRect.height - popupGap; // 功能说明:向上展开时与输入框顶部对齐 by xu 20260126
top = Math.max(margin, top);
} else {
top = triggerRect.bottom + popupGap; // 功能说明:向下展开时与输入框底部对齐 by xu 20260126
if (top + popupRect.height > viewportHeight - margin) {
top = Math.max(
margin,
viewportHeight - popupRect.height - margin
);
}
}
popupLayerStyle.value = {
...popupLayerStyle.value,
left: `${left}px`,
top: `${top}px`,
bottom: "auto", // 功能说明:无论 top/bottom 展开都用 top 定位,禁用 bottom by xu 20260126
};
});
};
const openPopup = () => {
if (!popupWinVisible.value) popupWinVisible.value = true;
Vue.nextTick(() => {
calculatePopupDirection();
updatePopupPosition();
});
};
// Teleport 场景下:滚动/缩放重定位 by xu 20260126
const handleViewportChange = () => {
if (!popupWinVisible.value) return;
calculatePopupDirection();
updatePopupPosition();
};
// Teleport 场景下:点击外部关闭 by xu 20260126
const onDocPointerDown = (event) => {
if (!popupWinVisible.value) return;
const target = event.target;
if (selectContainerRef.value?.contains(target)) return;
if (popupRef.value?.contains(target)) return;
hidePopup();
};
//点击下拉菜单的文本区域时,会触发的方法
function togglePopup() {
// 可录入的 objPicker,更新下拉菜单选项
updateOptionBYInputText(inputText.value);
// popupWinVisible.value = !popupWinVisible.value;
Vue.nextTick(() => {
calculatePopupDirection();
updatePopupPosition(); // Teleport 场景下同步定位 by xu 20260126
});
}
const hidePopup = () => {
popupWinVisible.value = false;
};
//点击下拉菜单的三角形时,会触发的方法
// 添加toggle逻辑,点击时切换显示/隐藏 by xu 20251212
const suffixClick = () => {
// 如果popup已显示,则关闭 by xu 20251212
if (popupWinVisible.value) {
hidePopup();
console.log("[objp] 点三角关闭popup");
return;
}
//可录入的objPicker,更新下拉菜单选项
updateOptionBYInputText("");
Vue.nextTick(() => {
calculatePopupDirection();
updatePopupPosition(); // Teleport 场景下同步定位 by xu 20260126
});
console.log("[objp] 点三角打开popup");
};
//可录入的objPicker,录入项变化时,会触发
async function handleInputChange(event) {
inputText.value = event.target.value;
if (!inputText.value) {
inputText.value = "";
}
//可录入的objPicker,更新下拉菜单选项
updateOptionBYInputText(inputText.value);
// filteredOptions.value = props.opt.filter((option) =>
// option.label.toLowerCase().includes(inputText.value.toLowerCase())
// );
// if (!popupWinVisible.value) {
// popupWinVisible.value = true; // 确保下拉框在输入时打开
// }
}
Vue.onMounted(() => {
initDefaultValue();
// Teleport 场景下:滚动/缩放需要重定位(scroll 用 capture 捕获容器滚动) by xu 20260126
window.addEventListener("resize", handleViewportChange);
window.addEventListener("scroll", handleViewportChange, true);
// 点击外部关闭(原本依赖 mouseleave,Teleport 后会误关) by xu 20260126
document.addEventListener("pointerdown", onDocPointerDown, true);
});
Vue.onUnmounted(() => {
window.removeEventListener("resize", handleViewportChange);
window.removeEventListener("scroll", handleViewportChange, true);
document.removeEventListener("pointerdown", onDocPointerDown, true);
});
return {
errMsg,
selectItem,
inputText,
canInput,
filteredOptions,
popupWinVisible,
popupDirection,
popupMaxHeight, // 添加popup最大高度 by xu 20251212
popupContentAreaMaxHeight,
selectContainerRef,
popupRef,
teleportRootStyle,
popupLayerStyle,
suffixClick,
togglePopup,
hidePopup,
doSelectItem,
handleInputChange,
};
},
template: `
`,
};
// ss-hidden 隐藏字段组件
const SsHidden = {
name: "SsHidden",
props: {
modelValue: String,
name: {
type: String,
required: true,
},
rule: {
type: String,
required: false,//因为要单独发布非级联用的隐藏字段,改为非必需
},
param: {
type: String,
required: false,//因为要单独发布非级联用的隐藏字段,改为非必需
},
url: {
type: String,
required: false,//因为要单独发布非级联用的隐藏字段,改为非必需
},
},
emits: ["update:modelValue"],
setup(props, { emit }) {
const errMsg = Vue.ref("");
const validate = () => {
if (window.ssVm) {
const result = window.ssVm.validateField(props.name);
console.log("validate", window.ssVm.validateField(props.name));
errMsg.value = result.valid ? "" : result.message;
}
};
Vue.onMounted(() => {
/**
* 初始化级联菜单值初始值思路:
* 1. 带隐藏字段(即带编码规则)的级联菜单
* 在隐藏字段这,可以取到要回显的值和编码规则,从而计算出各级下拉菜单要回显的值。
* 然后通过ajax取各级级联菜单的值回显。
* 2. 不带隐藏字段的级联,只能在各个下拉菜单的setup事件中通过ajax取回显值回显
*/
// 当同组级联下拉菜单选中值变化时,会调用本隐藏字段下面这方法设置隐藏字段值
window.addEventListener(
"cascader-setHiddenVal-" + props.name,
(event) => {
const { value } = event.detail;
emit("update:modelValue", value);
console.log(value);
setTimeout(() => {
validate();
}, 50);
}
);
// 如果有初始值,触发回显过程
if (props.modelValue&&props.param) {//增加props.param非空判断,非级联的hidden没props.param Ben(20260414)
console.log("级联隐藏字段,开始回显,初始值:", props.modelValue);
triggerCascaderEcho(props.modelValue);
validate();
}
});
// 触发级联回显
const triggerCascaderEcho = (code) => {
/**
* 开始回显,初始值: 440304
* 解析后的所有值: Array(3)0: "440000"1: "440300"2: "440304"length: 3[[Prototype]]: Array(0)
*/
const values = parseHiddenCodeForAll(code, props.rule);
console.log("解析后的所有值:", values);
// 转换为 JSON 对象
// const paramObj = JSON.parse(props.param);
const paramObj = props.param;
let selectArr = paramObj.fieldOrd; //保存本组级联菜单项的数组,如:['hksheng','hkshi','hkxian']
if (selectArr.length != values.length) {
// alert('属性'+props.name+'的值'+code+'与级联菜单中下拉菜单的数目不匹配!');
return;
}
// 按顺序触发回显,并增加延迟确保数据加载
/**
* 通过隐藏字段的setup事件,
* 循环遍历各级下拉菜单,并触发定义在下拉菜单中的'cascader-echo'事件,
* 在此事件中完成每个下拉菜单回显值操作(只取当前要回显的键值对显示,
* 下拉菜单所有的值,在点击下拉菜单时,才通过ajax取)。
*/
values.forEach((value, index) => {
if (value) {
setTimeout(() => {
let upperVal = undefined;
if (index != 0) {
upperVal = values[index - 1];
}
const echoEvent = new CustomEvent(
"cascader-echo-" + selectArr[index],
{
detail: {
name: props.name,
value: value,
// level: index + 1,
isAuto: true, // 标记为自动回显
upperVal: upperVal,
},
}
);
console.log(props.name + "--upperValue:" + upperVal);
window.dispatchEvent(echoEvent);
}, index * 500); // 每级增加500ms延迟
}
});
};
// 解析所有级别的代码
const parseHiddenCodeForAll = (code, rule) => {
if (!code || !rule) return [];
// 获取规则中每段的长度
const segments = [];
let currentChar = rule[0];
let currentLength = 1;
for (let i = 1; i < rule.length; i++) {
if (rule[i] === currentChar) {
currentLength++;
} else {
segments.push(currentLength);
currentChar = rule[i];
currentLength = 1;
}
}
segments.push(currentLength);
// 解析每一级的值
const values = [];
let position = 0;
segments.forEach((length, index) => {
const value = code
.substring(0, position + length)
.padEnd(rule.length, "0");
values.push(value);
position += length;
});
return values;
};
watchEffect(() => {});
return {};
},
template: ``,
};
// ss-cascader 级联选择器
const SsCcp = {
name: "SsCcp",
inheritAttrs: false,
props: {
modelValue: String,
name: {
type: String,
required: true,
},
level: {
type: Number,
required: true,
},
opt: {
type: Array,
default: () => [],
},
placeholder: {
type: String,
default: "请选择",
},
width: {
type: String,
default: "150px",
},
direction: {
type: String,
default: "bottom",
},
mode: {
type: String,
default: "1",
},
inp: {
type: Boolean,
default: false,
},
onchange: {
type: String,
required: false,
},
//级联菜单配置参数,如果是数组,则代表本下拉菜单是多套级联菜单共用的第一级菜单。如果是对象,则只有一套级联菜单用此下拉菜单。
param: {
type: String,
required: true,
},
//向后台拿数据的url
url: {
type: String,
required: true,
},
},
emits: ["update:modelValue", "change"],
setup(props, { emit }) {
const canInput = props.inp === true;
const inputText = Vue.ref("");
const filteredOptions = Vue.ref(props.opt);
const visibleOptions = Vue.computed(() =>
canInput ? filteredOptions.value : props.opt
);
let inputRequestId = 0;
// alert('级联菜单初始化:'+props.name+':--:'+props.modelValue);
const selectItem = Vue.ref({ label: props.placeholder, value: "" });
const popupWinVisible = Vue.ref(false);
const isAutoEcho = Vue.ref(false); // 用于标记是否是自动回显
const upperValue = Vue.ref(""); //上级下拉菜单当前值,在初始化下拉菜单默认值时,和上级下拉菜单的值变化时,修改此upperValue变量
const popupDirection = Vue.ref("bottom");
const popupMaxHeight = Vue.ref("none"); // popup最大高度,用于空间不足时限制高度并出滚动条 by xu 20251212
const selectContainerRef = Vue.ref(null);
const popupRef = Vue.ref(null);
const teleportRootStyle = Vue.ref({
position: "fixed",
left: "0",
top: "0",
width: "0",
height: "0",
zIndex: 9999,
pointerEvents: "none",
});
const popupLayerStyle = Vue.ref({
position: "fixed",
left: "0",
top: "0",
bottom: "auto",
minWidth: "0",
zIndex: 9999,
pointerEvents: "auto",
});
//有隐藏字段的下拉菜单,加载菜单项并展开事件
// 被上级下拉菜单选中值后,触发本下拉菜单刷新菜单项并弹出显示
window.addEventListener("cascader-open-" + props.name, async (event) => {
const { upperVal } = event.detail;
upperValue.value = upperVal;
console.log(
"22props.name:" +
props.name +
",22props.upperValue:" +
upperValue.value
);
selectItem.value = ""; //清除本下拉菜单当前选中的值
inputText.value = "";
filteredOptions.value = props.opt;
emit("update:modelValue", ""); //通知父级
//清空下拉菜单,并设置第一项的值为placeholder
clearAndInit1stOpt();
//下个下拉菜单名
let nextSelName = getNextSel(props.name, props.param.fieldOrd);
if (nextSelName) {
//清下个下拉菜单选中值和选项
event = new CustomEvent("cascader-cleanOpt-" + nextSelName, {
detail: {},
});
window.dispatchEvent(event);
}
showPopup();
});
//设置mode2的下级下拉菜单的上级菜单当前值
function setNextSelectUpperValue() {
//设置下级菜单的上级菜单当前值upperValue
let paramArr = undefined;
if (Array.isArray(props.param)) {
paramArr = props.param;
} else {
paramArr = [];
paramArr.push(props.param);
}
for (const oneParam of paramArr) {
//下个下拉菜单名
const nextSelName = getNextSel(props.name, oneParam.fieldOrd);
if (nextSelName) {
setTimeout(() => {
const openNextEvent = new CustomEvent(
"cascade-setUpperVal-" + nextSelName,
{
detail: {
upperVal: props.modelValue,
},
}
);
window.dispatchEvent(openNextEvent);
}, 100);
}
} // end for
}
// 把上级 级联下拉菜单的值,设置进本组件的事件
window.addEventListener("cascade-setUpperVal-" + props.name, (event) => {
// alert('props.name:'+props.name+',props.upperValue:'+event.detail.upperVal);
const { upperVal } = event.detail;
upperValue.value = upperVal;
// console.log('props.name:'+props.name+',props.upperValue:'+upperValue.value);
});
//清空下拉菜单,并设置第一项的值为空
function clearAndInit1stOpt() {
if (props.opt)
props.opt.length = 0; //通过修改数组的length属性,直接清空数组元素,内存会被自动释放。这是性能最优的方式
else {
props.opt = [];
}
props.opt.push({ label: "", value: "" });
}
// 兼容旧版 Map 结果和新版 List