import { getCurrentInstance as te, defineComponent as oe, computed as h, watch as ne, h as R, resolveComponent as S, createElementBlock as C, openBlock as _, Fragment as O, normalizeClass as D, createElementVNode as k, createVNode as V, unref as t, isRef as j, withCtx as P, renderList as ie, createBlock as G, createCommentVNode as $, toDisplayString as I, withModifiers as Q } from "vue";
import { G as H, u as J, Q as W, M as N, A as z, I as L, B as se, ap as q, a5 as re } from "./index.vue_vue_type_script_setup_true_lang-BMVa5UfU.js";
import { useI18n as X, useCoreStore as le } from "@feedmepos/mf-common";
import { useDialog as ce, useSnackbar as Z, FmButtonVariant as A, components as de, useBreakpoints as ue } from "@feedmepos/ui-library";
import { _ as me } from "./app-D-J2cjak.js";
import { a as ye, l as ee, T as pe } from "./index-4cR8a2UZ.js";
import { u as fe } from "./search-BAPEUu1R.js";
import { f as F } from "./currency-DBI5JSrw.js";
import { defineStore as _e } from "pinia";
import { C as ke } from "./catalog-rNLjUMn-.js";
import { c as ve } from "./createComponentProgrammatically-Bt2rn1IQ.js";
function we(T, M, l, m) {
  var y, v, w, g;
  const i = L(T);
  i.override.takeaway[l._id] = {
    price: l.price || void 0
  };
  const f = [...l.usedBy, ...M.usedBy];
  for (const r of f) {
    const c = l.usedBy.some(
      (e) => e._id == r._id && e.combinationKey == r.combinationKey
    ) ? l._id : null, a = (i.override.items[r._id] || []).findIndex(
      (e) => e.combinationKey === r.combinationKey
    );
    let d;
    if (a >= 0)
      d = (y = i.override.items[r._id][a]) != null && y.takeawayUsed ? L((v = i.override.items[r._id][a]) == null ? void 0 : v.takeawayUsed) : void 0;
    else {
      const e = m.find((u) => u._id === r._id);
      r.combinationKey ? d = ((g = (w = e == null ? void 0 : e.variant) == null ? void 0 : w.variantCombinations.find(
        (u) => u.combinationKey === r.combinationKey
      )) == null ? void 0 : g.takeawayUsed) || (e == null ? void 0 : e.takeawayUsed) : d = e == null ? void 0 : e.takeawayUsed;
    }
    if (a >= 0)
      i.override.items[r._id][a].takeawayUsed = c;
    else if (d !== c) {
      const e = {
        _id: r._id,
        combinationKey: r.combinationKey,
        takeawayUsed: c
      };
      i.override.items[r._id] = [...i.override.items[r._id] || [], e];
    }
  }
  return i;
}
const ge = _e("takeaway-manager", () => {
  const T = ce(), M = Z(), l = H(M), m = W(l), i = J(), f = te(), { t: y } = X(), v = (a) => {
    var e, u;
    const { vNode: d } = ve(
      ye,
      f,
      a
    );
    (u = (e = d.component) == null ? void 0 : e.exposed) == null || u.trigger();
  };
  async function w(a) {
    var u, U;
    const e = ((U = (u = i.currentCatalog) == null ? void 0 : u.override.takeaway[a._id]) == null ? void 0 : U.price) ? null : i.state.menu.modules.takeaway.find((b) => b._id === a._id);
    v({
      initialValue: a,
      applyProduct: !0,
      bindToVariant: i.rules.item.bindToVariant,
      fallback: e,
      action: "update",
      "onUpdate:takeaway": async (b) => {
        let o = L(i.currentCatalog);
        b.price ? o.override.takeaway[a._id] = { price: b.price } : delete o.override.takeaway[a._id], o = we(o, a, b, i.state.menu.modules.item), await new ke(o, i, m.updateMenu, T).update();
      }
    });
  }
  async function g(a) {
    v({
      initialValue: a,
      bindToVariant: i.rules.item.bindToVariant,
      applyProduct: !0,
      action: "update",
      "onUpdate:takeaway": async (d) => {
        await m.updateMenu(
          {
            module: z.F_MENU_MODULE_V4_KEY.enum.takeaway,
            operation: N.F_OPERATION_TYPE.update,
            data: d,
            link: ee(d.usedBy || [])
          },
          d.name
        );
      }
    });
  }
  async function r(a) {
    i.currentCatalog ? await w(a) : await g(a);
  }
  async function c(a) {
    T.open({
      title: y("menu.common.dialog.remove.takeaway.title"),
      message: y("menu.common.dialog.remove.takeaway.message", { name: a.name }),
      primaryActions: {
        text: y("menu.common.actions.remove"),
        close: !0,
        variant: A.Destructive
      },
      secondaryActions: {
        text: y("menu.common.actions.cancel"),
        close: !0
      }
    }).onPrimary(async () => {
      await m.updateMenu(
        {
          module: z.F_MENU_MODULE_V4_KEY.enum.takeaway,
          operation: N.F_OPERATION_TYPE.delete,
          data: a._id
        },
        a.name,
        !0
      );
    });
  }
  return {
    deleteTakeaway: c,
    updateTakeaway: r
  };
}), be = {
  key: 0,
  class: /* @__PURE__ */ D(["flex-1 overflow-hidden", "space-y-16", "flex flex-col", "overflow-hidden", "pt-16"])
}, he = {
  class: "flex items-center space-x-8 justify-end"
}, xe = {
  class: "w-[320px]"
}, Ce = {
  class: "px-16 pt-8"
}, Ve = {
  class: /* @__PURE__ */ D(["flex-1", "overflow-scroll", "divide-y divide-fm-color-neutral-gray-100"])
}, Te = ["onClick"], Me = {
  class: "flex-1"
}, Ue = {
  class: "fm-typo-en-body-lg-600 mb-4"
}, Ee = {
  class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary"
}, Ke = {
  class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary"
}, Ie = {
  key: 1,
  class: "xs:pt-24"
}, Re = /* @__PURE__ */ oe({
  __name: "Takeaway",
  emits: ["update:count"],
  setup(T, {
    emit: M
  }) {
    const l = J(), m = ge(), i = h(() => l.rules.item.bindToVariant), f = h(() => l.rules.takeaway), y = W(H(Z())), v = le(), w = h(() => se.Country.getCountry(v.currentCountry.value).currency), g = h(() => l.takeaways.map((o) => ({
      ...o,
      usedBy: l.items.reduce((s, p) => {
        var n, E, Y;
        const x = p.takeawayUsed === o._id;
        if ((!i.value || !((E = (n = p.variant) == null ? void 0 : n.variantGroupIds) != null && E.length)) && x)
          s.push({
            _id: p._id
          });
        else {
          const ae = (((Y = p.variant) == null ? void 0 : Y.variantCombinations) || []).filter((K) => K.takeawayUsed === o._id || !K.takeawayUsed && x).map((K) => ({
            _id: p._id,
            combinationKey: K.combinationKey
          }));
          s = [...s, ...ae];
        }
        return s;
      }, [])
    }))), {
      filter: r,
      searchKey: c
    } = fe(), a = h(() => g.value.filter((o) => r([o.name, F(o.price, !1)]))), d = M;
    ne(() => a.value.length, (o) => {
      d("update:count", o);
    }, {
      immediate: !0
    });
    const {
      t: e
    } = X(), u = h(() => [{
      accessorKey: "name",
      header: () => e("menu.takeaway.table.columns.name"),
      enableSorting: !1,
      size: 700
    }, {
      accessorKey: "price",
      header: () => e("menu.takeaway.table.columns.price", {
        symbol: w.value.symbol
      }),
      enableSorting: !1,
      size: 200,
      meta: {
        textAlign: "right"
      },
      cell: (o) => {
        const s = o.getValue();
        return F(s, !1);
      }
    }, {
      accessorKey: "usedBy",
      header: () => e("menu.takeaway.table.columns.products"),
      enableSorting: !1,
      size: 200,
      cell: (o) => {
        const s = o.getValue(), p = q(l.categorizedItems, s).flatMap((x) => x.items).length ?? 0;
        return e("menu.takeaway.table.items_linked", {
          count: p
        });
      }
    }, {
      id: "action",
      size: 52,
      meta: {
        cellClass: "pl-16",
        headerContentClass: "-mx-16"
      },
      cell: (o) => R("div", {
        class: "flex justify-end items-center"
      }, [f.value.delete ? R(de.FmButton, {
        prependIcon: "delete",
        variant: A.Tertiary,
        textColor: "neutral-gray-400",
        onClick: (s) => {
          s.stopPropagation(), m.deleteTakeaway(o.row.original);
        }
      }) : null])
    }]), U = ue(), b = h(() => U.breakpoints.value.xs);
    return (o, s) => {
      const p = S("fm-search"), x = S("fm-table"), B = S("fm-button");
      return g.value.length ? (_(), C(O, {
        key: 0
      }, [b.value ? (_(), C(O, {
        key: 1
      }, [k("div", Ce, [V(p, {
        class: "w-full",
        autofocus: "",
        modelValue: t(c),
        "onUpdate:modelValue": s[2] || (s[2] = (n) => j(c) ? c.value = n : null),
        placeholder: t(e)("menu.takeaway.table.search.placeholder")
      }, null, 8, ["modelValue", "placeholder"])]), k("div", Ve, [(_(!0), C(O, null, ie(a.value, (n) => (_(), C("div", {
        key: n._id,
        class: D(["py-12 px-16", "flex  space-x-8", "items-center"]),
        onClick: () => {
          f.value.edit && t(m).updateTakeaway(n);
        }
      }, [k("div", Me, [k("p", Ue, I(n.name), 1), k("p", Ee, I(`${t(q)(t(l).categorizedItems, n.usedBy).flatMap((E) => E.items).length ?? 0} items linked`), 1), k("p", Ke, " Price: " + I(w.value.symbol) + I(t(F)(n.price, !1)), 1)]), f.value.delete ? (_(), G(B, {
        key: 0,
        variant: t(A).Tertiary,
        "text-color": "neutral-gray-400",
        "prepend-icon": "delete",
        onClick: Q(() => t(m).deleteTakeaway(n), ["stop"])
      }, null, 8, ["variant", "onClick"])) : $("", !0)], 8, Te))), 128))])], 64)) : (_(), C("div", be, [k("div", he, [k("div", xe, [V(p, {
        autofocus: "",
        modelValue: t(c),
        "onUpdate:modelValue": s[0] || (s[0] = (n) => j(c) ? c.value = n : null),
        placeholder: t(e)("menu.takeaway.table.search.placeholder")
      }, null, 8, ["modelValue", "placeholder"])])]), V(me, null, {
        default: P(() => [V(x, {
          "column-defs": u.value,
          loading: t(y).checkMenuIsLoading(),
          "page-size": a.value.length,
          "row-data": a.value,
          "search-value": t(c),
          "shrink-at": !1,
          class: "flex-1 overflow-hidden",
          "hide-footer": "",
          "pin-header-row": "",
          onRowClick: s[1] || (s[1] = (n) => {
            f.value.edit && t(m).updateTakeaway(n.original);
          })
        }, null, 8, ["column-defs", "loading", "page-size", "row-data", "search-value"])]),
        _: 1
      })]))], 64)) : (_(), C("div", Ie, [V(t(re), {
        subtitle: t(e)("menu.takeaway.empty.subtitle"),
        title: t(e)("menu.takeaway.empty.title")
      }, {
        action: P(() => [f.value.create ? (_(), G(t(pe), {
          key: 0,
          "bind-to-variant": i.value,
          action: "add",
          "apply-product": "",
          "onUpdate:takeaway": s[3] || (s[3] = (n) => t(y).updateMenu({
            module: t(z.F_MENU_MODULE_V4_KEY).enum.takeaway,
            operation: t(N.F_OPERATION_TYPE).create,
            data: n,
            link: t(ee)(n.usedBy || [])
          }, n.name))
        }, {
          default: P(({
            trigger: n
          }) => [V(B, {
            "prepend-icon": "add",
            label: t(e)("menu.takeaway.empty.action"),
            onClick: Q(n, ["stop"])
          }, null, 8, ["label", "onClick"])]),
          _: 1
        }, 8, ["bind-to-variant"])) : $("", !0)]),
        _: 1
      }, 8, ["subtitle", "title"])]));
    };
  }
});
export {
  Re as _
};
