/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var default_action_popup_exports = {};
__export(default_action_popup_exports, {
  FLOW_SURFACE_DEFAULT_ACTION_POPUP_TYPES: () => FLOW_SURFACE_DEFAULT_ACTION_POPUP_TYPES,
  FLOW_SURFACE_DEFAULT_ACTION_POPUP_USES: () => FLOW_SURFACE_DEFAULT_ACTION_POPUP_USES,
  buildFlowSurfaceDefaultActionPopupBlocks: () => buildFlowSurfaceDefaultActionPopupBlocks,
  collectFlowSurfaceDefaultActionPopupFieldGroupFieldPaths: () => collectFlowSurfaceDefaultActionPopupFieldGroupFieldPaths,
  getFlowSurfaceDefaultActionPopupConfigByUse: () => getFlowSurfaceDefaultActionPopupConfigByUse,
  hasFlowSurfaceInlinePopupBlocks: () => hasFlowSurfaceInlinePopupBlocks,
  hasFlowSurfaceInlinePopupTemplate: () => hasFlowSurfaceInlinePopupTemplate,
  isFlowSurfaceDefaultActionPopupBusinessField: () => isFlowSurfaceDefaultActionPopupBusinessField,
  isFlowSurfaceDefaultActionPopupType: () => isFlowSurfaceDefaultActionPopupType,
  isFlowSurfaceDefaultActionPopupUse: () => isFlowSurfaceDefaultActionPopupUse,
  pickFlowSurfaceDefaultActionPopupFieldGroups: () => pickFlowSurfaceDefaultActionPopupFieldGroups,
  pickFlowSurfaceDefaultActionPopupFieldPaths: () => pickFlowSurfaceDefaultActionPopupFieldPaths,
  resolveFlowSurfaceDefaultActionPopupTabTitle: () => resolveFlowSurfaceDefaultActionPopupTabTitle
});
module.exports = __toCommonJS(default_action_popup_exports);
var import_lodash = __toESM(require("lodash"));
var import_association_interfaces = require("./association-interfaces");
var import_relation_backing_foreign_key = require("./relation-backing-foreign-key");
var import_service_helpers = require("./service-helpers");
const DEFAULT_ACTION_POPUP_SYSTEM_FIELD_NAMES = /* @__PURE__ */ new Set(["id", "createdBy", "createdById", "updatedBy", "updatedById"]);
const DEFAULT_ACTION_POPUP_SYSTEM_FIELD_INTERFACES = /* @__PURE__ */ new Set([
  "id",
  "snowflakeId",
  "createdBy",
  "createdById",
  "updatedBy",
  "updatedById"
]);
const DEFAULT_ACTION_POPUP_AUDIT_TIMESTAMP_FIELD_NAMES = /* @__PURE__ */ new Set(["createdAt", "updatedAt"]);
const DEFAULT_ACTION_POPUP_AUDIT_TIMESTAMP_FIELD_INTERFACES = /* @__PURE__ */ new Set(["createdAt", "updatedAt"]);
const FLOW_SURFACE_DEFAULT_ACTION_POPUP_CONFIGS = [
  {
    type: "addNew",
    use: "AddNewActionModel",
    defaultButtonTitle: '{{t("Add new")}}',
    defaultPopupTabTitle: '{{t("Add new")}}',
    blockKey: "defaultCreateForm",
    blockType: "createForm",
    blockUse: "CreateFormModel",
    resourceBinding: "currentCollection",
    blockSettings: {
      layout: "vertical",
      colon: false,
      assignRules: []
    },
    submitAction: {
      key: "defaultSubmit",
      type: "submit",
      settings: {
        title: '{{t("Submit")}}',
        type: "primary",
        confirm: false
      }
    }
  },
  {
    type: "view",
    use: "ViewActionModel",
    defaultButtonTitle: '{{t("View")}}',
    defaultPopupTabTitle: '{{t("Details")}}',
    blockKey: "defaultDetails",
    blockType: "details",
    blockUse: "DetailsBlockModel",
    resourceBinding: "currentRecord",
    blockSettings: {
      layout: "vertical",
      colon: true,
      dataScope: {
        logic: "$and",
        items: []
      },
      linkageRules: []
    }
  },
  {
    type: "edit",
    use: "EditActionModel",
    defaultButtonTitle: '{{t("Edit")}}',
    defaultPopupTabTitle: '{{t("Edit")}}',
    blockKey: "defaultEditForm",
    blockType: "editForm",
    blockUse: "EditFormModel",
    resourceBinding: "currentRecord",
    blockSettings: {
      layout: "vertical",
      colon: false,
      assignRules: [],
      dataScope: {
        logic: "$and",
        items: []
      }
    },
    submitAction: {
      key: "defaultSubmit",
      type: "submit",
      settings: {
        title: '{{t("Submit")}}',
        type: "primary",
        confirm: false
      }
    }
  }
];
const FLOW_SURFACE_DEFAULT_ACTION_POPUP_TYPES = new Set(
  FLOW_SURFACE_DEFAULT_ACTION_POPUP_CONFIGS.map((item) => item.type)
);
const FLOW_SURFACE_DEFAULT_ACTION_POPUP_USES = new Set(
  FLOW_SURFACE_DEFAULT_ACTION_POPUP_CONFIGS.map((item) => item.use)
);
const FLOW_SURFACE_DEFAULT_ACTION_POPUP_CONFIG_BY_USE = FLOW_SURFACE_DEFAULT_ACTION_POPUP_CONFIGS.reduce(
  (result, item) => {
    result[item.use] = item;
    return result;
  },
  {}
);
const FLOW_SURFACE_DEFAULT_ACTION_POPUP_LEGACY_BUTTON_TITLES = {
  AddNewActionModel: "Add new",
  ViewActionModel: "View",
  EditActionModel: "Edit"
};
function isFlowSurfaceDefaultActionPopupType(type) {
  return FLOW_SURFACE_DEFAULT_ACTION_POPUP_TYPES.has(String(type || "").trim());
}
function isFlowSurfaceDefaultActionPopupUse(use) {
  return FLOW_SURFACE_DEFAULT_ACTION_POPUP_USES.has(String(use || "").trim());
}
function getFlowSurfaceDefaultActionPopupConfigByUse(use) {
  const normalizedUse = String(use || "").trim();
  if (!isFlowSurfaceDefaultActionPopupUse(normalizedUse)) {
    return void 0;
  }
  return FLOW_SURFACE_DEFAULT_ACTION_POPUP_CONFIG_BY_USE[normalizedUse];
}
function resolveFlowSurfaceDefaultActionPopupTabTitle(use, currentTitle) {
  const actionConfig = getFlowSurfaceDefaultActionPopupConfigByUse(use);
  if (!actionConfig) {
    return void 0;
  }
  const normalizedTitle = String(currentTitle || "").trim();
  const legacyDefaultButtonTitle = FLOW_SURFACE_DEFAULT_ACTION_POPUP_LEGACY_BUTTON_TITLES[actionConfig.use];
  if (normalizedTitle && normalizedTitle !== actionConfig.defaultButtonTitle && normalizedTitle !== legacyDefaultButtonTitle) {
    return normalizedTitle;
  }
  return actionConfig.defaultPopupTabTitle;
}
function isFlowSurfaceDefaultActionPopupBusinessField(field) {
  var _a;
  const fieldInterface = String((0, import_service_helpers.getFieldInterface)(field) || "").trim();
  const fieldType = String((0, import_service_helpers.getFieldType)(field) || "").trim();
  if (!fieldInterface || (field == null ? void 0 : field.hidden) || ((_a = field == null ? void 0 : field.options) == null ? void 0 : _a.hidden)) {
    return false;
  }
  return fieldType !== "sort" && fieldInterface !== "sort";
}
function isFlowSurfaceDefaultActionPopupSystemField(field) {
  var _a, _b;
  const fieldName = String((0, import_service_helpers.getFieldName)(field) || "").trim();
  const fieldInterface = String((0, import_service_helpers.getFieldInterface)(field) || "").trim();
  return DEFAULT_ACTION_POPUP_SYSTEM_FIELD_NAMES.has(fieldName) || DEFAULT_ACTION_POPUP_SYSTEM_FIELD_INTERFACES.has(fieldInterface) || !!(field == null ? void 0 : field.primaryKey) || !!((_a = field == null ? void 0 : field.options) == null ? void 0 : _a.primaryKey) || !!(field == null ? void 0 : field.autoIncrement) || !!((_b = field == null ? void 0 : field.options) == null ? void 0 : _b.autoIncrement);
}
function isFlowSurfaceDefaultActionPopupTechnicalIdField(field) {
  var _a, _b;
  const fieldName = String((0, import_service_helpers.getFieldName)(field) || "").trim();
  const fieldInterface = String((0, import_service_helpers.getFieldInterface)(field) || "").trim();
  return fieldName === "id" || fieldInterface === "id" || fieldInterface === "snowflakeId" || !!(field == null ? void 0 : field.primaryKey) || !!((_a = field == null ? void 0 : field.options) == null ? void 0 : _a.primaryKey) || !!(field == null ? void 0 : field.autoIncrement) || !!((_b = field == null ? void 0 : field.options) == null ? void 0 : _b.autoIncrement);
}
function isFlowSurfaceDefaultActionPopupAuditTimestampField(field) {
  const fieldName = String((0, import_service_helpers.getFieldName)(field) || "").trim();
  const fieldInterface = String((0, import_service_helpers.getFieldInterface)(field) || "").trim();
  return DEFAULT_ACTION_POPUP_AUDIT_TIMESTAMP_FIELD_NAMES.has(fieldName) || DEFAULT_ACTION_POPUP_AUDIT_TIMESTAMP_FIELD_INTERFACES.has(fieldInterface);
}
function isFlowSurfaceDefaultActionPopupMultiValueAssociationField(field) {
  const fieldInterface = String((0, import_service_helpers.getFieldInterface)(field) || "").trim();
  return import_association_interfaces.MULTI_VALUE_ASSOCIATION_INTERFACES.has(fieldInterface);
}
function isFlowSurfaceDefaultActionPopupAssociationField(field) {
  const fieldType = String((0, import_service_helpers.getFieldType)(field) || "").trim();
  return fieldType === "belongsTo" || fieldType === "hasOne" || fieldType === "hasMany" || fieldType === "belongsToMany";
}
function collectFlowSurfaceDefaultActionPopupRelationBackingForeignKeys(candidates) {
  return (0, import_relation_backing_foreign_key.collectRelationBackingForeignKeyNames)({
    getFields: () => candidates.map((candidate) => candidate == null ? void 0 : candidate.field).filter(Boolean)
  });
}
function isFlowSurfaceDefaultActionPopupAssociationForeignKeyField(field, associationForeignKeys) {
  const fieldName = String((0, import_service_helpers.getFieldName)(field) || "").trim();
  return !!fieldName && associationForeignKeys.has(fieldName);
}
function pickFlowSurfaceDefaultActionPopupFieldPaths(candidates, options = {}) {
  return filterFlowSurfaceDefaultActionPopupFieldCandidates(candidates, options).map((candidate) => String((candidate == null ? void 0 : candidate.fieldPath) || "").trim()).filter(Boolean);
}
function collectFlowSurfaceDefaultActionPopupFieldGroupFieldPaths(fieldGroups) {
  const fieldPaths = /* @__PURE__ */ new Set();
  import_lodash.default.castArray(fieldGroups || []).forEach((group) => {
    import_lodash.default.castArray((group == null ? void 0 : group.fields) || []).forEach((field) => {
      const fieldPath = getFlowSurfaceDefaultActionPopupFieldGroupFieldPath(field);
      if (fieldPath) {
        fieldPaths.add(fieldPath);
      }
    });
  });
  return fieldPaths;
}
function filterFlowSurfaceDefaultActionPopupFieldCandidates(candidates, options = {}) {
  const associationForeignKeys = collectFlowSurfaceDefaultActionPopupRelationBackingForeignKeys(candidates);
  const excludeRelationBackingForeignKeyFields = options.excludeRelationBackingForeignKeyFields !== false;
  const preferredCandidates = candidates.filter(
    (candidate) => !isFlowSurfaceDefaultActionPopupSystemField(candidate.field) && (!options.excludeAuditTimestampFields || !isFlowSurfaceDefaultActionPopupAuditTimestampField(candidate.field)) && (!options.excludeAssociationFields || !isFlowSurfaceDefaultActionPopupAssociationField(candidate.field)) && !isFlowSurfaceDefaultActionPopupMultiValueAssociationField(candidate.field) && (!excludeRelationBackingForeignKeyFields || !isFlowSurfaceDefaultActionPopupAssociationForeignKeyField(candidate.field, associationForeignKeys))
  );
  const fallbackCandidates = candidates.filter(
    (candidate) => !isFlowSurfaceDefaultActionPopupTechnicalIdField(candidate.field) && (!options.excludeAuditTimestampFields || !isFlowSurfaceDefaultActionPopupAuditTimestampField(candidate.field)) && (!options.excludeAssociationFields || !isFlowSurfaceDefaultActionPopupAssociationField(candidate.field)) && !isFlowSurfaceDefaultActionPopupMultiValueAssociationField(candidate.field) && (!excludeRelationBackingForeignKeyFields || !isFlowSurfaceDefaultActionPopupAssociationForeignKeyField(candidate.field, associationForeignKeys))
  );
  const baseCandidates = preferredCandidates.length ? preferredCandidates : fallbackCandidates;
  return baseCandidates.filter((candidate) => String((candidate == null ? void 0 : candidate.fieldPath) || "").trim());
}
function getFlowSurfaceDefaultActionPopupFieldGroupFieldPath(field) {
  if (typeof field === "string") {
    return field.trim();
  }
  if (!import_lodash.default.isPlainObject(field)) {
    return "";
  }
  return String(field.field || field.fieldPath || "").trim();
}
function normalizeFlowSurfaceDefaultActionPopupFieldGroupField(field, fieldPath) {
  if (!import_lodash.default.isPlainObject(field)) {
    return fieldPath;
  }
  const fieldSpec = field;
  const titleField = String(fieldSpec.titleField || "").trim();
  return import_lodash.default.pickBy(
    {
      field: fieldPath,
      titleField: titleField || void 0,
      settings: import_lodash.default.isPlainObject(fieldSpec.settings) ? import_lodash.default.cloneDeep(fieldSpec.settings) : void 0
    },
    (value) => !import_lodash.default.isUndefined(value)
  );
}
function pickFlowSurfaceDefaultActionPopupFieldGroups(candidates, fieldGroups, options = {}) {
  const allowedFieldPaths = new Set(
    filterFlowSurfaceDefaultActionPopupFieldCandidates(candidates, {
      ...options,
      excludeRelationBackingForeignKeyFields: false
    }).map((candidate) => String((candidate == null ? void 0 : candidate.fieldPath) || "").trim())
  );
  const usedFieldPaths = /* @__PURE__ */ new Set();
  return import_lodash.default.castArray(fieldGroups || []).flatMap((group) => {
    const title = String((group == null ? void 0 : group.title) || "").trim();
    if (!title) {
      return [];
    }
    const fields = import_lodash.default.castArray((group == null ? void 0 : group.fields) || []).map((field) => {
      const fieldPath = getFlowSurfaceDefaultActionPopupFieldGroupFieldPath(field);
      if (!fieldPath || !allowedFieldPaths.has(fieldPath) || usedFieldPaths.has(fieldPath)) {
        return null;
      }
      usedFieldPaths.add(fieldPath);
      return normalizeFlowSurfaceDefaultActionPopupFieldGroupField(field, fieldPath);
    }).filter((field) => {
      if (!field) {
        return false;
      }
      return true;
    });
    if (!fields.length) {
      return [];
    }
    return [
      import_lodash.default.pickBy(
        {
          key: String((group == null ? void 0 : group.key) || "").trim() || void 0,
          title,
          fields
        },
        (value) => !import_lodash.default.isUndefined(value)
      )
    ];
  });
}
function normalizeDefaultActionPopupFieldsInput(input) {
  if (Array.isArray(input)) {
    return {
      fieldPaths: input,
      fieldGroups: []
    };
  }
  return {
    fieldPaths: import_lodash.default.castArray((input == null ? void 0 : input.fieldPaths) || []).map((field) => import_lodash.default.isPlainObject(field) ? import_lodash.default.cloneDeep(field) : String(field || "").trim()).filter((field) => import_lodash.default.isPlainObject(field) ? true : !!field),
    fieldGroups: import_lodash.default.castArray((input == null ? void 0 : input.fieldGroups) || []).filter((group) => import_lodash.default.isPlainObject(group))
  };
}
function buildFlowSurfaceDefaultActionPopupBlocks(use, fieldsInput) {
  const actionConfig = getFlowSurfaceDefaultActionPopupConfigByUse(use);
  if (!actionConfig) {
    return [];
  }
  const { fieldPaths, fieldGroups } = normalizeDefaultActionPopupFieldsInput(fieldsInput);
  const hasFieldGroups = !!fieldGroups.length;
  return [
    import_lodash.default.pickBy(
      {
        key: actionConfig.blockKey,
        type: actionConfig.blockType,
        resource: {
          binding: actionConfig.resourceBinding
        },
        settings: import_lodash.default.cloneDeep(actionConfig.blockSettings),
        fields: hasFieldGroups ? void 0 : fieldPaths,
        fieldGroups: hasFieldGroups ? fieldGroups : void 0,
        actions: actionConfig.submitAction ? [import_lodash.default.cloneDeep(actionConfig.submitAction)] : void 0
      },
      (value) => !import_lodash.default.isUndefined(value)
    )
  ];
}
function hasFlowSurfaceInlinePopupTemplate(popup) {
  return import_lodash.default.isPlainObject(popup == null ? void 0 : popup.template) && !!String(popup.template.uid || popup.template.local || "").trim();
}
function hasFlowSurfaceInlinePopupBlocks(popup) {
  return Array.isArray(popup == null ? void 0 : popup.blocks) && popup.blocks.length > 0;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  FLOW_SURFACE_DEFAULT_ACTION_POPUP_TYPES,
  FLOW_SURFACE_DEFAULT_ACTION_POPUP_USES,
  buildFlowSurfaceDefaultActionPopupBlocks,
  collectFlowSurfaceDefaultActionPopupFieldGroupFieldPaths,
  getFlowSurfaceDefaultActionPopupConfigByUse,
  hasFlowSurfaceInlinePopupBlocks,
  hasFlowSurfaceInlinePopupTemplate,
  isFlowSurfaceDefaultActionPopupBusinessField,
  isFlowSurfaceDefaultActionPopupType,
  isFlowSurfaceDefaultActionPopupUse,
  pickFlowSurfaceDefaultActionPopupFieldGroups,
  pickFlowSurfaceDefaultActionPopupFieldPaths,
  resolveFlowSurfaceDefaultActionPopupTabTitle
});
