import "../../../../../../node_modules/element-plus/es/index.mjs";
/* empty css                                                                */
/* empty css                                                                    */
/* empty css                                                                        */
/* empty css                                                                     */
/* empty css                                                                     */
/* empty css                                                                   */
/* empty css                                                                  */
/* empty css                                                                   */
import { getCurrentInstance, ref, watch, onMounted, onBeforeUnmount, computed, provide, resolveDirective, withDirectives, createCommentVNode, createBlock, openBlock, normalizeClass, withCtx, createVNode, normalizeStyle, unref, createElementBlock, Fragment, renderList } from "vue";
import "../../../../../../node_modules/grid-layout-plus/es/index.mjs";
import { getCurrentVueInstance } from "../../../utils/getInstance.mjs";
import getJsonAsyncUtil from "../../../utils/getJsonAsyncUtil.mjs";
import { FormItem } from "../formItem/index.mjs";
import { createDataSource } from "../../../utils/datasource.mjs";
import { generateFieldRules } from "./validation.mjs";
import { parseSingleParamValue } from "../../../utils/parseRouteParams.mjs";
import { cloneDeep, removeEmptyValues, isEqual } from "../../../utils/common.mjs";
/* empty css                                                                      */
/* empty css                                                                     */
/* empty css                                                                     */
import { calculate } from "../../../utils/formulajs/calculate.mjs";
import { useEventFlow } from "../../../utils/eventFlow/eventFlowHandler.mjs";
/* empty css                                                                    */
/* empty css                                                                      */
/* empty css                               */
import _export_sfc from "../../../../../../_virtual/_plugin-vue_export-helper.mjs";
/* empty css                                                     */
/* empty css                                                           */
/* empty css                                                      */
/* empty css                                                     */
/* empty css                                                        */
/* empty css                                                       */
/* empty css                                                                  */
/* empty css                                                        */
/* empty css                                                      */
/* empty css                                                       */
import api from "../../../api/index.mjs";
/* empty css                                                                    */
/* empty css                                                                          */
import { usePageEvents } from "../../../composables/usePageEvents.mjs";
import { header } from "../../details/header/index.mjs";
import { main } from "../../details/main/index.mjs";
import { footer } from "../../details/footer/index.mjs";
import FormAnchorNav from "./FormAnchorNav.vue.mjs";
import RightAnchorNav from "./RightAnchorNav.vue.mjs";
import { checkFilterMatch, checkFieldInFilterConfig, checkFieldInResultConfig } from "../../../utils/parseFilterConfig.mjs";
import hooks from "../../../../../../node_modules/moment/dist/moment.mjs";
import emitter from "../../../utils/eventBus.mjs";
/* empty css           */
import { useLocale } from "../../../../../../node_modules/element-plus/es/hooks/use-locale/index.mjs";
import { ElMessage } from "../../../../../../node_modules/element-plus/es/components/message/index.mjs";
import { ElContainer } from "../../../../../../node_modules/element-plus/es/components/container/index.mjs";
import { ElCol } from "../../../../../../node_modules/element-plus/es/components/col/index.mjs";
import { ElForm } from "../../../../../../node_modules/element-plus/es/components/form/index.mjs";
import De from "../../../../../../node_modules/grid-layout-plus/es/components/grid-layout.vue.mjs";
const _hoisted_1 = ["name", "value"];
const _sfc_main = /* @__PURE__ */ Object.assign({
  inheritAttrs: false
}, {
  __name: "Form",
  props: {
    templateKey: {
      type: String,
      default: ""
    },
    initOption: {
      type: Object,
      default: () => {
      }
    },
    modelValue: {
      type: Object,
      default: () => {
      }
    },
    isSubForm: {
      type: Boolean,
      default: false
    },
    isDialog: {
      type: Boolean,
      default: false
    },
    canPageEvent: {
      type: Boolean,
      default: true
    },
    initSearchData: {
      type: Object,
      default: {}
    },
    initFormMode: {
      type: String,
      default: ""
    },
    isApproval: {
      type: Boolean,
      default: false
    },
    class: {
      type: String,
      default: ""
    }
  },
  emits: [
    "submit",
    "change",
    "validate",
    "loaded",
    "update:modelValue",
    "layoutUpdated"
  ],
  setup(__props, { expose: __expose, emit: __emit }) {
    const props = __props;
    useLocale();
    const emit = __emit;
    const instance = getCurrentInstance();
    const ctx = getCurrentVueInstance();
    const fecFormRef = ref(null);
    const formRef = ref(null);
    const gridLayout = ref(null);
    const configLoading = ref(true);
    const localConfig = ref({});
    const formData = ref({});
    const formRules = ref({});
    const dataSourceOptions = ref({});
    const dictionaryOptions = ref({});
    const productData = ref({});
    const fieldsData = ref([]);
    const hiddenFields = ref([]);
    const prevFormData = ref({});
    let linkaged = false;
    const rowHeight = ref(1);
    const pageEvents = props.canPageEvent ? usePageEvents(() => ({
      pageEventConfig: localConfig.value.pageEventConfig,
      fields: [...fieldsData.value, ...hiddenFields.value],
      instance,
      formData: formData.value,
      localConfig: localConfig.value,
      initSearchData: props.initSearchData,
      components: {
        form: ctx
      }
    })) : null;
    if (pageEvents) {
      pageEvents.handleBeforeUnmount();
      pageEvents.handleUnmounted();
    }
    const formMode = ref("");
    watch(
      () => props.templateKey,
      (key) => {
        if (key) {
          loadConfig("dynamic");
        }
      }
    );
    watch(
      () => props.modelValue,
      (newVal, oldVal) => {
        if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
          loadFormData("change");
        }
      }
    );
    const loadConfig = async (state) => {
      if (!props.templateKey && (!props.initOption || Object.keys(props.initOption).length == 0)) {
        return;
      }
      prevFormData.value = {};
      linkaged = false;
      configLoading.value = true;
      try {
        let option = await getJsonAsyncUtil(
          ctx.$http,
          props.templateKey,
          "form",
          props.initOption
        );
        rowHeight.value = option.labelPosition == "top" ? 1.5 : 1;
        localConfig.value = option;
        if (props.initFormMode) {
          formMode.value = props.initFormMode;
        } else {
          formMode.value = option.formMode;
        }
        fieldsData.value = option.fieldsData.map((item) => {
          if (formMode.value == "query") {
            item.component.disabled = true;
          }
          return item.component;
        });
        hiddenFields.value = option.hiddenFields || [];
        loadFormData(state);
        loadEventFlow();
        if (pageEvents && localConfig.value.pageEventConfig) {
          const onCreatedEvent = localConfig.value.pageEventConfig.find(
            (e) => e.name === "onCreated"
          );
          if (onCreatedEvent) {
            console.log("🚀 页面 onCreated 事件触发");
            try {
              await pageEvents.executeEvent("onCreated");
            } catch (error) {
            }
          }
        }
        await loadFieldDataSources();
        await loadProductData();
        applyProductConfigToForm();
        mergeOptionsToFields();
        initGridLayoutDataConfig();
        initLinkage();
        emit("loaded", option, getFormData());
      } catch (error) {
        console.error("加载配置失败:", error);
        ElMessage.error("加载配置失败");
      } finally {
        configLoading.value = false;
      }
    };
    function layoutUpdated(layoutData) {
      emit("layoutUpdated", layoutData);
    }
    const loadFormData = (state) => {
      var _a;
      const defaultData = {};
      const rules = {};
      if (fieldsData.value) {
        (_a = fieldsData.value) == null ? void 0 : _a.forEach((component) => {
          if (component.fieldName) {
            let defaultValue = component.defaultValue || null;
            if (component.fieldType == "number") {
              defaultValue = Number(defaultValue || 0);
            }
            defaultData[component.fieldName] = defaultValue;
          }
          if (state != "change") {
            if (component.fieldName) {
              const fieldRules = generateFieldRules(component, formData, [
                ...fieldsData.value,
                ...hiddenFields.value
              ]);
              if (fieldRules.length > 0) {
                rules[component.fieldName] = fieldRules;
              }
            }
          }
        });
      }
      if (hiddenFields.value && hiddenFields.value.length > 0) {
        hiddenFields.value.forEach((field) => {
          if (field.fieldName) {
            if (typeof field.value == "object") {
              const value = parseSingleParamValue(
                field.value || field.defaultValue,
                defaultData,
                [...fieldsData.value, ...hiddenFields.value]
              );
              if (value) {
                defaultData[field.fieldName] = value;
              }
            } else if (field.value) {
              defaultData[field.fieldName] = field.value;
            }
          }
        });
      }
      if (state == "dynamic") {
        formData.value = { ...setFormData(props.modelValue, true), ...defaultData };
      } else {
        formData.value = { ...defaultData, ...setFormData(props.modelValue, true) };
      }
      if (state != "change") {
        formRules.value = rules;
      }
    };
    const loadFieldDataSources = async () => {
      var _a, _b;
      const fields = fieldsData.value || [];
      const fieldDataSources = /* @__PURE__ */ new Set();
      const dictionaryKeys = /* @__PURE__ */ new Set();
      for (const component of fields) {
        const fieldType = component.fieldType;
        if ((fieldType === "select" || fieldType === "multipleSelection" || fieldType === "radio" || fieldType === "checkbox" || fieldType === "cascader") && component.optionConfig) {
          const { optionSource, dataSourceValue, dictionaryValue } = component.optionConfig;
          if (optionSource === "dataSource" && dataSourceValue) {
            fieldDataSources.add(dataSourceValue);
          } else if (optionSource === "dictionary" && dictionaryValue) {
            dictionaryKeys.add(dictionaryValue);
          }
        }
      }
      for (const dataSourceId of fieldDataSources) {
        if (dataSourceOptions.value[dataSourceId]) continue;
        try {
          const dsManager = createDataSource({
            http: ctx.$http,
            dataSources: localConfig.value.dataSources,
            currentDataSourceId: dataSourceId,
            pagination: false,
            data: formData.value,
            fields: [...fieldsData.value, ...hiddenFields.value]
          });
          const data = await dsManager.fetch();
          let options = [];
          if (Array.isArray(data)) {
            options = data;
          } else if (typeof data === "object") {
            options = Array.isArray(data.data) ? data.data : ((_a = data.data) == null ? void 0 : _a.records) || ((_b = data.data) == null ? void 0 : _b.list) || [];
          }
          dataSourceOptions.value[dataSourceId] = options;
          dsManager.destroy();
        } catch (error) {
          console.error(`Failed to load data source ${dataSourceId}:`, error);
        }
      }
      if (dictionaryKeys.size > 0) {
        try {
          const keyName = Array.from(dictionaryKeys).join(",");
          const response = await ctx.$http.postForm(
            "/base-server/parm/sysParmDic/getDicListByKey",
            {
              keyName
            }
          );
          const dictionaryData = response;
          if (typeof dictionaryData === "object") {
            Object.keys(dictionaryData).forEach((dictKey) => {
              if (dictionaryKeys.has(dictKey)) {
                const dictItems = dictionaryData[dictKey];
                if (Array.isArray(dictItems)) {
                  dictionaryOptions.value[dictKey] = dictItems;
                }
              }
            });
          }
        } catch (error) {
          console.error("Failed to load dictionary data:", error);
        }
      }
    };
    const mergeOptionsToFields = () => {
      if (fieldsData.value) {
        fieldsData.value.forEach((component) => {
          if (!component.optionConfig) return;
          const {
            optionSource,
            dataSourceValue,
            dictionaryValue,
            displayField,
            valueField,
            idField,
            pidField
          } = component.optionConfig;
          if (optionSource === "dataSource" && dataSourceOptions.value[dataSourceValue]) {
            const rawOptions = dataSourceOptions.value[dataSourceValue];
            const labelField = displayField || "label";
            const keyField = valueField || "value";
            component.optionConfig.options = rawOptions.map((item) => ({
              label: item[labelField],
              value: item[keyField],
              disabled: item.disabled || false,
              ...item
            }));
          } else if (optionSource === "dictionary" && dictionaryOptions.value[dictionaryValue]) {
            const rawOptions = dictionaryOptions.value[dictionaryValue];
            const labelField = "optName";
            const keyField = "optCode";
            component.optionConfig.options = rawOptions.map((item) => ({
              label: item[labelField],
              value: item[keyField],
              disabled: item.disabled || false
            }));
          } else if (optionSource === "custom") {
            component.optionConfig.options = component.optionConfig.options || [];
          }
          applyProductConfigFilter(component);
        });
      }
    };
    const loadProductData = async () => {
      if (!localConfig.value || !localConfig.value.prodConfig) {
        return;
      }
      const { prodId } = localConfig.value.prodConfig;
      if (!prodId) {
        return;
      }
      const field = [...fieldsData.value, ...hiddenFields.value].find(
        (item) => item.id == prodId.value
      );
      if (!field) {
        return;
      }
      const prodIdValue = formData.value[field.fieldName];
      if (!prodIdValue) {
        return;
      }
      try {
        const response = await api.getProductData(ctx.$http, prodIdValue);
        productData.value = response;
        console.log("产品数据加载成功:", productData.value);
      } catch (error) {
        console.error("获取产品数据失败:", error);
        productData.value = {};
      }
    };
    const prodRules = ref({});
    const applyProductConfigToForm = () => {
      if (!localConfig.value || !localConfig.value.prodConfig || !productData.value) {
        return;
      }
      const { defaultValueConfigs, validationConfigs } = localConfig.value.prodConfig;
      if (defaultValueConfigs && defaultValueConfigs.length > 0) {
        defaultValueConfigs.forEach((config) => {
          if (config.pageField && config.productConfigField) {
            const defaultValue = productData.value[config.productConfigField];
            if (defaultValue !== void 0) {
              const formField = [...fieldsData.value, ...hiddenFields.value].find(
                (item) => item.id == config.pageField
              );
              if (formField && !formData.value[formField.fieldName]) {
                formData.value[formField.fieldName] = defaultValue;
              }
            }
          }
        });
      }
      if (validationConfigs && validationConfigs.length > 0) {
        validationConfigs.forEach((config) => {
          if (config.pageField && (config.minProductField || config.maxProductField)) {
            const minValue = productData.value[config.minProductField];
            const maxValue = productData.value[config.maxProductField];
            if (minValue !== void 0 || maxValue !== void 0) {
              const formField = [...fieldsData.value, ...hiddenFields.value].find(
                (item) => item.id == config.pageField
              );
              if (formField && !prodRules.value[formField.fieldName]) {
                prodRules.value[formField.fieldName] = [];
              }
              const customValidator = (rule, value, callback) => {
                if (value === null || value === void 0 || value === "") {
                  callback();
                  return;
                }
                const numValue = Number(value);
                if (isNaN(numValue)) {
                  callback(new Error("请输入有效的数字"));
                  return;
                }
                const formatValue = (val) => {
                  if (val === void 0 || val === null) return "";
                  const num = Number(val);
                  if (config.format === "amount") {
                    return `${num.toLocaleString()}元`;
                  } else if (config.format === "percent") {
                    return `${(num * 100).toFixed(2)}%`;
                  }
                  return num;
                };
                let errorMessage = "";
                if (minValue !== void 0 && numValue < Number(minValue)) {
                  errorMessage = `不能小于 ${formatValue(minValue)}`;
                }
                if (maxValue !== void 0 && numValue > Number(maxValue)) {
                  if (errorMessage) {
                    errorMessage = `${errorMessage} 且 不能大于 ${formatValue(
                      maxValue
                    )}`;
                  } else {
                    errorMessage = `不能大于 ${formatValue(maxValue)}`;
                  }
                }
                if (errorMessage) {
                  callback(new Error(errorMessage));
                } else {
                  callback();
                }
              };
              const customRule = {
                validator: customValidator,
                trigger: "blur"
              };
              prodRules.value[formField.fieldName].push(customRule);
            }
          }
        });
        for (let fieldName in prodRules.value) {
          if (formRules.value[fieldName]) {
            formRules.value[fieldName].push(...prodRules.value[fieldName]);
          } else {
            formRules.value[fieldName] = prodRules.value[fieldName];
          }
        }
      }
    };
    const applyProductConfigFilter = (component) => {
      if (!localConfig.value || !localConfig.value.prodConfig || !productData.value) {
        return;
      }
      const { optionConfigs } = localConfig.value.prodConfig;
      if (!optionConfigs || !component.optionConfig || !component.optionConfig.options) {
        return;
      }
      const componentConfig = optionConfigs.find(
        (item) => item.pageField == component.id
      );
      if (!componentConfig || !componentConfig.productConfigField) {
        return;
      }
      const fieldValue = productData.value[componentConfig.productConfigField];
      if (!fieldValue) {
        return;
      }
      const allowedValues = Array.isArray(fieldValue) ? fieldValue : fieldValue.split("|");
      component.optionConfig.options = component.optionConfig.options.filter(
        (option) => {
          const optionValue = option.value !== void 0 ? option.value : option;
          return allowedValues.includes(optionValue);
        }
      );
      if (component.optionConfig.options.length === 0) {
        component.optionConfig.options = [
          {
            label: `无可用选项（产品配置限制）`,
            value: "",
            disabled: true
          }
        ];
      }
    };
    const handleEvent = ref(null);
    function loadEventFlow() {
      const {
        getEventHandlers: createEventHandlers,
        handleEvent: createHandleEvent
      } = useEventFlow({
        fields: [...fieldsData.value, ...hiddenFields.value],
        instance,
        localConfig: localConfig.value,
        components: {
          form: ctx
        }
      });
      handleEvent.value = createHandleEvent;
      const getEventHandlers = (row, item, eventConfig) => {
        return createEventHandlers(item, row, eventConfig);
      };
      fieldsData.value.forEach((component) => {
        if (component.fieldName) {
          component.eventHandlers = getEventHandlers(
            formData.value,
            component,
            component.eventConfig
          );
        }
      });
    }
    function handleLabelLink(config) {
      var _a;
      handleEvent.value(
        getFormData(),
        config,
        (_a = config.labelLinkEventConfig) == null ? void 0 : _a.find((item) => item.name == "Click")
      );
    }
    const gridLayoutFieldsData = ref([]);
    const oriGridLayoutData = ref([]);
    const formItemRefs = ref(/* @__PURE__ */ new Map());
    const setFormItemRef = (el, component) => {
      if (!el) {
        if (component && component.id) {
          formItemRefs.value.delete(component.id);
        }
        return;
      }
      if (component && component.id) {
        formItemRefs.value.set(String(component.id), el);
      }
    };
    const getFormItemRef = (fieldId) => {
      const formItem = formItemRefs.value.get(fieldId);
      if (!formItem) {
        console.log(`未找到 fieldId: ${fieldId} 的 FormItem 组件`);
        return null;
      }
      console.log(`找到 FormItem 组件:`, formItem);
      if (typeof formItem.getInnerComponentRef === "function") {
        const innerRef = formItem.getInnerComponentRef();
        console.log(`内部组件 ref:`, innerRef);
        return innerRef;
      } else {
        console.log(`FormItem 组件没有 getInnerComponentRef 方法`);
        return null;
      }
    };
    function initGridLayoutDataConfig() {
      let gridLayoutData = cloneDeep(localConfig.value.fieldsData || []);
      gridLayoutData = gridLayoutData.map((item) => {
        item.isResizable = false;
        const component = item.component;
        item.y = item.y * 60;
        if (component.fieldType == "subTitle" || component.fieldType == "h2") {
          item.h = item.h * 40;
        } else if (component.fieldType == "divider") {
          item.h = item.h * 0;
        } else if (!item.fixedH) {
          item.h = item.h * 60;
        } else if (item.fixedH) {
          item.h = item.h / (localConfig.value.labelPosition == "top" ? 1.5 : 1);
        }
        if (formMode.value == "query") {
          if (item.component.displayMode == "edit") {
            item.hidden = true;
          }
        } else {
          if (item.component.displayMode == "query") {
            item.hidden = true;
          }
        }
        return item;
      });
      oriGridLayoutData.value = gridLayoutData;
    }
    const getFieldError = (fieldName) => {
      var _a;
      if (!formRef.value) return "";
      const field = (_a = formRef.value.fields) == null ? void 0 : _a.find((f) => f.prop === fieldName);
      return (field == null ? void 0 : field.validateMessage) || "";
    };
    const handleFieldChange = (config, value) => {
      console.log("🚀 ~ handleFieldChange ~ value:", config.fieldName, value);
    };
    const handleCustomButtonClick = (button) => {
      var _a;
      const opt = { ...button };
      opt.isApproval = false;
      handleEvent.value(
        getFormData(),
        opt,
        (_a = button.eventConfig) == null ? void 0 : _a.find((item) => item.name == "Click")
      );
    };
    const handleActionClick = (button) => {
      var _a;
      handleEvent.value(
        getFormData(),
        button,
        (_a = button.eventConfig) == null ? void 0 : _a.find((item) => item.name == "Click")
      );
    };
    const hasSaveButton = () => {
      var _a, _b;
      return (_b = (_a = localConfig.value.pageFooterConfig) == null ? void 0 : _a.actions) == null ? void 0 : _b.some(
        (item) => item.isApproval
      );
    };
    const handleApprovalEvent = (isSubmit) => {
      return new Promise((resolve, reject) => {
        var _a, _b;
        const actions = ((_a = localConfig.value.pageFooterConfig) == null ? void 0 : _a.actions) || [];
        const approvalAction = actions.find((item) => item.isApproval);
        if (approvalAction) {
          let action = { ...approvalAction };
          if (!isSubmit) {
            action.isApproval = false;
          }
          handleEvent.value(
            formData.value,
            action,
            (_b = approvalAction.eventConfig) == null ? void 0 : _b.find((item) => item.name == "Click")
          ).then(() => {
            resolve();
          }).catch((error) => {
            reject(error);
          });
        }
      });
    };
    const validate = () => {
      var _a;
      const subFormComps = gridLayoutFieldsData.value.filter((item) => item.component.fieldType == "subForm").map((item) => item.component);
      const subFormPromises = subFormComps.map((subForm) => {
        var _a2, _b;
        const subFormRef = getFormItemRef(String(subForm.id));
        return ((_b = (_a2 = subFormRef == null ? void 0 : subFormRef.subFormRef) == null ? void 0 : _a2.validate) == null ? void 0 : _b.call(_a2)) || Promise.resolve();
      });
      subFormPromises.push((_a = formRef.value) == null ? void 0 : _a.validate());
      return Promise.all(subFormPromises).then(() => getFormData());
    };
    const docValidate = () => {
      const documentComps = gridLayoutFieldsData.value.filter((item) => item.component.fieldType == "document").map((item) => item.component);
      const compPromises = documentComps.map((comp) => {
        var _a;
        const compRef = getFormItemRef(String(comp.id));
        return ((_a = compRef == null ? void 0 : compRef.validate) == null ? void 0 : _a.call(compRef)) || Promise.resolve();
      });
      return Promise.all(compPromises);
    };
    const resetFields = () => {
      var _a, _b;
      (_a = formRef.value) == null ? void 0 : _a.clearValidate();
      (_b = formRef.value) == null ? void 0 : _b.resetFields();
      loadFormData();
    };
    const valueFormatMap = {
      date: "YYYYMMDD",
      week: "YYYYMMDD",
      month: "YYYYMM",
      year: "YYYY",
      datetime: "YYYYMMDDHHmmss"
    };
    const formValueFormatMap = {
      date: "YYYY/MM/DD",
      week: "YYYY/MM/DD",
      month: "YYYY/MM",
      year: "YYYY",
      datetime: "YYYY/MM/DD HH:mm:ss"
    };
    const getFormData = () => {
      const result = { ...formData.value };
      const processField = (field) => {
        const fieldName = field.fieldName;
        const fieldType = field.fieldType;
        const value = result[fieldName];
        if (fieldName && (fieldType === "checkbox" || fieldType === "multipleSelection" || fieldType === "cascader" || fieldType === "area" || fieldType === "industry")) {
          let splitStr = "|";
          if (fieldType === "cascader" || fieldType === "area" || fieldType === "industry") {
            splitStr = ",";
          }
          if (Array.isArray(value)) {
            result[fieldName] = value.join(splitStr);
          }
        } else if (fieldName && fieldType === "date" && value) {
          const dateValueType = field.dateValueType;
          const valueFormat = valueFormatMap[field.dateType] || "YYYYMMDD";
          const formValueFormat = formValueFormatMap[field.dateType] || "YYYY/MM/DD";
          switch (dateValueType) {
            case "date":
              result[fieldName] = hooks(value, formValueFormat).toDate();
              break;
            case "timestamp":
              result[fieldName] = hooks(value, formValueFormat).valueOf();
              break;
            case "string":
            default:
              result[fieldName] = hooks(value, formValueFormat).format(
                valueFormat
              );
              break;
          }
        }
        if (fieldType != "number" && !result[fieldName]) {
          result[fieldName] = "";
        }
      };
      if (fieldsData.value) {
        fieldsData.value.forEach((component) => {
          processField(component);
        });
      }
      if (hiddenFields.value && hiddenFields.value.length > 0) {
        hiddenFields.value.forEach((field) => {
          processField(field);
        });
      }
      return result;
    };
    const setFormData = (data, flag = false) => {
      const processedData = { ...data };
      const processField = (field) => {
        const fieldName = field.fieldName;
        const fieldType = field.fieldType;
        if (!processedData.hasOwnProperty(fieldName)) {
          return;
        }
        const value = processedData[fieldName];
        if (fieldName && (fieldType === "checkbox" || fieldType === "multipleSelection" || fieldType === "cascader" || fieldType === "area" || fieldType === "industry")) {
          let splitStr = "|";
          if (fieldType === "cascader" || fieldType === "area" || fieldType === "industry") {
            splitStr = ",";
          }
          if (typeof value === "string" && value.includes(splitStr)) {
            processedData[fieldName] = value.split(splitStr);
          } else if (typeof value === "string" && value !== "") {
            processedData[fieldName] = [value];
          } else if (value === "" || value === null || value === void 0) {
            processedData[fieldName] = [];
          }
          processedData[fieldName] = processedData[fieldName].map((item) => {
            if (item.indexOf(",") > -1) {
              return item.split(",");
            }
            return item;
          });
        } else if (fieldName && fieldType === "date" && value) {
          const valueFormat = valueFormatMap[field.dateType] || "YYYYMMDD";
          const formValueFormat = formValueFormatMap[field.dateType] || "YYYY/MM/DD";
          processedData[fieldName] = hooks(value, valueFormat).format(
            formValueFormat
          );
        }
      };
      if (fieldsData.value) {
        fieldsData.value.forEach((component) => {
          processField(component);
        });
      }
      if (hiddenFields.value && hiddenFields.value.length > 0) {
        hiddenFields.value.forEach((field) => {
          processField(field);
        });
      }
      if (flag) {
        return removeEmptyValues(processedData);
      }
      Object.assign(formData.value, processedData);
    };
    onMounted(() => {
      loadConfig();
    });
    onBeforeUnmount(() => {
      formItemRefs.value.clear();
    });
    const findChangedFields = (newData, oldData) => {
      const changedFields = [];
      const allKeys = /* @__PURE__ */ new Set([
        ...Object.keys(newData || {}),
        ...Object.keys(oldData || {})
      ]);
      let initFlag = false;
      if (Object.keys(oldData || {}).length === 0) {
        initFlag = true;
      }
      for (const key of allKeys) {
        if (initFlag) {
          changedFields.push(key);
          continue;
        }
        const hasKeyInNew = newData && Object.prototype.hasOwnProperty.call(newData, key);
        const hasKeyInOld = oldData && Object.prototype.hasOwnProperty.call(oldData, key);
        if (!hasKeyInNew && !hasKeyInOld) {
          continue;
        }
        const newVal = hasKeyInNew ? newData[key] : void 0;
        const oldVal = hasKeyInOld ? oldData[key] : void 0;
        if (!newVal && !oldVal && Object.keys(oldData || {}).length === 0) {
          continue;
        }
        if (JSON.stringify(newVal) != JSON.stringify(oldVal)) {
          changedFields.push(key);
        }
      }
      return changedFields;
    };
    const filterRelevantLinkageConfigs = (changedFieldNames, linkedConfig, fields) => {
      const result = {
        dataLink: [],
        visibility: [],
        required: [],
        readonly: [],
        disabled: [],
        options: []
      };
      if (!linkedConfig || changedFieldNames.length === 0) {
        return result;
      }
      const changedFieldIds = changedFieldNames.map((fieldName) => {
        const field = fields.find((f) => f.fieldName == fieldName);
        return field ? field.id : null;
      }).filter((id) => id !== null);
      if (linkedConfig.dataLink) {
        result.dataLink = linkedConfig.dataLink.filter((item) => {
          return changedFieldIds.some(
            (fieldId) => checkFieldInFilterConfig(item.filterConfig, fieldId) || checkFieldInResultConfig(item.fieldAssignments, fieldId, fields)
          );
        });
      }
      if (linkedConfig.options) {
        result.options = linkedConfig.options.filter((item) => {
          return changedFieldIds.some(
            (fieldId) => checkFieldInFilterConfig(item.filterConfig, fieldId)
          );
        });
      }
      if (linkedConfig.visibility) {
        result.visibility = linkedConfig.visibility;
      }
      if (linkedConfig.required) {
        result.required = linkedConfig.required;
      }
      if (linkedConfig.readonly) {
        result.readonly = linkedConfig.readonly;
      }
      if (linkedConfig.disabled) {
        result.disabled = linkedConfig.disabled;
      }
      return result;
    };
    const applyLinkageEffectsForChangedFields = (changedFieldNames) => {
      var _a;
      const linkedConfig = localConfig.value.linkedConfig || {};
      const fields = [...fieldsData.value, ...hiddenFields.value];
      const relevantConfigs = filterRelevantLinkageConfigs(
        changedFieldNames,
        linkedConfig,
        fields
      );
      relevantConfigs.dataLink.forEach((item) => {
        if (checkFilterMatch(item.filterConfig, formData.value, fields)) {
          const fieldAssignments = item.fieldAssignments || [];
          fieldAssignments.forEach((assignment) => {
            var _a2, _b;
            const fieldId = assignment.fieldId;
            const formulaText = (_b = (_a2 = assignment.formula) == null ? void 0 : _a2.value) == null ? void 0 : _b.text;
            const field = fields.find((f) => f.id == fieldId);
            if (field && formulaText) {
              const calcResult = calculate({
                text: formulaText,
                marks: [],
                value: formData.value,
                fieldsList: fields
              });
              formData.value[field.fieldName] = calcResult;
            }
          });
        }
      });
      const updatedLayoutData = cloneDeep(oriGridLayoutData.value || []);
      relevantConfigs.options.forEach((item) => {
        if (checkFilterMatch(item.filterConfig, formData.value, fields)) {
          const fieldAssignments = item.fieldAssignments || [];
          fieldAssignments.forEach((assignment) => {
            const fieldId = assignment.fieldId;
            const optionsOpt = assignment.optionsOpt || [];
            const layoutFieldItem = updatedLayoutData.find((g) => g.id == fieldId);
            if (layoutFieldItem && optionsOpt.length > 0) {
              const oriOptions = layoutFieldItem.component.optionConfig.options;
              layoutFieldItem.component.optionConfig.options = oriOptions.filter(
                (item2) => optionsOpt.includes(item2.value)
              );
            }
          });
        }
      });
      relevantConfigs.visibility.forEach((item) => {
        const dataLinkFieldList = item.dataLinkFieldList || [];
        dataLinkFieldList.forEach((fieldId) => {
          const layoutFieldItem = updatedLayoutData.find((g) => g.id == fieldId);
          if (layoutFieldItem) {
            layoutFieldItem.hidden = true;
          }
        });
        if (checkFilterMatch(item.filterConfig, formData.value, fields)) {
          dataLinkFieldList.forEach((fieldId) => {
            const layoutFieldItem = updatedLayoutData.find((g) => g.id == fieldId);
            if (layoutFieldItem) {
              layoutFieldItem.hidden = false;
            }
          });
        }
      });
      relevantConfigs.required.forEach((item) => {
        const dataLinkFieldList = item.dataLinkFieldList || [];
        dataLinkFieldList.forEach((fieldId) => {
          const layoutFieldItem = updatedLayoutData.find((g) => g.id == fieldId);
          if (layoutFieldItem) {
            layoutFieldItem.component.required = false;
          }
        });
        if (checkFilterMatch(item.filterConfig, formData.value, fields)) {
          dataLinkFieldList.forEach((fieldId) => {
            const layoutFieldItem = updatedLayoutData.find((g) => g.id == fieldId);
            if (layoutFieldItem) {
              layoutFieldItem.component.required = true;
            }
          });
        }
      });
      const rules = {};
      updatedLayoutData.forEach(({ component }) => {
        if (component.fieldName) {
          const fieldRules = generateFieldRules(component, formData, fields);
          if (fieldRules.length > 0) {
            rules[component.fieldName] = fieldRules;
          }
        }
      });
      for (let fieldName in prodRules.value) {
        if (rules[fieldName]) {
          rules[fieldName].push(...prodRules.value[fieldName]);
        } else {
          rules[fieldName] = prodRules.value[fieldName];
        }
      }
      formRules.value = rules;
      if (formMode.value != "query") {
        relevantConfigs.readonly.forEach((item) => {
          const dataLinkFieldList = item.dataLinkFieldList || [];
          dataLinkFieldList.forEach((fieldId) => {
            const layoutFieldItem = updatedLayoutData.find((g) => g.id == fieldId);
            if (layoutFieldItem) {
              layoutFieldItem.component.readOnly = false;
            }
          });
          if (checkFilterMatch(item.filterConfig, formData.value, fields)) {
            dataLinkFieldList.forEach((fieldId) => {
              const layoutFieldItem = updatedLayoutData.find(
                (g) => g.id == fieldId
              );
              if (layoutFieldItem) {
                layoutFieldItem.component.readOnly = true;
              }
            });
          }
        });
        relevantConfigs.disabled.forEach((item) => {
          const dataLinkFieldList = item.dataLinkFieldList || [];
          dataLinkFieldList.forEach((fieldId) => {
            const layoutFieldItem = updatedLayoutData.find((g) => g.id == fieldId);
            if (layoutFieldItem) {
              layoutFieldItem.component.disabled = false;
            }
          });
          if (checkFilterMatch(item.filterConfig, formData.value, fields)) {
            dataLinkFieldList.forEach((fieldId) => {
              const layoutFieldItem = updatedLayoutData.find(
                (g) => g.id == fieldId
              );
              if (layoutFieldItem) {
                layoutFieldItem.component.disabled = true;
              }
            });
          }
        });
      }
      const fieldsConfigArr = updatedLayoutData.filter((item) => !item.hidden);
      gridLayoutFieldsData.value = sortLayoutItems(fieldsConfigArr);
      (_a = gridLayout == null ? void 0 : gridLayout.value) == null ? void 0 : _a.resizeEvent();
    };
    function sortLayoutItems(arr) {
      return [...arr].sort((a, b) => {
        if (a.y !== b.y) {
          return a.y - b.y;
        }
        return a.x - b.x;
      });
    }
    const subTableCounts = ref({});
    const navLinkCompId = ref("");
    const anchorNavLinks = computed(() => {
      var _a;
      const baseId = (_a = gridLayoutFieldsData.value) == null ? void 0 : _a[0].id;
      const list = gridLayoutFieldsData.value.map((item) => {
        if (item.component.fieldType == "h2") {
          return {
            id: item.id,
            title: item.component.label
          };
        } else if (item.component.titleMode == "label") {
          return {
            id: item.id,
            title: item.component.label,
            count: subTableCounts.value[item.id] ?? 0
          };
        } else {
          return null;
        }
      }).filter(Boolean);
      if (list.length == 0) {
        return list;
      }
      return [{ id: baseId, title: "基本信息" }, ...list];
    });
    emitter.on("onSubTableDataLoaded", ({ subTableConfig, visibleData }) => {
      const id = subTableConfig.id;
      const count = (visibleData == null ? void 0 : visibleData.length) || 0;
      subTableCounts.value[id] = count;
    });
    const navType = computed(() => {
      var _a;
      if ((localConfig.value.navigationEnabled ?? true) && !props.isSubForm && ((_a = anchorNavLinks.value) == null ? void 0 : _a.length) > 0 && fecFormRef.value) {
        if (fecFormRef.value.$el.closest(".fec-layout-row")) {
          return "top";
        } else {
          if (!props.isDialog) {
            return "right";
          } else {
            return "";
          }
        }
      } else {
        return "";
      }
    });
    function initLinkage() {
      const changedFields = findChangedFields(formData.value, prevFormData.value);
      if (changedFields.length > 0) {
        applyLinkageEffectsForChangedFields(changedFields);
      }
      prevFormData.value = { ...formData.value };
      linkaged = true;
    }
    watch(
      formData,
      (newVal, oldVal) => {
        if (!linkaged) {
          return;
        }
        const lastValue = { ...prevFormData.value };
        if (isEqual(newVal, lastValue)) {
          return;
        }
        const changedFields = findChangedFields(newVal, lastValue);
        if (changedFields.length > 0) {
          applyLinkageEffectsForChangedFields(changedFields);
        }
        prevFormData.value = { ...formData.value };
        emit("update:modelValue", getFormData());
      },
      { deep: true }
    );
    function setFormItemHeight(id, fixedH, h) {
      var _a;
      const item = gridLayoutFieldsData.value.find((item2) => item2.id == id);
      if (!fixedH) {
        item.h = h * 60;
      } else if (fixedH) {
        item.h = h / (localConfig.value.labelPosition == "top" ? 1.5 : 1);
      }
      const oriItem = oriGridLayoutData.value.find((item2) => item2.id == id);
      if (!fixedH) {
        oriItem.h = h * 60;
      } else if (fixedH) {
        oriItem.h = h / (localConfig.value.labelPosition == "top" ? 1.5 : 1);
      }
      (_a = gridLayout == null ? void 0 : gridLayout.value) == null ? void 0 : _a.resizeEvent();
    }
    provide("formData", formData);
    provide("localConfig", localConfig);
    provide("fieldsData", fieldsData);
    provide("hiddenFields", hiddenFields);
    provide("rowHeight", rowHeight);
    provide("gridLayout", gridLayout);
    provide("gridLayoutFieldsData", gridLayoutFieldsData);
    provide("setFormItemHeight", setFormItemHeight);
    provide("formCtx", ctx);
    provide("handleEvent", handleEvent);
    provide("getFormData", getFormData);
    __expose({
      validate,
      docValidate,
      resetFields,
      getFormData,
      setFormData,
      getFormItemRef,
      formRef,
      localConfig,
      handleApprovalEvent,
      hasSaveButton
    });
    return (_ctx, _cache) => {
      const _component_el_form = ElForm;
      const _component_el_col = ElCol;
      const _component_el_container = ElContainer;
      const _directive_fec_layout = resolveDirective("fec-layout");
      return !configLoading.value ? withDirectives((openBlock(), createBlock(_component_el_container, {
        key: 0,
        class: normalizeClass(["fec-form", __props.class]),
        "data-id": localConfig.value.templateKey,
        "data-name": localConfig.value.templateName,
        "data-pkId": localConfig.value.pkId,
        "data-version": "v5",
        ref_key: "fecFormRef",
        ref: fecFormRef
      }, {
        default: withCtx(() => [
          createVNode(_component_el_col, {
            span: unref(navType) == "right" ? 21 : 24,
            class: "fec-form-col",
            style: normalizeStyle({ marginRight: unref(navType) == "right" ? "4px" : "0" })
          }, {
            default: withCtx(() => [
              createVNode(unref(header), {
                showBack: !__props.isSubForm && !__props.isDialog,
                isApproval: __props.isApproval,
                pageHeaderConfig: localConfig.value.pageHeaderConfig,
                onActionClick: handleActionClick
              }, null, 8, ["showBack", "isApproval", "pageHeaderConfig"]),
              unref(navType) == "top" ? (openBlock(), createBlock(FormAnchorNav, {
                key: 0,
                fecFormRef: fecFormRef.value,
                links: unref(anchorNavLinks),
                modelValue: navLinkCompId.value,
                "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => navLinkCompId.value = $event)
              }, null, 8, ["fecFormRef", "links", "modelValue"])) : createCommentVNode("", true),
              createVNode(unref(main), {
                scrollbar: !__props.isDialog
              }, {
                default: withCtx(() => [
                  createVNode(_component_el_form, {
                    ref_key: "formRef",
                    ref: formRef,
                    model: formData.value,
                    rules: formRules.value,
                    "label-position": localConfig.value.labelPosition,
                    style: { padding: "0", width: "100%" },
                    class: normalizeClass({ "fec-el-form": !__props.isSubForm }),
                    "validate-on-rule-change": false,
                    size: "large",
                    "scroll-to-error": ""
                  }, {
                    default: withCtx(() => [
                      createVNode(unref(De), {
                        ref_key: "gridLayout",
                        ref: gridLayout,
                        layout: gridLayoutFieldsData.value,
                        "onUpdate:layout": _cache[1] || (_cache[1] = ($event) => gridLayoutFieldsData.value = $event),
                        "row-height": rowHeight.value,
                        margin: [0, 0],
                        "use-css-transforms": false,
                        "col-num": localConfig.value.columns,
                        "is-draggable": false,
                        "is-resizable": false,
                        onLayoutUpdated: layoutUpdated
                      }, {
                        item: withCtx(({ item: { component } }) => [
                          createVNode(unref(FormItem), {
                            ref: (el) => setFormItemRef(el, component),
                            modelValue: formData.value[component.fieldName],
                            "onUpdate:modelValue": ($event) => formData.value[component.fieldName] = $event,
                            config: component,
                            localConfig: localConfig.value,
                            error: getFieldError(component.fieldName),
                            formRef: formRef.value,
                            formMode: formMode.value,
                            onChange: handleFieldChange,
                            onLabelLink: handleLabelLink
                          }, null, 8, ["modelValue", "onUpdate:modelValue", "config", "localConfig", "error", "formRef", "formMode"])
                        ]),
                        _: 1
                      }, 8, ["layout", "row-height", "col-num"]),
                      (openBlock(true), createElementBlock(Fragment, null, renderList(hiddenFields.value, (field) => {
                        return openBlock(), createElementBlock("input", {
                          key: field.fieldName,
                          type: "hidden",
                          name: field.fieldName,
                          value: formData.value[field.fieldName]
                        }, null, 8, _hoisted_1);
                      }), 128))
                    ]),
                    _: 1
                  }, 8, ["model", "rules", "label-position", "class"])
                ]),
                _: 1
              }, 8, ["scrollbar"]),
              !__props.isSubForm && !__props.isDialog && !__props.isApproval ? (openBlock(), createBlock(unref(footer), {
                key: 1,
                formMode: formMode.value,
                pageFooterConfig: localConfig.value.pageFooterConfig,
                onCustomButtonClick: handleCustomButtonClick
              }, null, 8, ["formMode", "pageFooterConfig"])) : createCommentVNode("", true)
            ]),
            _: 1
          }, 8, ["span", "style"]),
          unref(navType) == "right" ? (openBlock(), createBlock(_component_el_col, {
            key: 0,
            span: 3,
            class: "fec-form-col",
            style: { "margin-left": "4px" }
          }, {
            default: withCtx(() => [
              createVNode(RightAnchorNav, {
                fecFormRef: fecFormRef.value,
                links: unref(anchorNavLinks),
                modelValue: navLinkCompId.value,
                "onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => navLinkCompId.value = $event)
              }, null, 8, ["fecFormRef", "links", "modelValue"])
            ]),
            _: 1
          })) : createCommentVNode("", true)
        ]),
        _: 1
      }, 8, ["class", "data-id", "data-name", "data-pkId"])), [
        [_directive_fec_layout]
      ]) : createCommentVNode("", true);
    };
  }
});
const _Form = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-ae7b77e4"]]);
export {
  _Form as default
};
