var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/ticketBooking/hooks/pisellos/useProducts.ts
var useProducts_exports = {};
__export(useProducts_exports, {
  useProducts: () => useProducts
});
module.exports = __toCommonJS(useProducts_exports);
var import_ahooks = require("ahooks");
var import_bookingTicket = require("./bookingTicket");
var import_react = require("react");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_dayjs = __toESM(require("dayjs"));
var import_useLogger = __toESM(require("../../../../hooks/useLogger"));
var import_usePromotion = __toESM(require("../../../booking/hooks/usePromotion"));
var import_utils = require("@pisell/utils");
var DEFAULT_IDLE_TIMEOUT = 1e4;
var USER_INTERACTION_EVENTS = ["click", "touchstart", "keydown"];
var useProducts = (notAvailableRef) => {
  var _a;
  const bookingTicket = (0, import_bookingTicket.useBookingTicket)();
  const context = (0, import_useEngineContext.default)();
  const platform = (0, import_useEngineContext.usePlatform)();
  const [products, setProducts] = (0, import_react.useState)([]);
  const [loading, setLoading] = (0, import_react.useState)(true);
  const isFirstLoadRef = (0, import_react.useRef)(true);
  const isFirstLoadDataRef = (0, import_react.useRef)(true);
  const { getApp } = ((_a = context.appHelper) == null ? void 0 : _a.utils) || {};
  const logger = (0, import_useLogger.default)();
  const { formatProductList } = (0, import_usePromotion.default)();
  const useCurrentId = (0, import_react.useRef)((0, import_utils.getUniqueId)());
  const pendingWsDataRef = (0, import_react.useRef)(null);
  const idleTimerRef = (0, import_react.useRef)(null);
  const app = getApp();
  const [scheduleTimePoints, setScheduleTimePoints] = (0, import_react.useState)([]);
  const scheduledTaskQueueIdRef = (0, import_react.useRef)("booking-schedule-products");
  const paramsRef = (0, import_react.useRef)(void 0);
  const isDeferEnabled = (0, import_ahooks.useMemoizedFn)(() => {
    return (localStorage == null ? void 0 : localStorage.getItem("__PISELL_DEFER_WS_UPDATE__")) === "true";
  });
  const getDeferTimeout = (0, import_ahooks.useMemoizedFn)(() => {
    const val = Number(localStorage == null ? void 0 : localStorage.getItem("__PISELL_DEFER_WS_UPDATE_TIMEOUT__"));
    return val > 0 ? val : DEFAULT_IDLE_TIMEOUT;
  });
  const flushPendingData = (0, import_ahooks.useMemoizedFn)(() => {
    if (pendingWsDataRef.current) {
      setProducts(formatProductList(pendingWsDataRef.current));
      pendingWsDataRef.current = null;
    }
  });
  const resetIdleTimer = (0, import_ahooks.useMemoizedFn)(() => {
    if (idleTimerRef.current) {
      clearTimeout(idleTimerRef.current);
    }
    idleTimerRef.current = setTimeout(() => {
      flushPendingData();
    }, getDeferTimeout());
  });
  const ensureIdleTimer = (0, import_ahooks.useMemoizedFn)(() => {
    if (!idleTimerRef.current) {
      idleTimerRef.current = setTimeout(() => {
        flushPendingData();
      }, getDeferTimeout());
    }
  });
  (0, import_react.useEffect)(() => {
    const handler = () => {
      if (!isDeferEnabled()) return;
      resetIdleTimer();
    };
    USER_INTERACTION_EVENTS.forEach((evt) => {
      document.addEventListener(evt, handler, { capture: true, passive: true });
    });
    return () => {
      USER_INTERACTION_EVENTS.forEach((evt) => {
        document.removeEventListener(evt, handler, { capture: true });
      });
      if (idleTimerRef.current) {
        clearTimeout(idleTimerRef.current);
        idleTimerRef.current = null;
      }
    };
  }, []);
  const getProducts = (0, import_ahooks.useMemoizedFn)(async (params) => {
    var _a2;
    setLoading(true);
    try {
      paramsRef.current = params;
      logger.addLog({
        title: "useProducts: getProducts 调用",
        metadata: {
          params
        }
      });
      const products2 = await bookingTicket.loadProducts(params, {
        callback: (res) => {
          var _a3;
          if (!((_a3 = res == null ? void 0 : res.data) == null ? void 0 : _a3.list)) return;
          if (isDeferEnabled()) {
            pendingWsDataRef.current = res.data.list;
            ensureIdleTimer();
            return;
          }
          setProducts(formatProductList(res.data.list));
        },
        subscriberId: useCurrentId
      });
      logger.addLog({
        title: "useProducts: getProducts 返回",
        metadata: {
          products: (products2 == null ? void 0 : products2.length) || 0
        }
      });
      setProducts(formatProductList(products2));
      setLoading(false);
      isFirstLoadRef.current = false;
    } catch (error) {
      logger.addLog({
        title: "useProducts: getProducts 错误",
        metadata: {
          error: error == null ? void 0 : error.message
        }
      });
      if ((error == null ? void 0 : error.code) === 607100 && (isFirstLoadRef.current || products.length > 0)) {
        (_a2 = notAvailableRef.current) == null ? void 0 : _a2.open();
      }
      setLoading(false);
      isFirstLoadRef.current = false;
    }
  });
  (0, import_react.useEffect)(() => {
    return () => {
      bookingTicket.unsubscribeProductQuery(useCurrentId);
    };
  }, []);
  (0, import_react.useEffect)(() => {
    var _a2, _b, _c;
    if (platform === "shop") {
      return;
    }
    try {
      const app2 = (_c = (_b = (_a2 = context == null ? void 0 : context.appHelper) == null ? void 0 : _a2.utils) == null ? void 0 : _b.getApp) == null ? void 0 : _c.call(_b);
      if (!app2 || !app2.tasksManager) {
        console.warn("App 或 tasksManager 不可用");
        return;
      }
      app2.tasksManager.addTaskFunction("getProducts", async ({ task }) => {
        console.log("定时执行 getProducts，参数：", task.payload);
        logger.addLog({
          title: "useProducts: 定时执行 getProducts",
          metadata: {
            payload: task.payload,
            task
          }
        });
        await getProducts(task.payload);
        logger.addLog({
          title: "useProducts: 定时执行 getProducts 完成",
          metadata: {
            payload: task.payload,
            task
          }
        });
        return { status: "success" };
      });
      if (scheduleTimePoints && scheduleTimePoints.length > 0) {
        app2.tasksManager.clearTasks({
          module: "scheduledTasks",
          queueId: scheduledTaskQueueIdRef.current
        });
        const tasks = scheduleTimePoints.map((timePoint) => {
          const [hours, minutes] = timePoint.split(":");
          const executeDayjs = (0, import_dayjs.default)().hour(parseInt(hours, 10)).minute(parseInt(minutes, 10)).second(4);
          const executeAt = executeDayjs.format("YYYY-MM-DD HH:mm:ss");
          const schedule_date = executeDayjs.format("YYYY-MM-DD");
          return {
            action: "getProducts",
            payload: {
              ...paramsRef.current,
              schedule_date,
              schedule_datetime: executeAt
            },
            scheduled: {
              executeAt
            }
          };
        });
        app2.tasksManager.addTask({
          module: "scheduledTasks",
          queueId: scheduledTaskQueueIdRef.current,
          tasks
        });
        app2.tasksManager.run({
          module: "scheduledTasks",
          queueId: scheduledTaskQueueIdRef.current
        });
        logger.addLog({
          title: "useProducts: 创建定时任务",
          metadata: {
            tasks: tasks.length,
            log: `已为 ${tasks.length} 个时间点创建定时任务`
          }
        });
        console.log(`已为 ${tasks.length} 个时间点创建定时任务`);
      }
    } catch (error) {
      console.error("创建定时任务失败：", error);
      logger.addLog({
        title: "useProducts: 创建定时任务失败",
        metadata: {
          error: error == null ? void 0 : error.message
        }
      });
    }
    return () => {
      var _a3, _b2, _c2;
      try {
        const app2 = (_c2 = (_b2 = (_a3 = context == null ? void 0 : context.appHelper) == null ? void 0 : _a3.utils) == null ? void 0 : _b2.getApp) == null ? void 0 : _c2.call(_b2);
        if (app2 && app2.tasksManager) {
          logger.addLog({
            title: "useProducts: 清理定时任务",
            metadata: {
              queueId: scheduledTaskQueueIdRef.current
            }
          });
          app2.tasksManager.clearTasks({
            module: "scheduledTasks",
            queueId: scheduledTaskQueueIdRef.current
          });
        }
      } catch (error) {
        logger.addLog({
          title: "useProducts: 清理定时任务失败",
          metadata: {
            error: error == null ? void 0 : error.message
          }
        });
        console.error("清理定时任务失败：", error);
      }
    };
  }, [scheduleTimePoints]);
  const getScheduleTimePoints = (0, import_ahooks.useMemoizedFn)(async (params) => {
    if (platform === "shop") {
      return;
    }
    const scheduleTimePoints2 = await bookingTicket.getScheduleTimePoints(params);
    setScheduleTimePoints(scheduleTimePoints2);
  });
  return {
    getScheduleTimePoints,
    getProducts,
    products,
    loading
  };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useProducts
});
