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