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