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