/**
 * 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 template_service_utils_exports = {};
__export(template_service_utils_exports, {
  FLOW_TEMPLATE_BLOCK_USAGES: () => FLOW_TEMPLATE_BLOCK_USAGES,
  FLOW_TEMPLATE_SUPPORTED_MODES: () => FLOW_TEMPLATE_SUPPORTED_MODES,
  FLOW_TEMPLATE_SUPPORTED_TYPES: () => FLOW_TEMPLATE_SUPPORTED_TYPES,
  FLOW_TEMPLATE_UNSUPPORTED_BLOCK_TEMPLATE_SOURCE_USES: () => FLOW_TEMPLATE_UNSUPPORTED_BLOCK_TEMPLATE_SOURCE_USES,
  POPUP_HOST_STEP_PARAM_PATHS: () => POPUP_HOST_STEP_PARAM_PATHS,
  buildFlowTemplateReferenceBlockStepParams: () => buildFlowTemplateReferenceBlockStepParams,
  buildTemplateListFilter: () => buildTemplateListFilter,
  collectFlowTemplateModelUids: () => collectFlowTemplateModelUids,
  collectFlowTemplateUsageMapFromModelOptions: () => collectFlowTemplateUsageMapFromModelOptions,
  findFieldsTemplateReferenceGrid: () => findFieldsTemplateReferenceGrid,
  findFlowTemplateOpenViewStep: () => findFlowTemplateOpenViewStep,
  normalizeRequiredTemplateString: () => normalizeRequiredTemplateString,
  normalizeTemplateSaveMode: () => normalizeTemplateSaveMode,
  normalizeTemplateUidValue: () => normalizeTemplateUidValue,
  replaceFlowModelTreeUids: () => replaceFlowModelTreeUids,
  stripTemplateInternalOpenViewFields: () => stripTemplateInternalOpenViewFields,
  stripTemplateInternalReferenceSettings: () => stripTemplateInternalReferenceSettings
});
module.exports = __toCommonJS(template_service_utils_exports);
var import_lodash = __toESM(require("lodash"));
var import_service_helpers = require("./service-helpers");
var import_service_utils = require("./service-utils");
var import_errors = require("./errors");
const FLOW_TEMPLATE_SUPPORTED_TYPES = /* @__PURE__ */ new Set(["block", "popup"]);
const FLOW_TEMPLATE_SUPPORTED_MODES = /* @__PURE__ */ new Set(["reference", "copy"]);
const FLOW_TEMPLATE_BLOCK_USAGES = /* @__PURE__ */ new Set(["block", "fields"]);
const FLOW_TEMPLATE_UNSUPPORTED_BLOCK_TEMPLATE_SOURCE_USES = /* @__PURE__ */ new Set([
  "ApplyTaskCardDetailsModel",
  "ApprovalTaskCardDetailsModel"
]);
const POPUP_HOST_STEP_PARAM_PATHS = [
  ["popupSettings", "openView"],
  ["selectExitRecordSettings", "openView"],
  ["openSelectRecordView", "openView"],
  ["openAddRecordView", "openView"]
];
function normalizeTemplateUidValue(actionName, values) {
  const templateUid = String((values == null ? void 0 : values.filterByTk) || (values == null ? void 0 : values.uid) || "").trim();
  if (!templateUid) {
    (0, import_errors.throwBadRequest)(`flowSurfaces ${actionName} template uid is required`, "FLOW_SURFACE_TEMPLATE_UID_REQUIRED");
  }
  return templateUid;
}
function normalizeRequiredTemplateString(actionName, value, field) {
  const normalized = String(value || "").trim();
  if (!normalized) {
    (0, import_errors.throwBadRequest)(`flowSurfaces ${actionName} ${field} is required`, "FLOW_SURFACE_TEMPLATE_REQUIRED_FIELD");
  }
  return normalized;
}
function normalizeTemplateSaveMode(actionName, value) {
  const normalized = String(value || "duplicate").trim() || "duplicate";
  if (normalized !== "duplicate" && normalized !== "convert") {
    (0, import_errors.throwBadRequest)(
      `flowSurfaces ${actionName} saveMode only supports 'duplicate' or 'convert'`,
      "FLOW_SURFACE_TEMPLATE_SAVE_MODE_UNSUPPORTED"
    );
  }
  return normalized;
}
function buildTemplateListFilter(existingFilter, search, requestedType) {
  const typeFilter = requestedType ? { type: requestedType } : void 0;
  return (0, import_service_helpers.buildFlowTemplateSearchFilter)(
    existingFilter && typeFilter ? { $and: [existingFilter, typeFilter] } : existingFilter || typeFilter,
    search
  );
}
function findFlowTemplateOpenViewStep(node) {
  for (const [flowKey, stepKey] of POPUP_HOST_STEP_PARAM_PATHS) {
    const openView = import_lodash.default.get(node, ["stepParams", flowKey, stepKey]);
    if (import_lodash.default.isPlainObject(openView)) {
      return {
        flowKey,
        stepKey,
        openView
      };
    }
  }
  return null;
}
function buildFlowTemplateReferenceBlockStepParams(template, templateTargetUid, resourceInit) {
  const normalizedResourceInit = (0, import_service_utils.buildDefinedPayload)(resourceInit || {});
  return (0, import_service_utils.buildDefinedPayload)({
    referenceSettings: {
      target: {
        targetUid: templateTargetUid,
        mode: "reference"
      },
      useTemplate: {
        templateUid: template.uid,
        templateName: template.name,
        templateDescription: template.description,
        targetUid: templateTargetUid,
        mode: "reference"
      }
    },
    ...Object.keys(normalizedResourceInit).length ? {
      resourceSettings: {
        init: normalizedResourceInit
      }
    } : {}
  });
}
function collectFlowTemplateUsageMapFromModelOptions(modelUid, options, carry = /* @__PURE__ */ new Map()) {
  const normalizedModelUid = String(modelUid || "").trim();
  if (!normalizedModelUid) {
    return carry;
  }
  const addUsage = (templateUid) => {
    var _a;
    const normalizedTemplateUid = String(templateUid || "").trim();
    if (!normalizedTemplateUid) {
      return;
    }
    if (!carry.has(normalizedModelUid)) {
      carry.set(normalizedModelUid, /* @__PURE__ */ new Set());
    }
    (_a = carry.get(normalizedModelUid)) == null ? void 0 : _a.add(normalizedTemplateUid);
  };
  const normalizedOptions = import_lodash.default.isPlainObject(options) || Array.isArray(options) ? options : typeof options === "string" ? JSON.parse(options) : {};
  const useTemplate = import_lodash.default.get(normalizedOptions, ["stepParams", "referenceSettings", "useTemplate"]);
  const useTemplateUid = String((useTemplate == null ? void 0 : useTemplate.templateUid) || "").trim();
  const useTemplateMode = String((useTemplate == null ? void 0 : useTemplate.mode) || "reference").trim() || "reference";
  if (useTemplateUid && useTemplateMode !== "copy") {
    addUsage(useTemplateUid);
  }
  const popupGroups = [
    import_lodash.default.get(normalizedOptions, ["stepParams", "popupSettings"]),
    import_lodash.default.get(normalizedOptions, ["stepParams", "selectExitRecordSettings"])
  ];
  for (const group of popupGroups) {
    if (!group || typeof group !== "object") {
      continue;
    }
    for (const value of Object.values(group)) {
      const popupTemplateUid = String((value == null ? void 0 : value.popupTemplateUid) || "").trim();
      const popupTemplateMode = String((value == null ? void 0 : value.popupTemplateMode) || "reference").trim() || "reference";
      if (popupTemplateUid && popupTemplateMode !== "copy") {
        addUsage(popupTemplateUid);
      }
    }
  }
  return carry;
}
function collectFlowTemplateModelUids(node, carry = /* @__PURE__ */ new Set()) {
  if (!(node == null ? void 0 : node.uid)) {
    return carry;
  }
  carry.add(String(node.uid));
  for (const child of Object.values(node.subModels || {})) {
    for (const item of import_lodash.default.castArray(child)) {
      collectFlowTemplateModelUids(item, carry);
    }
  }
  return carry;
}
function replaceFlowModelTreeUids(node, uidMap) {
  const replaceInPlace = (value) => {
    if (Array.isArray(value)) {
      for (let i = 0; i < value.length; i += 1) {
        value[i] = replaceInPlace(value[i]);
      }
      return value;
    }
    if (value && typeof value === "object") {
      for (const key of Object.keys(value)) {
        value[key] = replaceInPlace(value[key]);
      }
      return value;
    }
    return typeof value === "string" && uidMap[value] ? uidMap[value] : value;
  };
  const walk = (current) => {
    if (!current || typeof current !== "object") {
      return current;
    }
    if (typeof current.uid === "string" && uidMap[current.uid]) {
      current.uid = uidMap[current.uid];
    }
    if (typeof current.parent === "string" && uidMap[current.parent]) {
      current.parent = uidMap[current.parent];
    }
    if (typeof current.parentId === "string" && uidMap[current.parentId]) {
      current.parentId = uidMap[current.parentId];
    }
    if (current.stepParams) {
      current.stepParams = replaceInPlace(current.stepParams);
    }
    Object.values(current.subModels || {}).forEach((child) => {
      import_lodash.default.castArray(child).forEach((item) => walk(item));
    });
    return current;
  };
  return walk(import_lodash.default.cloneDeep(node));
}
function stripTemplateInternalOpenViewFields(openView) {
  if (!import_lodash.default.isPlainObject(openView)) {
    return openView;
  }
  const hasTemplateState = !!String(openView.popupTemplateUid || "").trim() || !!openView.popupTemplateContext || !!String(openView.popupTemplateMode || "").trim();
  return import_lodash.default.omit(openView, [
    "popupTemplateUid",
    "popupTemplateMode",
    "popupTemplateContext",
    "popupTemplateHasFilterByTk",
    "popupTemplateHasSourceId",
    ...hasTemplateState ? ["uid"] : []
  ]);
}
function stripTemplateInternalReferenceSettings(node) {
  var _a;
  if (!import_lodash.default.isPlainObject((_a = node == null ? void 0 : node.stepParams) == null ? void 0 : _a.referenceSettings)) {
    return;
  }
  delete node.stepParams.referenceSettings;
  if (import_lodash.default.isPlainObject(node.stepParams) && !Object.keys(node.stepParams).length) {
    delete node.stepParams;
  }
}
function findFieldsTemplateReferenceGrid(node) {
  var _a;
  return (0, import_service_utils.getSingleNodeSubModel)((_a = node == null ? void 0 : node.subModels) == null ? void 0 : _a.grid);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  FLOW_TEMPLATE_BLOCK_USAGES,
  FLOW_TEMPLATE_SUPPORTED_MODES,
  FLOW_TEMPLATE_SUPPORTED_TYPES,
  FLOW_TEMPLATE_UNSUPPORTED_BLOCK_TEMPLATE_SOURCE_USES,
  POPUP_HOST_STEP_PARAM_PATHS,
  buildFlowTemplateReferenceBlockStepParams,
  buildTemplateListFilter,
  collectFlowTemplateModelUids,
  collectFlowTemplateUsageMapFromModelOptions,
  findFieldsTemplateReferenceGrid,
  findFlowTemplateOpenViewStep,
  normalizeRequiredTemplateString,
  normalizeTemplateSaveMode,
  normalizeTemplateUidValue,
  replaceFlowModelTreeUids,
  stripTemplateInternalOpenViewFields,
  stripTemplateInternalReferenceSettings
});
