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/eftposPay/linkly/hooks/useTimeQuery.ts
var useTimeQuery_exports = {};
__export(useTimeQuery_exports, {
  useTimeResultQuery: () => useTimeResultQuery
});
module.exports = __toCommonJS(useTimeQuery_exports);
var import_react = require("react");
var import_utils = require("@pisell/utils");
var import_store = require("../../store");
var import_hooks = require("../../hooks");
var import_const = require("../../const");
var import_const2 = require("../const");
var import_payLog = __toESM(require("../../utils/payLog"));
var GlobalTimeout = 1e3 * 60 * 2;
var RequestTimeout = 1e3 * 5;
var QUERY_INTERVAL = 1e3 * 2;
var useTimeResultQuery = (api, resultCheck, handleLinklySuccess) => {
  const dispatch = (0, import_store.useDispatch)();
  const { numRef, modeRef, deviceRef } = (0, import_hooks.useStoreRef)();
  const fail = (0, import_hooks.useFail)(0);
  const failRef = (0, import_react.useRef)(fail);
  const isPay = modeRef.current === import_const.ModeEnum.Pay || modeRef.current === import_const.ModeEnum.FullPay;
  const controllerRef = (0, import_react.useRef)(null);
  const requestTimeoutIdRef = (0, import_react.useRef)(
    null
  );
  const globalTimeoutIdRef = (0, import_react.useRef)(null);
  const isRequestCanceledRef = (0, import_react.useRef)(false);
  const startTimeRef = (0, import_react.useRef)(null);
  const isQueryFinishedRef = (0, import_react.useRef)(true);
  const queryIntervalTimerRef = (0, import_react.useRef)(null);
  const _resultQuery = async () => {
    var _a, _b;
    if (controllerRef.current) {
      controllerRef.current.abort();
      controllerRef.current = null;
    }
    if (requestTimeoutIdRef.current) {
      clearTimeout(requestTimeoutIdRef.current);
      requestTimeoutIdRef.current = null;
    }
    controllerRef.current = new AbortController();
    const { signal } = controllerRef.current;
    isRequestCanceledRef.current = false;
    requestTimeoutIdRef.current = setTimeout(() => {
      var _a2;
      import_payLog.default.log("Linkly轮询：单次请求超时");
      (_a2 = controllerRef.current) == null ? void 0 : _a2.abort();
      isRequestCanceledRef.current = true;
    }, RequestTimeout);
    const requestApi = isPay ? api.linklyPayQuery : api.linklyRefundQuery;
    const params = {
      // 设备id
      pinpad_id: (_b = (_a = deviceRef == null ? void 0 : deviceRef.current) == null ? void 0 : _a.metadata) == null ? void 0 : _b.linkly_pinpad_id,
      // 交易流水号
      session_id: numRef.current
    };
    const requestPromise = requestApi(params, { signal });
    requestPromise.then((result) => {
      var _a2;
      console.log("Success: 请求成功", result);
      if (checkNeedToHandleResult()) {
        console.log("Success: 全局超时或不需要处理结果，终止查询");
        return;
      }
      isQueryFinishedRef.current = true;
      const data = (result == null ? void 0 : result.data) || {};
      if (data.status == 1) {
        import_payLog.default.log("Linkly轮询：交易成功");
        reset();
        handleLinklySuccess(result);
        return;
      }
      if ((data == null ? void 0 : data.status) == 0 && (data == null ? void 0 : data.signature_flag) != 1) {
        import_payLog.default.log("Linkly轮询：继续查询", { data });
        isQueryFinishedRef.current = false;
        queryIntervalTimerRef.current = setTimeout(() => {
          _resultQuery();
        }, QUERY_INTERVAL);
        return;
      }
      if (data.status < 0) {
        import_payLog.default.log("Linkly轮询：交易失败", { data });
        reset();
        result.code = import_const.PayStatus.Unknown;
        (_a2 = failRef.current) == null ? void 0 : _a2.call(failRef, result, false);
        return;
      }
      if (data.signature_flag == 1) {
        import_payLog.default.log("Linkly轮询：需要签名", { data });
        reset();
        gotoSignature();
        return;
      }
    }).catch((error) => {
      var _a2;
      console.log("Error: 请求失败", error);
      if (checkNeedToHandleResult()) {
        console.log("Error: 全局超时或不需要处理结果，终止查询");
        return;
      }
      isQueryFinishedRef.current = true;
      if ((error == null ? void 0 : error.name) === "AbortError" /* AbortError */ || isRequestCanceledRef.current) {
        import_payLog.default.log("Linkly轮询：请求被取消，继续查询");
        isQueryFinishedRef.current = false;
        queryIntervalTimerRef.current = setTimeout(() => {
          _resultQuery();
        }, QUERY_INTERVAL);
        return;
      }
      if (!(error == null ? void 0 : error.code) || `${error.code}` === import_const.PayStatus.Timeout) {
        import_payLog.default.log("Linkly轮询：网关报错，继续查询");
        isQueryFinishedRef.current = false;
        queryIntervalTimerRef.current = setTimeout(() => {
          _resultQuery();
        }, QUERY_INTERVAL);
        return;
      }
      import_payLog.default.log("Linkly轮询：查询失败", { error });
      reset();
      (_a2 = failRef.current) == null ? void 0 : _a2.call(failRef, error, true);
    }).finally(() => {
      if (requestTimeoutIdRef.current) {
        clearTimeout(requestTimeoutIdRef.current);
        requestTimeoutIdRef.current = null;
      }
    });
  };
  const gotoSignature = () => {
    dispatch((0, import_store.updateStatus)(import_const.StatusEnum.Question));
    dispatch(
      (0, import_store.updateState)({
        title: import_utils.locales.getText("page.eftpos-pay.text.receipt.again.title")
      })
    );
    dispatch((0, import_store.updateCustom)({ actionStatus: import_const2.LinklyActionStatus.Signature }));
  };
  const checkNeedToHandleResult = () => {
    return checkIsGlobalTimeout() || !resultCheck() || isQueryFinishedRef.current;
  };
  const checkIsGlobalTimeout = () => {
    if (startTimeRef.current) {
      const elapsedTime = Date.now() - startTimeRef.current;
      if (elapsedTime > GlobalTimeout) {
        return true;
      } else {
        return false;
      }
    }
    return false;
  };
  const reset = () => {
    import_payLog.default.log("Linkly轮询：重置查询状态");
    if (globalTimeoutIdRef.current) {
      clearTimeout(globalTimeoutIdRef.current);
      globalTimeoutIdRef.current = null;
    }
    if (requestTimeoutIdRef.current) {
      clearTimeout(requestTimeoutIdRef.current);
      requestTimeoutIdRef.current = null;
    }
    if (queryIntervalTimerRef.current) {
      clearTimeout(queryIntervalTimerRef.current);
      queryIntervalTimerRef.current = null;
    }
    if (controllerRef.current) {
      controllerRef.current.abort();
      controllerRef.current = null;
    }
    startTimeRef.current = null;
    isRequestCanceledRef.current = false;
    isQueryFinishedRef.current = true;
  };
  const run = () => {
    reset();
    globalTimeoutIdRef.current = setTimeout(() => {
      var _a;
      import_payLog.default.log("Linkly轮询：全局超时");
      setTimeout(reset, 0);
      (_a = failRef.current) == null ? void 0 : _a.call(failRef, { code: import_const.PayStatus.Timeout }, false);
    }, GlobalTimeout);
    startTimeRef.current = Date.now();
    isQueryFinishedRef.current = false;
    import_payLog.default.log("Linkly轮询：开始查询");
    return _resultQuery();
  };
  return { run, stop: reset };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useTimeResultQuery
});
