import { defineComponent as ue, resolveComponent as X, createBlock as le, openBlock as C, unref as l, isRef as Fe, withCtx as G, createElementVNode as ae, createVNode as Y, toDisplayString as re, createTextVNode as Ne, onMounted as me, watch as k, ref as Q, computed as oe, onBeforeMount as $e, onBeforeUnmount as Be, createElementBlock as K, Fragment as xe } from "vue";
import { detectLocale as U, useCoreStore as W } from "@feedmepos/mf-common";
import { d, u as Je, a as se, b as Qe, c as ie, e as Ue, f as ze, s as je, t as H } from "./app-BHYwfe1u.js";
import { storeToRefs as q } from "pinia";
import { u as Ve, a as Pe } from "./_plugin-vue_export-helper-onplcgja.js";
import { u as Ge, a as Ke } from "./GlobalFilterSelect.vue_vue_type_script_setup_true_lang-BZlXHYzg.js";
import { u as We, _ as He } from "./NavigationTab.vue_vue_type_script_setup_true_lang-Bwrmuhdd.js";
import { u as ce } from "./message-dialog-UoMWOnil.js";
import { useRoute as Xe, useRouter as Ye } from "vue-router";
const Ze = { class: "fm-typo-en-body-md-400 text-ellipsis overflow-hidden" }, Me = /* @__PURE__ */ ue({
  __name: "Dialog",
  setup(T) {
    const { t: c } = Ve(), g = ce(), { isOpened: S, message: L, title: E } = q(ce());
    return (O, _) => {
      const F = X("FmButton"), z = X("FmDialog");
      return C(), le(z, {
        modelValue: l(S),
        "onUpdate:modelValue": _[0] || (_[0] = (j) => Fe(S) ? S.value = j : null),
        overlay: "",
        "close-button": !1,
        "z-index": 3e3
      }, {
        "dialog-header": G(() => [
          Ne(re(l(E)), 1)
        ]),
        default: G(() => [
          ae("p", Ze, re(l(L)), 1)
        ]),
        "dialog-footer": G(() => [
          _[1] || (_[1] = ae("div", { class: "grow" }, null, -1)),
          Y(F, {
            label: l(c)("report.common.cancel"),
            variant: "tertiary",
            onClick: l(g).dismiss
          }, null, 8, ["label", "onClick"]),
          Y(F, {
            label: l(c)("report.common.confirm"),
            onClick: l(g).confirm
          }, null, 8, ["label", "onClick"])
        ]),
        _: 1
      }, 8, ["modelValue"]);
    };
  }
}), de = Q(U());
function et() {
  const T = (c) => {
    switch (de.value = c, c) {
      case "zh-CN":
        d.locale("zh-cn");
        break;
      default:
        d.locale("en");
        break;
    }
  };
  return me(() => {
    T(U());
  }), k(() => U(), T, { deep: !0, immediate: !0 }), {
    currentLocale: de
  };
}
d.locale(U() === "zh-CN" ? "zh-cn" : "en");
const tt = ["src"], nt = ["src"], mt = /* @__PURE__ */ ue({
  __name: "App",
  setup(T) {
    const { businessId: c, token: g, country: S } = q(Je()), { sessionUser: L, currentBusiness: E, currentCountry: O, registerSidebarComponent: _ } = W(), { getRestaurantAndWarehouse: F, getBusinessSetting: z, beginBusinessLoad: j, completeBusinessLoad: fe } = se(), pe = Qe(), { getFeatureFlags: ge } = pe, { version: y } = q(ie()), { getSettings: Se } = Ue(), { promptLoader: ye } = Pe(), n = Xe(), N = Ye(), w = Ge(), Z = We(), o = se(), b = ie(), { suppressReportRouteSync: $ } = q(b), { getReports: ve, getOverviewReport: De, getReportConfig: Ie, currentReportId: M } = w, { currentReportId: he, reports: _e } = q(w), { getSchema: Re } = Ke(), { fetchSchedules: Le } = Z, { init: Ee } = ze(), V = Q("v5"), B = Q(!1), x = Q(!0), Oe = oe(() => `https://portal-v1.feedme.cc/b/${c.value}/report/CLOSE_UP?showHeader=false&country=${S.value.toUpperCase()}&menuOption=business-report&token=${g.value}&v2=true&reportV5Button=true`), we = oe(() => `https://report-v4.feedme.cc?businessId=${c.value}&country=${S.value}&token=${g.value}&reportV3Button=true`);
    k(
      [() => E.value, () => L.value, () => O.value],
      () => {
        var e, a;
        const t = ((e = E.value) == null ? void 0 : e.id) ?? "";
        E.value && L.value && O.value && (je(O.value), c.value !== t && (c.value = t), g.value = ((a = L.value) == null ? void 0 : a.token) ?? "", S.value = O.value ?? "");
      },
      { immediate: !0 }
    );
    function ee(t) {
      if (typeof t.data == "string")
        try {
          const e = JSON.parse(t.data);
          (e == null ? void 0 : e.token) !== "" && (e == null ? void 0 : e.token) !== void 0 && (g.value = e.token);
        } catch (e) {
          console.error(e);
        }
    }
    function te(t) {
      if (typeof t.data == "string")
        try {
          const e = JSON.parse(t.data);
          (e == null ? void 0 : e.v5) === !0 ? y.value = V.value : (e == null ? void 0 : e.v3) === !0 && (y.value = "v3");
        } catch (e) {
          console.error(e);
        }
    }
    k(y, () => {
      ["v3", "v4"].includes(y.value) ? W().hideSidebarToggle(!0) : W().hideSidebarToggle(!1);
    }), $e(() => {
      _(He);
    }), me(() => {
      console.log("5.27.19", !0), window.addEventListener("message", ee), window.addEventListener("message", te);
    }), Be(() => {
      window.removeEventListener("message", ee), window.removeEventListener("message", te), w.$dispose(), Z.$dispose();
    });
    function be(t) {
      try {
        return decodeURIComponent(t);
      } catch {
        return t;
      }
    }
    function J(t) {
      if (typeof t != "string" || t.length === 0) return;
      const e = t.includes("%") ? [t, be(t)] : [t];
      for (const a of e)
        try {
          const s = JSON.parse(a);
          if (typeof s == "string")
            try {
              return JSON.parse(s);
            } catch {
              return s;
            }
          return s;
        } catch {
        }
    }
    function ne(t) {
      if (!t || typeof t != "object") return !1;
      const e = t;
      return typeof e.hour == "number" && typeof e.minute == "number";
    }
    function Ae(t = n.query) {
      const e = t, a = e.startDate ? d(e.startDate).startOf("day").toISOString() : void 0, s = e.endDate ? d(e.endDate).endOf("day").toISOString() : void 0, m = typeof e.timeStart == "string", i = typeof e.timeEnd == "string", f = J(e.timeStart), v = J(e.timeEnd), D = ne(f) ? f : null, A = ne(v) ? v : null, R = e.compareStartDate ? d(e.compareStartDate).startOf("day").toISOString() : void 0, p = e.compareEndDate ? d(e.compareEndDate).endOf("day").toISOString() : void 0, I = e.isAllLocation === "true" || e.isAllLocation === void 0;
      let h = [];
      if (I)
        h = o.selectedLocationIds ?? [];
      else {
        const r = J(e.locationIds);
        h = Array.isArray(r) ? r : [];
      }
      let u = e.reportId || M;
      if (_e.value.find((r) => r.id === u) || (u = M), u && u !== w.currentReportId && w.updateCurrentReportId(u), a || s) {
        const r = o.dateRange;
        (r.startDate !== a || r.endDate !== s) && o.setDateRange({ startDate: a, endDate: s });
      }
      if (m || i) {
        const r = o.timeRange;
        (r.start !== D || r.end !== A) && o.setTimeRange({ start: D, end: A });
      }
      if (R || p) {
        const r = o.compareDateRange;
        (r.startDate !== R || r.endDate !== p) && o.setCompareDateRange({
          startDate: R,
          endDate: p
        });
      }
      if (!I) {
        const r = o.selectedLocationIds;
        r.length === h.length && r.every((P, Te) => P === h[Te]) || o.setSelectedLocationIds(h);
      }
      return {
        // TODO: this returned value can used for getBusinessSetting
        reportId: u,
        startDate: e.startDate,
        endDate: e.endDate,
        timeStart: e.timeStart,
        timeEnd: e.timeEnd,
        compareStartDate: e.compareStartDate,
        compareEndDate: e.compareEndDate,
        locationIds: typeof e.locationIds == "string" ? e.locationIds : void 0,
        isAllLocation: e.isAllLocation
      };
    }
    return k(
      () => c.value,
      async (t, e) => {
        if (t !== "") {
          B.value = !1, j(t);
          const a = "mf-report-prev-business-id", s = (() => {
            try {
              return sessionStorage.getItem(a);
            } catch {
              return null;
            }
          })(), m = !!s && s !== t;
          let i = { ...n.query }, f = !1;
          if (!x.value || e !== void 0 || m) {
            o.setSelectedLocationIds([]);
            const {
              locationIds: v,
              startDate: D,
              endDate: A,
              timeStart: R,
              timeEnd: p,
              compareStartDate: I,
              compareEndDate: h,
              ...u
            } = n.query;
            i = {
              ...u,
              isAllLocation: "true"
            }, f = !0, await N.replace({
              name: n.name,
              params: n.params,
              query: i
            });
          }
          $.value !== void 0 && ($.value = !0), await ye(async () => {
            await Ee({
              apiKey: "6GhcttsJ9Rj9cTevcdrpin",
              url: "https://flag.feedme.farm/api/v1/",
              enableAnalytics: !1,
              cacheFlags: !1
            });
            const v = await Ie();
            V.value = v.version, y.value = V.value, await ge(), n.name === "template" && !b.canAccessTemplate() && await N.replace({
              name: "reports",
              query: n.query
            });
            const D = b.canAccess(
              H.report_accessOverview
            ), A = b.canAccess(
              H.report_accessSetting
            ), R = b.canAccess(
              H.report_accessIntegration
            ), p = [
              Re(),
              Le(),
              ve(),
              F(
                (() => {
                  const I = J(i.locationIds);
                  return Array.isArray(I) ? I : void 0;
                })()
              )
            ];
            if (D && p.push(De()), R && p.push(Se()), await Promise.all(p), A && await z(), Ae(i), f) {
              const {
                locationIds: I,
                startDate: h,
                endDate: u,
                timeStart: Ce,
                timeEnd: r,
                compareStartDate: ke,
                compareEndDate: qe,
                ...P
              } = n.query;
              (n.query.locationIds !== void 0 || n.query.startDate !== void 0 || n.query.endDate !== void 0 || n.query.timeStart !== void 0 || n.query.timeEnd !== void 0 || n.query.compareStartDate !== void 0 || n.query.compareEndDate !== void 0 || n.query.isAllLocation !== "true") && await N.replace({
                name: n.name,
                params: n.params,
                query: {
                  ...P,
                  isAllLocation: "true"
                }
              });
            }
            fe(t);
            try {
              sessionStorage.setItem(a, t);
            } catch {
            }
          }), B.value = !0, x.value && (x.value = !1);
        }
      },
      {
        immediate: !0
      }
    ), k(
      () => (B.value, {
        reportId: he.value,
        selectedLocationIds: o.selectedLocationIds,
        dateRange: o.dateRange,
        timeRange: o.timeRange,
        compareDateRange: o.compareDateRange,
        timezone: o.timezone
      }),
      (t) => {
        if (!B.value || !t.reportId || x.value) return;
        if ($.value) {
          $.value = !1;
          return;
        }
        const e = t.selectedLocationIds, a = t.dateRange, s = t.timeRange, m = t.compareDateRange, i = {
          ...n.query,
          reportId: t.reportId,
          startDate: a.startDate ? d(a.startDate).startOf("day").toISOString() : void 0,
          endDate: a.endDate ? d(a.endDate).endOf("day").toISOString() : void 0,
          compareStartDate: m.startDate ? d(m.startDate).startOf("day").toISOString() : void 0,
          compareEndDate: m.endDate ? d(m.endDate).endOf("day").toISOString() : void 0,
          timeStart: s.start ? JSON.stringify(s.start) : void 0,
          timeEnd: s.end ? JSON.stringify(s.end) : void 0
        }, f = e.length === o.locations.length;
        i.isAllLocation = String(f), f ? delete i.locationIds : e.length > 0 ? i.locationIds = JSON.stringify(e) : delete i.locationIds;
        const v = JSON.stringify(n.query), D = JSON.stringify(i);
        v !== D && N.replace({
          name: n.name,
          params: n.params,
          query: i
        });
      },
      { deep: !0 }
    ), et(), (t, e) => {
      const a = X("router-view");
      return C(), K(xe, null, [
        Y(Me),
        l(y) === "v3" ? (C(), K("iframe", {
          key: 0,
          class: "bg-white h-full w-full",
          src: Oe.value
        }, null, 8, tt)) : l(y) === "v4" ? (C(), K("iframe", {
          key: 1,
          class: "bg-white h-full w-full",
          src: we.value
        }, null, 8, nt)) : (C(), le(a, { key: 2 }))
      ], 64);
    };
  }
});
export {
  mt as default
};
