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