import { defineComponent as me, ref as O, watch as W, computed as w, h as f, withModifiers as ue, resolveComponent as x, createBlock as T, openBlock as F, withCtx as i, createVNode as n, createElementVNode as y, unref as e, normalizeStyle as pe, normalizeClass as C, withDirectives as B, createElementBlock as de, Fragment as fe, renderList as ve, toDisplayString as R, createTextVNode as ye, vShow as D } from "vue";
import { storeToRefs as X } from "pinia";
import { a as ge } from "./v4-C5fRBp_c.js";
import { _ as be } from "./Default.vue_vue_type_script_setup_true_lang-C25HSYeu.js";
import { u as he } from "./message-dialog-UoMWOnil.js";
import { b as xe, f as Ce } from "./global-loader-CbmVhJAK.js";
import { useSnackbar as _e, useBreakpoints as ke, components as we, FmButtonColorThemeVariant as $e } from "@feedmepos/ui-library";
import { _ as Ie } from "./NoData.vue_vue_type_script_setup_true_lang-CdFXBqlX.js";
import { useRouter as Se, useRoute as Fe, onBeforeRouteLeave as Re } from "vue-router";
import { useI18n as Le } from "@feedmepos/mf-common";
import { r as Z } from "./i18n-Cif1I9J2.js";
const Ve = { class: "fm-typo-en-body-md-400 text-fm-color-typo-secondary" }, ze = { class: "w-[343px]" }, Pe = { class: "fm-typo-en-body-md-600" }, Ye = /* @__PURE__ */ me({
  __name: "Report",
  setup(Ne) {
    const { t: r, te: A } = Le(), M = Se(), q = Fe(), p = ge(), { business: ee } = X(xe()), {
      reports: d,
      categories: $,
      pinReport: I,
      isOpenAddReportDialog: te,
      scrollPositionY: J,
      customReportQuota: K,
      canCreateCustomReport: oe
    } = X(p), { promptMessage: U } = he(), { promptLoader: j } = Ce(), v = _e(), { breakpoints: s } = ke(), g = O();
    Re(() => {
      g.value && (J.value = g.value.$el.children[0].scrollTop);
    }), W(g, () => {
      g.value && setTimeout(() => {
        g.value.$el.children[0].scrollTop = J.value;
      }, 200);
    });
    const L = w(() => I.value && d.value ? d.value.filter((t) => {
      var o;
      return (o = I.value) == null ? void 0 : o.includes(t.id);
    }) : []);
    W(
      [() => ee.value],
      () => {
        p.refreshPinReport();
      },
      { immediate: !0 }
    );
    const Y = w(() => L.value.length > 0 ? d.value.filter(
      (t) => L.value.findIndex((o) => o.id === t.id) === -1
    ) : d.value), { FmButton: re, FmMenu: V, FmMenuItem: _, FmIcon: z, FmChip: P } = we, E = w(() => [
      { value: void 0, label: "All" },
      ...$.value.map((t) => ({
        value: t.id,
        label: t.name
      }))
    ]), b = O(E.value[0]), S = O(""), h = w(() => Y.value.length === 0 || $.value.length === 0 ? [] : [
      ...L.value.map((o) => {
        const a = $.value.find((c) => c.id === o.category);
        return {
          name: Z(r, A, o.name, "other"),
          categoryId: (a == null ? void 0 : a.id) ?? "",
          category: a != null && a.name ? r(`report.category.${a.name}`) : r("report.common.uncategorized"),
          reportId: o.id,
          editable: o.editable,
          pin: !0
        };
      }).filter((o) => b.value.value && o.categoryId !== b.value.value ? !1 : o.name.toLowerCase().indexOf(S.value.toLowerCase()) !== -1),
      ...Y.value.map((o) => {
        const a = $.value.find((c) => c.id === o.category);
        return {
          name: Z(r, A, o.name, "other"),
          categoryId: (a == null ? void 0 : a.id) ?? "",
          category: a != null && a.name ? r(`report.category.${a.name}`) : r("report.common.uncategorized"),
          reportId: o.id,
          editable: o.editable,
          pin: !1
        };
      }).filter((o) => b.value.value && o.categoryId !== b.value.value ? !1 : o.name.toLowerCase().indexOf(S.value.toLowerCase()) !== -1)
    ]), ae = w(
      () => h.value.map((t) => `${t.name}${t.category}`).toString()
    ), le = [
      {
        accessorKey: "name",
        header: r("report.common.name"),
        enableSorting: !1,
        cell: (t) => t.getValue()
      },
      {
        accessorKey: "category",
        header: r("report.common.category"),
        enableSorting: !1,
        meta: {
          width: "200px"
        },
        cell: (t) => f(
          P,
          {
            class: `${t.getValue() !== r("report.common.uncategorized") ? "bg-fm-color-system-info-100 text-fm-color-typo-info" : "text-fm-color-typo-secondary"} fm-typo-en-body-sm-600`,
            compact: !0
          },
          { default: () => t.getValue() }
        )
      },
      {
        accessorKey: "",
        id: "Action",
        header: r("report.common.actions"),
        meta: {
          width: "100px"
        },
        cell: (t) => {
          const o = t.row.original, a = o.reportId, c = d.value.find((m) => m.id === a), N = [
            {
              label: r("report.common.duplicate"),
              onClick: () => {
                c && G(c);
              },
              variant: "",
              disabled: !1
            },
            {
              label: r("report.common.remove"),
              onClick: () => {
                c && H(c);
              },
              variant: "destructive",
              disabled: !o.editable
            }
          ];
          return f(
            "div",
            {
              class: `flex ${s.value.lg || s.value.md ? "justify-end" : ""} items-center`
            },
            {
              default: () => [
                f(
                  "button",
                  {
                    onClick: ue(() => {
                      c && Q(c);
                    }, ["stop"]),
                    class: `text-fm-color-neutral-gray-400 ${o.pin ? "" : "show-pin"} hover:bg-fm-color-opacity-sm rounded-lg flex items-center justify-center`
                  },
                  {
                    default: () => [
                      f(
                        z,
                        {
                          name: "keep",
                          class: "px-12 p-8",
                          outline: !o.pin,
                          size: "md"
                        },
                        {}
                      )
                    ]
                  }
                ),
                f(
                  V,
                  { stopClickPropagation: !0, shift: !0 },
                  {
                    default: () => N.map(
                      (m) => f(
                        _,
                        {
                          onClick: m.disabled ? {} : m.onClick,
                          label: m.label,
                          class: m.disabled ? "text-fm-color-typo-disabled" : m.variant === "destructive" ? "text-fm-color-typo-error" : "",
                          disabled: m.disabled
                        },
                        {
                          label: () => f("p", m.label)
                        }
                      )
                    ),
                    "menu-button": () => f(
                      re,
                      {
                        variant: "tertiary",
                        size: "md",
                        icon: "more_vert",
                        iconColor: $e.NeutralGray400
                      },
                      {}
                    )
                  }
                )
              ]
            }
          );
        }
      }
    ];
    async function G(t) {
      if (await U({
        title: r("report.common.duplicate"),
        message: r("report.messages.confirmAction", {
          action: r("report.common.duplicate"),
          name: t.name
        })
      })) {
        const a = JSON.parse(JSON.stringify(t));
        a.editable = !0, a.id = "", a.name = `${a.name} ${r("report.common.duplicate")}`, j(async () => {
          try {
            await p.createOrUpdateReport(a), v.open({
              message: `${r("report.messages.duplicateSuccess", { name: a.name })}`,
              type: "success"
            });
          } catch (c) {
            v.open({ message: JSON.stringify(c), type: "error" });
          }
        });
      }
    }
    async function H(t) {
      await U({
        title: r("report.messages.deleteReport"),
        message: r("report.messages.confirmDelete", { name: t.name })
      }) && j(async () => {
        try {
          await p.removeReport(t), v.open({
            message: r("report.messages.deleteSuccess", { name: t.name }),
            type: "success"
          });
        } catch (a) {
          v.open({ message: JSON.stringify(a), type: "error" });
        }
      });
    }
    function ne() {
      if (oe.value)
        te.value = !0;
      else {
        let t = `Your current plan only support up to ${K.value} custom reports.`;
        K.value === 0 && (t = "Your current plan does not support custom report."), v.open({
          message: t,
          type: "error"
        });
      }
    }
    function Q(t) {
      I.value && I.value.includes(t.id) ? (v.open({
        message: `${r("report.common.unpin")} ${t.name} ${r("report.common.successful")}`,
        type: "success"
      }), p.clearPinReport(t.id)) : (v.open({
        message: `${r("report.common.pin")} ${t.name} ${r("report.common.successful")}`,
        type: "success"
      }), p.cachePinReport(t));
    }
    function se(t) {
      b.value = t;
    }
    return (t, o) => {
      const a = x("FmPageHead"), c = x("FmSearch"), N = x("FmForm"), m = x("FmListItem"), ce = x("FmList"), ie = x("FmTable");
      return F(), T(be, null, {
        default: i(() => [
          n(a, {
            title: e(r)("report.common.report", 1),
            class: "h-[68px]",
            actions: [
              {
                label: `${e(r)("report.view.report.add")}`,
                value: "add",
                isPrimary: !0,
                prependIcon: "add"
              }
            ],
            "onClick:action": o[0] || (o[0] = (l) => ne())
          }, null, 8, ["title", "actions"]),
          y("div", {
            class: C(`overflow-y-hidden flex flex-col gap-8 ${e(s).sm || e(s).xs ? "mb-20" : ""}`),
            style: pe({ height: `calc(100% - ${e(s).lg || e(s).md ? 72 : 64}px)` })
          }, [
            n(N, {
              class: C(`flex items-center gap-2 ${e(s).sm || e(s).xs ? "px-3" : "px-24"}`)
            }, {
              default: i(() => [
                n(e(V), null, {
                  "menu-button": i(() => [
                    n(e(P), { class: "fm-typo-en-body-md-600 text-fm-color-neutral-gray-400" }, {
                      default: i(() => [
                        y("p", null, R(e(r)(`report.category.${b.value.label}`)), 1),
                        n(e(z), { name: "expand_more" })
                      ]),
                      _: 1
                    })
                  ]),
                  default: i(() => [
                    (F(!0), de(fe, null, ve(E.value, (l, u) => (F(), T(e(_), {
                      key: u,
                      label: e(r)(`report.category.${l.label}`),
                      onClick: () => se(l)
                    }, null, 8, ["label", "onClick"]))), 128))
                  ]),
                  _: 1
                }),
                y("div", {
                  class: C(`flex ${e(s).sm || e(s).xs ? "justify-center items-center" : ""}`)
                }, [
                  y("p", Ve, R(e(r)("report.common.results", { count: h.value.length })), 1)
                ], 2),
                o[3] || (o[3] = y("div", { class: "grow" }, null, -1)),
                y("div", ze, [
                  n(c, {
                    modelValue: S.value,
                    "onUpdate:modelValue": o[1] || (o[1] = (l) => S.value = l),
                    class: C(`${e(s).lg || e(s).md ? "grow" : ""}`)
                  }, null, 8, ["modelValue", "class"])
                ])
              ]),
              _: 1
            }, 8, ["class"]),
            B((F(), T(ie, {
              key: ae.value,
              ref_key: "table",
              ref: g,
              class: C([e(s).sm || e(s).xs ? "px-0" : "px-24", "report-table"]),
              style: { height: "calc(100% - 40px)" },
              "column-defs": le,
              "row-data": h.value,
              "page-size": h.value.length,
              "hide-footer": !0,
              "row-class-name": "row",
              onRowClick: o[2] || (o[2] = (l) => {
                e(p).updateCurrentReportId(l.original.reportId), e(M).push({
                  name: "reportView",
                  query: e(q).query
                });
              })
            }, {
              "list-row": i(({ original: l }) => [
                n(ce, {
                  onClick: () => {
                    l.reportId && (e(p).updateCurrentReportId(l.reportId), e(M).push({
                      name: "reportView",
                      query: e(q).query
                    }));
                  }
                }, {
                  default: i(() => [
                    n(m, {
                      tag: "label",
                      label: l.name,
                      clickable: ""
                    }, {
                      append: i(() => [
                        n(e(P), {
                          class: C(
                            l.category !== "Uncategorized" ? "bg-fm-color-system-info-100 text-fm-color-typo-info" : "text-fm-color-typo-secondary"
                          ),
                          compact: !0
                        }, {
                          default: i(() => [
                            y("p", Pe, R(l.category), 1)
                          ]),
                          _: 2
                        }, 1032, ["class"]),
                        n(e(V), {
                          placement: "left",
                          "stop-click-propagation": !0
                        }, {
                          "menu-button": i(() => [
                            n(e(z), {
                              name: "more_vert",
                              class: "btn-color"
                            })
                          ]),
                          default: i(() => [
                            n(e(_), {
                              label: l.pin ? "Unpin" : "Pin",
                              onClick: () => {
                                const u = e(d).find(
                                  (k) => k.id === l.reportId
                                );
                                u && Q(u);
                              }
                            }, null, 8, ["label", "onClick"]),
                            n(e(_), {
                              label: e(r)("report.common.duplicate"),
                              onClick: () => {
                                const u = e(d).find(
                                  (k) => k.id === l.reportId
                                );
                                u && G(u);
                              }
                            }, null, 8, ["label", "onClick"]),
                            B(n(e(_), {
                              label: e(r)("report.common.delete"),
                              class: "text-fm-color-typo-error",
                              onClick: () => {
                                const u = e(d).find(
                                  (k) => k.id === l.reportId
                                );
                                u && H(u);
                              }
                            }, {
                              label: i(() => [
                                ye(R(e(r)("report.common.delete")), 1)
                              ]),
                              _: 2
                            }, 1032, ["label", "onClick"]), [
                              [D, l.editable]
                            ])
                          ]),
                          _: 2
                        }, 1024)
                      ]),
                      _: 2
                    }, 1032, ["label"])
                  ]),
                  _: 2
                }, 1032, ["onClick"])
              ]),
              _: 1
            }, 8, ["class", "row-data", "page-size"])), [
              [D, h.value.length > 0]
            ]),
            B(n(Ie, null, null, 512), [
              [D, h.value.length === 0]
            ])
          ], 6)
        ]),
        _: 1
      });
    };
  }
});
export {
  Ye as default
};
