import { defineComponent as pe, ref as v, computed as c, watch as R, onMounted as fe, resolveComponent as p, openBlock as j, createElementBlock as ye, Fragment as ge, createVNode as n, unref as s, withCtx as f, createElementVNode as u, normalizeClass as G, normalizeStyle as he, toDisplayString as E, withDirectives as be, vModelText as _e, createBlock as Se, withModifiers as xe, createCommentVNode as Fe } from "vue";
import { u as ke, _ as we } from "./SingleColumnLayout.vue_vue_type_script_setup_true_lang-sUxHOj47.js";
import { a as Ie, u as Ce, q as V, i as Le, w as Ve } from "./app-Bpb4394e.js";
import { u as Ae } from "./surcharge-aw55KM3G.js";
import { useSnackbar as De, useDialog as Me, useBreakpoints as Oe } from "@feedmepos/ui-library";
import { _ as Pe } from "./FmInventoryTableToolbar.vue_vue_type_script_setup_true_lang-j3aDZ2cT.js";
import { a as Te } from "./FmMultiselectDialog-D-38fV59.js";
import { useI18n as Be } from "@feedmepos/mf-common";
import { u as ze } from "./supplier-Bu6V24R6.js";
import { u as Ee } from "./feature-Cz6F0_cm.js";
import { D as Ne, P as $e, L as qe } from "./app-DiX-EfV6.js";
import { D as H, R as A } from "./row-action.enum-DQ9bJ_uv.js";
import { c as Ue } from "./component-kqxARxvM.js";
const Je = { class: "flex flex-col py-8" }, Re = { class: "fm-typo-en-body-lg-600 text-fm-color-typo-primary line-clamp-1" }, je = { class: "flex flex-col h-full justify-between" }, Ge = { class: "space-y-16" }, He = ["placeholder"], Ke = { class: "flex flex-col gap-16" }, Qe = { class: "flex flex-col gap-8" }, We = { class: "flex-1 fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, Xe = { class: "flex flex-col gap-12" }, Ye = { class: "flex flex-col gap-4" }, Ze = { class: "flex items-center gap-8" }, pt = /* @__PURE__ */ pe({
  __name: "SurchargeView",
  setup(et) {
    const y = De(), N = Me(), D = Ie(), x = Ae(), F = Ce(), M = ze(), K = Ee(), g = v(!1), Q = c(() => x.surcharges), k = v(""), { breakpoints: $ } = Oe(), O = c(() => $.value.xs || $.value.sm), W = c(() => O.value ? 10 : 20), X = ke(), { t: a } = Be(), Y = c(() => F.businessLevel);
    R(Y, T);
    const Z = c(() => (F.businessLevel || K.businessSupplierOnly ? M.businessSuppliers : M.locationSuppliers).map((t) => ({ label: t.name, value: t._id }))), ee = c(() => [
      {
        key: "supplierId",
        type: "string",
        entity: "supplier",
        options: Z.value
      },
      {
        key: "totalCost",
        type: "number"
      }
    ]), te = c(() => D.skus.map((e) => ({
      label: `${e.code} - ${e.name}`,
      sublabel: e.code,
      value: e,
      disabled: e.isInactive,
      tags: e.isInactive ? ["Inactive"] : ["Active"]
    }))), w = c(() => {
      var t;
      const e = (t = o.value.value) == null ? void 0 : t.skuId;
      return e ? D.skus.find((r) => r._id === e) : null;
    });
    function ae() {
      var i;
      const e = (i = o.value.value) == null ? void 0 : i.skuId, t = e ? D.skus.find((d) => d._id === e) : null, r = [
        {
          type: "string",
          key: "tags",
          entity: "item",
          values: ["Inactive", "Active"]
        }
      ];
      N.open({
        title: a("inventory.surcharge.form.value.itemPlaceholder"),
        closeButton: !0,
        contentComponent: Te,
        contentComponentProps: {
          modelValue: t ? [t] : [],
          items: te.value,
          virtualScroll: !0,
          filterAttributes: r,
          maxSelections: 1
        },
        primaryActions: {
          text: a("common.confirm"),
          close: !0
        },
        secondaryActions: {
          text: a("common.close"),
          close: !0,
          variant: "tertiary"
        }
      }).onPrimary((d) => {
        d && d.length > 0 ? z(d[0]._id) : z(null);
      });
    }
    const _ = v(!1), P = v(""), o = v({
      _id: "",
      name: "",
      value: {
        amount: {
          currency: V(),
          amount: 0,
          precision: 0
        }
      },
      rule: null,
      businessId: "",
      applyTo: "purchaseOrder"
    }), S = v(), h = v(""), b = v(null), oe = c(() => [
      {
        label: a("inventory.surcharge.actions.create"),
        value: "create",
        isPrimary: !0,
        prependIcon: "add"
      }
    ]);
    async function T() {
      try {
        await M.readSuppliers();
      } catch {
        y.open({ message: a("Failed to fetch suppliers"), type: "error" });
      }
    }
    async function le() {
      o.value.rule = b.value ? $e.build(b.value) : null, g.value = !0;
      try {
        S.value ? (await x.update(o.value._id, o.value), y.open({
          title: a("Success"),
          message: a("Order surcharge updated successfully"),
          type: "success"
        })) : (await x.create(o.value), y.open({
          title: a("Success"),
          message: a("Order surcharge created successfully"),
          type: "success"
        })), _.value = !1, o.value = {
          _id: "",
          name: "",
          value: { amount: { currency: V(), amount: 0, precision: 0 } },
          rule: null,
          businessId: "",
          applyTo: "purchaseOrder"
        }, S.value = void 0;
      } catch (e) {
        e instanceof Le || y.open({
          title: a("Error"),
          message: a("Failed to save order surcharge"),
          type: "error"
        });
      } finally {
        g.value = !1;
      }
    }
    async function re(e) {
      g.value = !0;
      try {
        await x.delete(e._id), y.open({
          title: a("Success"),
          message: a("inventory.surcharge.delete.success", { name: e.name }),
          type: "success"
        }), _.value = !1;
      } catch (t) {
        y.open({
          title: a("inventory.surcharge.delete.error"),
          message: a("inventory.surcharge.delete.errorMessage", { name: e.name }),
          type: "error"
        }), console.error("failed to delete surcharge", t);
      } finally {
        g.value = !1;
      }
    }
    function ne() {
      S.value && N.open({
        title: a("inventory.surcharge.delete.title", { name: o.value.name }),
        closeButton: !1,
        message: a("inventory.surcharge.delete.message"),
        primaryActions: {
          text: a("common.delete"),
          close: !0,
          variant: "destructive"
        },
        secondaryActions: {
          text: a("common.cancel"),
          close: !0
        }
      }).onPrimary(() => re(o.value));
    }
    function se(e, t) {
      if (e === A.Edit) {
        q(t);
        return;
      }
      if (e === A.Delete) {
        o.value = JSON.parse(JSON.stringify(t)), S.value = t, ne();
        return;
      }
    }
    function ue(e) {
      switch (e) {
        case "create": {
          if (g.value) {
            y.open({
              title: "Loading data...",
              message: "Please wait.",
              type: "info"
            });
            return;
          }
          P.value = "inventory.surcharge.actions.create";
          const t = V();
          o.value = {
            _id: "",
            name: "",
            value: {
              amount: {
                currency: t,
                amount: 0,
                precision: 0
              }
            },
            rule: null,
            businessId: "",
            applyTo: "purchaseOrder"
          }, S.value = void 0, b.value = null, h.value = "", _.value = !0;
          break;
        }
      }
    }
    function q(e) {
      P.value = "inventory.surcharge.actions.edit", o.value = JSON.parse(JSON.stringify(e)), S.value = e, b.value = e.rule ? qe.build(e.rule) : null, h.value = "", _.value = !0;
    }
    function U() {
      var t;
      if (h.value !== "")
        return h.value;
      const e = (t = o.value.value) == null ? void 0 : t.amount;
      return e ? Ve.toFormatString({
        value: {
          amount: e.amount,
          precision: e.precision
        }
      }) : "0";
    }
    let B = null;
    function ie(e) {
      h.value = e, B && clearTimeout(B), B = setTimeout(() => {
        var I, L;
        const t = parseFloat(e) || 0, r = (I = o.value.value) == null ? void 0 : I.amount, i = (r == null ? void 0 : r.precision) ?? 0, d = (r == null ? void 0 : r.currency) ?? V(), C = (L = o.value.value) == null ? void 0 : L.skuId;
        o.value.value = {
          amount: {
            amount: Math.round(t * Math.pow(10, i)),
            precision: i,
            currency: d
          },
          ...C && { skuId: C }
        }, h.value = "";
      }, 500);
    }
    function z(e) {
      const t = o.value.value;
      if (e)
        o.value.value = {
          ...t,
          skuId: e
        };
      else {
        const { skuId: r, ...i } = t || {};
        o.value.value = i;
      }
    }
    const ce = c(() => [
      {
        accessorKey: "name",
        header: () => a("inventory.surcharge.table.name"),
        enableSorting: !0,
        size: "auto"
      },
      {
        id: "action",
        header: "",
        cell(e) {
          return Ue(
            [H[A.Edit], H[A.Delete]],
            (t) => {
              se(t, e.row.original);
            }
          );
        },
        enableSorting: !1,
        size: 40
      }
    ]), me = c(() => {
      let e = Q.value;
      if (k.value) {
        const t = k.value.toLowerCase();
        e = e.filter((r) => r.name.toLowerCase().includes(t));
      }
      return e;
    });
    return fe(() => {
      T(), x.browse();
    }), R(
      () => F._currentLocation,
      () => {
        F._currentLocation && T();
      }
    ), (e, t) => {
      const r = p("FmTable"), i = p("FmFormGroup"), d = p("FmLabel"), C = p("FmTextField"), I = p("FmButton"), L = p("FmIcon"), de = p("FmCard"), ve = p("FmSideSheet");
      return j(), ye(ge, null, [
        n(we, {
          title: s(a)("inventory.surcharge.title"),
          actions: oe.value,
          "onClick:action": ue
        }, {
          default: f(() => [
            u("div", {
              class: G([
                "flex flex-col gap-8 max-h-full",
                {
                  "p-0": O.value,
                  "px-24 ": !O.value
                }
              ])
            }, [
              n(Pe, {
                searchable: "",
                search: k.value,
                "onUpdate:search": t[0] || (t[0] = (l) => k.value = l)
              }, null, 8, ["search"]),
              n(r, {
                style: he(s(X).tableHeight),
                "column-defs": ce.value,
                "row-data": me.value,
                "search-value": k.value,
                loading: g.value || !s(F)._currentLocation,
                "page-size": W.value,
                onRowClick: t[1] || (t[1] = (l) => q(l.original))
              }, {
                "list-row": f((l) => [
                  u("div", Je, [
                    u("div", Re, E(l.original.name), 1)
                  ])
                ]),
                _: 1
              }, 8, ["style", "column-defs", "row-data", "search-value", "loading", "page-size"])
            ], 2)
          ]),
          _: 1
        }, 8, ["title", "actions"]),
        n(ve, {
          modelValue: _.value,
          "onUpdate:modelValue": t[8] || (t[8] = (l) => _.value = l),
          header: s(a)(P.value),
          "max-width": 800
        }, {
          "side-sheet-footer": f(() => [
            n(I, {
              variant: "primary",
              class: "w-full",
              onClick: le,
              loading: g.value,
              label: s(a)("inventory.surcharge.actions.save")
            }, null, 8, ["loading", "label"])
          ]),
          default: f(() => [
            u("div", je, [
              u("div", Ge, [
                n(i, {
                  modelValue: o.value.name,
                  "onUpdate:modelValue": t[3] || (t[3] = (l) => o.value.name = l),
                  label: s(a)("inventory.surcharge.form.name"),
                  required: !0,
                  rules: [(l) => !!l.trim().length || s(a)("inventory.surcharge.form.nameRequired")]
                }, {
                  default: f(() => [
                    be(u("input", {
                      "onUpdate:modelValue": t[2] || (t[2] = (l) => o.value.name = l),
                      class: "w-full p-8 border rounded-md outline-none focus:border-blue-500",
                      placeholder: s(a)("inventory.surcharge.form.namePlaceholder")
                    }, null, 8, He), [
                      [_e, o.value.name]
                    ])
                  ]),
                  _: 1
                }, 8, ["modelValue", "label", "rules"]),
                u("div", Ke, [
                  u("div", Qe, [
                    n(d, {
                      label: s(a)("inventory.surcharge.form.rules.title"),
                      required: ""
                    }, null, 8, ["label"]),
                    u("div", We, E(s(a)("inventory.surcharge.form.rules.description")), 1)
                  ]),
                  n(de, {
                    variant: "outlined",
                    class: "p-16"
                  }, {
                    default: f(() => {
                      var l;
                      return [
                        u("div", Xe, [
                          u("div", Ye, [
                            n(i, {
                              "model-value": parseFloat(U()),
                              label: s(a)("inventory.surcharge.form.value.amount"),
                              required: !0,
                              rules: [(m) => m > 0 || "Amount must be greater than 0"]
                            }, {
                              default: f(() => [
                                n(C, {
                                  "model-value": U(),
                                  "onUpdate:modelValue": t[4] || (t[4] = (m) => ie(m)),
                                  onBlur: t[5] || (t[5] = () => h.value = ""),
                                  type: "number",
                                  step: 0.01
                                }, null, 8, ["model-value"])
                              ]),
                              _: 1
                            }, 8, ["model-value", "label", "rules"]),
                            n(i, {
                              "model-value": (l = o.value.value) == null ? void 0 : l.skuId,
                              label: s(a)("inventory.surcharge.form.value.item"),
                              "label-mark": "optional"
                            }, {
                              default: f(() => [
                                u("div", {
                                  class: "flex items-center justify-between p-12 border border-fm-color-neutral-gray-300 rounded-md cursor-pointer hover:border-fm-color-neutral-gray-400 transition-colors",
                                  onClick: ae
                                }, [
                                  u("span", {
                                    class: G([
                                      "line-clamp-1 fm-typo-en-body-lg-400",
                                      w.value ? "text-fm-color-typo-primary" : "text-fm-color-typo-tertiary"
                                    ])
                                  }, E(w.value ? `${w.value.code} - ${w.value.name}` : s(a)("inventory.surcharge.form.value.itemPlaceholder")), 3),
                                  u("div", Ze, [
                                    w.value ? (j(), Se(I, {
                                      key: 0,
                                      variant: "tertiary",
                                      icon: "close",
                                      onClick: t[6] || (t[6] = xe((m) => z(null), ["stop"]))
                                    })) : Fe("", !0),
                                    n(L, {
                                      name: "arrow_drop_down",
                                      size: "md"
                                    })
                                  ])
                                ])
                              ]),
                              _: 1
                            }, 8, ["model-value", "label"]),
                            n(s(Ne), {
                              modelValue: b.value,
                              "onUpdate:modelValue": t[7] || (t[7] = (m) => b.value = m),
                              attributes: ee.value
                            }, null, 8, ["modelValue", "attributes"]),
                            n(i, {
                              "model-value": b.value,
                              rules: [(m) => {
                                var J;
                                return !!((J = m == null ? void 0 : m.rules) != null && J.length) || "At least one rule is required";
                              }]
                            }, null, 8, ["model-value", "rules"])
                          ])
                        ])
                      ];
                    }),
                    _: 1
                  })
                ])
              ])
            ])
          ]),
          _: 1
        }, 8, ["modelValue", "header"])
      ], 64);
    };
  }
});
export {
  pt as default
};
