import { defineComponent as U, mergeModels as _, useModel as H, computed as D, ref as E, watch as j, createBlock as M, openBlock as y, unref as e, withCtx as c, createCommentVNode as Q, withModifiers as de, createVNode as b, mergeProps as W, createElementVNode as re, createElementBlock as me, Fragment as pe, isRef as F } from "vue";
import { useI18n as x } from "vue-i18n";
import { storeToRefs as z } from "pinia";
import { s as B, X, ak as ce, h as be, i as Ae, c as O, a as ve, I as J, j as fe, e as ge, k as he, ab as ye, a2 as Se, ai as Ee, aa as Me, ar as Ie, ac as G } from "./start-CE9SawgU.js";
import "./header-Bn1EKnBE.js";
import { B as Te } from "./base-B7u32Mej.js";
import { c as L, f as Ve, T as N, e as q } from "./topBarRoutes-CBd5qLxn.js";
import { E as we } from "./EditAttributeMapping-CrfwYxpD.js";
import { A as Ne, a as Ce } from "./tables-CSI_JQBB.js";
const k = `${Te}CalculatedEntityFields.`, P = {
  /** Fetches the ETL attribute set map and ETL attribute map to allow creation/editing of the mapping of a calculated entity field. */
  async getMaps(r) {
    return B.post(`${k}getMaps`, r);
  },
  /** deletes calculated mappings, the source attribute set is equal to the destination attribute */
  async deleteCalculatedAttributeMap(r, i) {
    return B.post(`${k}deleteCalculatedAttributeMap`, {
      attributeSetId: r,
      destinationAttributeId: i
    });
  },
  /** update older entities when a new automatic mapping is created. */
  async recalculateEntityFields(r) {
    return B.post(`${k}recalculateEntityFields`, r);
  }
}, _e = /* @__PURE__ */ U({
  __name: "AssignedSetDetails",
  props: /* @__PURE__ */ _({
    attributeMap: {},
    pluginName: {}
  }, {
    modelValue: { type: Boolean },
    modelModifiers: {}
  }),
  emits: /* @__PURE__ */ _(["save"], ["update:modelValue"]),
  setup(r) {
    const i = r, m = H(r, "modelValue"), { t: S } = x(), { isLoadingDataTypes: V, dataTypes: g } = z(
      L(i.pluginName)
    ), I = D(() => {
      const n = i.attributeMap?.dhAttribute.name ?? "", u = i.attributeMap?.attributeSetName ?? "";
      return S("datahub-ui.dh-shared.editAssignedAttribute", {
        attribute: n,
        attributeSet: u
      });
    }), l = E();
    return j(
      () => i.attributeMap,
      () => {
        l.value = i.attributeMap?.configuration ?? i.attributeMap?.dhAttribute?.dataTypeInstance?.defaultConfiguration;
      },
      { immediate: !0 }
    ), (n, u) => (y(), M(e(X), {
      modelValue: m.value,
      "onUpdate:modelValue": u[3] || (u[3] = (A) => m.value = A),
      title: I.value,
      "min-width": "600px",
      "max-width": "800px"
    }, {
      actions: c(() => [
        b(e(J), {
          text: n.$t("common.applyChanges"),
          color: "primary",
          onClick: u[0] || (u[0] = (A) => n.$emit("save", { config: l.value }))
        }, null, 8, ["text"])
      ]),
      default: c(() => [
        n.attributeMap ? (y(), M(e(ce), {
          key: 0,
          class: "h-100 overflow-y-auto overflow-x-hidden",
          onSubmit: u[2] || (u[2] = de(() => {
          }, ["prevent"]))
        }, {
          default: c(() => [
            b(e(be), {
              class: "pa-2 mt-1",
              fluid: ""
            }, {
              default: c(() => [
                b(e(Ae), null, {
                  default: c(() => [
                    b(e(O), null, {
                      default: c(() => [
                        b(e(ve), {
                          "model-value": n.attributeMap.dhAttribute.dataType,
                          label: n.$t("datahub-ui.dh-table.dataType"),
                          loading: e(V),
                          items: e(g),
                          "item-title": "name",
                          "item-value": "id",
                          readonly: ""
                        }, null, 8, ["model-value", "label", "loading", "items"])
                      ]),
                      _: 1
                    }),
                    b(e(O), null, {
                      default: c(() => [
                        b(Ve, {
                          modelValue: l.value,
                          "onUpdate:modelValue": u[1] || (u[1] = (A) => l.value = A),
                          attribute: n.attributeMap.dhAttribute,
                          "data-type-instance": n.attributeMap.dhAttribute.dataTypeInstance,
                          "remote-scopes": [],
                          "remote-languages": []
                        }, null, 8, ["modelValue", "attribute", "data-type-instance"])
                      ]),
                      _: 1
                    })
                  ]),
                  _: 1
                })
              ]),
              _: 1
            })
          ]),
          _: 1
        })) : Q("", !0)
      ]),
      _: 1
    }, 8, ["modelValue", "title"]));
  }
}), De = { class: "w-100" }, $e = /* @__PURE__ */ U({
  __name: "AddAssignedAttributes",
  props: /* @__PURE__ */ _({
    pluginName: {},
    attributes: {}
  }, {
    modelValue: { type: Boolean },
    modelModifiers: {}
  }),
  emits: /* @__PURE__ */ _(["save"], ["update:modelValue"]),
  setup(r) {
    const i = r, m = H(r, "modelValue"), { t: S } = x(), V = L(i.pluginName), { attributesApi: g } = V, I = D(() => ({
      excludedIds: [...i.attributes, ...l.value].map(
        ({ attributeId: s }) => s
      )
    })), l = E([]), n = D(
      () => l.value.length > 0 && l.value.every(({ attributeId: s }) => s)
    );
    function u() {
      l.value.push({});
    }
    function A(s, h) {
      l.value = l.value.map(
        (d, f) => f === h ? { ...d, ...s } : d
      );
    }
    function C({ rowIndex: s }) {
      l.value.splice(s, 1);
    }
    return j(m, (s) => {
      s && (l.value = []);
    }), (s, h) => (y(), M(e(X), {
      modelValue: m.value,
      "onUpdate:modelValue": h[1] || (h[1] = (d) => m.value = d),
      title: e(S)("datahub-ui.dh-shared.newAttributeAssignment"),
      "min-width": "600px",
      "max-width": "800px"
    }, {
      actions: c(() => [
        b(e(J), {
          disabled: !n.value,
          text: e(S)("datahub-ui.dh-shared.applyAttributeAssignments"),
          color: "primary",
          onClick: h[0] || (h[0] = (d) => s.$emit("save", l.value))
        }, null, 8, ["disabled", "text"])
      ]),
      default: c(() => [
        b(e(fe), W({
          data: l.value,
          "create-actions": [
            {
              title: s.$t("datahub-ui.dh-shared.newAttribute"),
              icon: "lucide:plus"
            }
          ]
        }, e(Ne), {
          onCreate: u,
          onRemove: C
        }), {
          "cell-attributeId": c(({ rowIndex: d, row: f }) => [
            re("div", De, [
              b(e(he), {
                data: e(g).getList,
                text: f?.name || "",
                "custom-query": I.value,
                "item-title": "name",
                "item-value": "id",
                "page-size": "",
                "prepend-text": "",
                block: "",
                select: "",
                search: "",
                onChange: (p) => A(
                  { name: p?.name, id: p?.id, attributeId: p?.id },
                  d
                )
              }, null, 8, ["data", "text", "custom-query", "onChange"])
            ])
          ]),
          "cell-requireFlag": c(({ rowIndex: d, cellValue: f }) => [
            b(e(ge), {
              "model-value": f,
              label: s.$t("datahub-ui.dh-shared.required"),
              "onUpdate:modelValue": (p) => A({ requireFlag: p }, d)
            }, null, 8, ["model-value", "label", "onUpdate:modelValue"])
          ]),
          _: 1
        }, 16, ["data", "create-actions"])
      ]),
      _: 1
    }, 8, ["modelValue", "title"]));
  }
}), Ge = /* @__PURE__ */ U({
  __name: "EditAssignedView",
  props: {
    id: {},
    pluginName: {}
  },
  setup(r) {
    const i = r, { t: m } = x(), S = L(i.pluginName), { selectedAttributeSet: V } = z(S), { attributeSetsApi: g } = S, I = ye(), l = E(), n = E(!1), u = E(), A = E(!1), C = E([]);
    let s = [];
    const h = D(() => {
      const a = V.value?.readOnly ? {
        createActions: !1,
        tableActions: void 0,
        rowSelection: Se.NONE
      } : void 0, t = i.id ? void 0 : { data: [], isLoading: !0 };
      return {
        data: g.getAttributes,
        ...Ce,
        ...a,
        ...t,
        customQuery: { setId: i.id }
      };
    }), {
      table: d,
      showError: f,
      isLoading: p,
      isEditMode: w,
      showChangeDialog: v,
      onAddRow: K,
      onEditRow: Y,
      onDeleteRows: Z,
      batchApiCalls: R
    } = Ee({
      addApi: g.addAttributes,
      editApi: g.updateAttribute,
      deleteApi: g.removeAttributes
    });
    function ee(a) {
      a.dhAttribute.dataTypeInstance.attributeSetConfigAllowed && (l.value = a, w.value = !0, v.value = !0);
    }
    function te() {
      w.value = !1, C.value = d.value?.table?.rows.value || [], v.value = !0;
    }
    async function ae(a) {
      const t = a.reduce(
        (T, { attributeId: $, requireFlag: oe }) => (T[+!!oe].push($), T),
        { 0: [], 1: [] }
      ), o = Object.entries(t).filter(([, T]) => T.length).map(([T, $]) => [
        {
          dhAttributeSetId: i.id,
          dhAttributeIds: $,
          requireFlag: T === "1"
        }
      ]);
      await R(K, o, !1), f.value || (v.value = !1);
    }
    async function ie(a) {
      await Y(a), f.value || (v.value = !1);
    }
    async function le(a) {
      try {
        p.value = !0, u.value = await P.getMaps({
          attributeId: a.dhAttribute.id,
          attributeSetId: i.id,
          includeSourcePortMaps: !1
        });
        const t = u.value.etlAttributeSetMap?.destinationAttributeSet;
        if (t?.parentSetId) {
          I.push({
            message: m(
              "datahub-ui.dh-shared.mappingsCannotBeCreatedForInheritedAttributeSets",
              {
                parentSetName: t.parentSetName,
                parentSetId: t.parentSetId
              }
            ),
            type: G.error,
            timeout: 1e4
          });
          return;
        }
        n.value = !0;
      } finally {
        p.value = !1;
      }
    }
    async function ue(a, t) {
      switch (s = t, a) {
        case N.DELETE:
          R(
            Z,
            [[i.id, t.map(({ attributeId: o }) => o)]],
            !1
          );
          return;
        case N.ADD_MAPPING:
        case N.EDIT_MAPPING:
          return w.value = a === N.EDIT_MAPPING, le(t[0]);
        case N.DELETE_MAPPING:
          await P.deleteCalculatedAttributeMap(
            i.id,
            t[0].attributeId
          ), d.value?.reloadTable();
          return;
      }
    }
    function ne() {
      I.push({
        message: m("datahub-ui.dh-shared.TriggeringRecalc"),
        type: G.success
      });
      const { destinationAttributeSet: a, id: t } = u.value.etlAttributeSetMap, o = {
        entityTypeId: a.entityType.id,
        attributeSetId: a.id,
        etlAttributeSetMapId: t,
        destinationAttributeId: s[0].dhAttribute.id,
        destinationLanguageId: 0,
        destinationScopeId: 0
      };
      P.recalculateEntityFields(o);
    }
    async function se(a) {
      try {
        p.value = !0, w.value ? await q.update(a) : await q.create(a), f.value || (n.value = !1, A.value = !0);
      } catch (t) {
        console.error(t);
      } finally {
        d.value?.reloadTable(), p.value = !1;
      }
    }
    return (a, t) => (y(), M(e(Me), W({
      ref_key: "table",
      ref: d,
      "disable-actions": e(p),
      embedded: ""
    }, h.value, {
      onAction: ue,
      onClickedRow: ee,
      onCreate: te
    }), {
      modals: c(() => [
        e(v) ? (y(), me(pe, { key: 0 }, [
          e(w) ? (y(), M(_e, {
            key: 0,
            modelValue: e(v),
            "onUpdate:modelValue": t[0] || (t[0] = (o) => F(v) ? v.value = o : null),
            "attribute-map": l.value,
            "plugin-name": a.pluginName,
            onSave: t[1] || (t[1] = (o) => ie({ ...o, id: l.value.id }))
          }, null, 8, ["modelValue", "attribute-map", "plugin-name"])) : (y(), M($e, {
            key: 1,
            modelValue: e(v),
            "onUpdate:modelValue": t[2] || (t[2] = (o) => F(v) ? v.value = o : null),
            "plugin-name": a.pluginName,
            attributes: C.value,
            onSave: ae
          }, null, 8, ["modelValue", "plugin-name", "attributes"]))
        ], 64)) : n.value ? (y(), M(we, {
          key: 1,
          id: Number(u.value.etlAttributeSetMap?.id),
          modelValue: n.value,
          "onUpdate:modelValue": t[3] || (t[3] = (o) => n.value = o),
          "attribute-map": u.value.etlAttributeMap,
          "destination-attribute": e(s)[0].dhAttribute,
          loading: e(p),
          "plugin-name": a.pluginName,
          onSave: se
        }, null, 8, ["id", "modelValue", "attribute-map", "destination-attribute", "loading", "plugin-name"])) : Q("", !0),
        b(e(Ie), {
          modelValue: A.value,
          "onUpdate:modelValue": t[4] || (t[4] = (o) => A.value = o),
          title: e(m)("datahub-ui.dh-shared.recalculateExistingEntities"),
          confirm: e(m)("datahub-ui.dh-shared.recalculate"),
          message: e(m)("datahub-ui.dh-shared.recalculateMessage"),
          "min-width": "600px",
          "max-width": "800px",
          onConfirm: ne
        }, null, 8, ["modelValue", "title", "confirm", "message"])
      ]),
      _: 1
    }, 16, ["disable-actions"]));
  }
});
export {
  Ge as default
};
