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_dayjs = __toESM(require("dayjs"));
var import_store = require("../../store");
var import_hooks = require("../../hooks");
var import_const = require("../../const");
var import_const2 = require("../const");
var GlobalTimeout = 1e3 * 60 * 2;
var RequestTimeout = 1e3 * 5;
var useTimeResultQuery = (api, resultCheck, handleLinklySuccess) => {
  const dispatch = (0, import_store.useDispatch)();
  const { numRef, modeRef, deviceRef, orderIdRef } = (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 queryIdRef = (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;
      console.log("单次请求超时，将尝试重试");
      _log("RequestTimeout" /* RequestTimeout */);
      (_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) {
        console.log("交易成功，终止查询");
        (0, import_utils.sendWarningLog)({
          title: `Linkly-${isPay ? "Pay" : "Refund"}-交易成功`,
          content: [{ key: "response", value: JSON.stringify(result) }]
        });
        reset();
        handleLinklySuccess(result);
        return;
      }
      if ((data == null ? void 0 : data.status) == 0 && (data == null ? void 0 : data.signature_flag) != 1) {
        console.log("交易状态为0需要继续查询");
        _log("Querying" /* Querying */, result);
        isQueryFinishedRef.current = false;
        setTimeout(() => {
          _resultQuery();
        }, 1500);
        return;
      }
      if (data.status < 0) {
        console.log("交易失败，终止查询");
        (0, import_utils.sendWarningLog)({
          title: `Linkly-${isPay ? "Pay" : "Refund"}-交易失败`,
          content: [{ key: "response", value: JSON.stringify(result) }]
        });
        reset();
        result.code = import_const.PayStatus.Unknown;
        (_a2 = failRef.current) == null ? void 0 : _a2.call(failRef, result, false);
        return;
      }
      if (data.signature_flag == 1) {
        console.log("交易需要签名，终止查询");
        (0, import_utils.sendWarningLog)({
          title: `Linkly-${isPay ? "Pay" : "Refund"}-交易需要签名`,
          content: [{ key: "response", value: JSON.stringify(result) }]
        });
        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) {
        _log("AbortError" /* AbortError */);
        console.log("Error: 请求被取消，将继续查询");
        isQueryFinishedRef.current = false;
        setTimeout(() => {
          _resultQuery();
        }, 1500);
        return;
      }
      if (!(error == null ? void 0 : error.code) || `${error.code}` === import_const.PayStatus.Timeout) {
        _log("NetworkError" /* NetworkError */);
        console.log("Error: 网关类报错，将继续查询");
        isQueryFinishedRef.current = false;
        setTimeout(() => {
          _resultQuery();
        }, 1500);
        return;
      }
      _log("Error" /* Error */, 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 = () => {
    console.log("linkly查询状态重制<<<<<<<----");
    _log("Reset" /* Reset */);
    if (globalTimeoutIdRef.current) {
      clearTimeout(globalTimeoutIdRef.current);
      globalTimeoutIdRef.current = null;
    }
    if (requestTimeoutIdRef.current) {
      clearTimeout(requestTimeoutIdRef.current);
      requestTimeoutIdRef.current = null;
    }
    if (controllerRef.current) {
      controllerRef.current.abort();
      controllerRef.current = null;
    }
    startTimeRef.current = null;
    isRequestCanceledRef.current = false;
    isQueryFinishedRef.current = true;
    queryIdRef.current = null;
  };
  const _log = (type, res) => {
    var _a, _b;
    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 content = [
      {
        key: "description",
        value: JSON.stringify({
          queryId: queryIdRef.current,
          orderId: orderIdRef.current,
          type,
          date: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss")
        })
      },
      { key: "params", value: JSON.stringify(params) }
    ];
    if (type === "Error" /* Error */) {
      content.push({ key: "error", value: JSON.stringify(res) });
    } else {
      content.push({ key: "response", value: JSON.stringify(res) });
    }
    (0, import_utils.sendWarningLog)({
      title: `Linkly-${isPay ? "Pay" : "Refund"}-交易结果轮询`,
      content
    });
  };
  const run = () => {
    reset();
    globalTimeoutIdRef.current = setTimeout(() => {
      var _a;
      console.log("全局超时，终止所有重试");
      _log("GlobalTimeout" /* GlobalTimeout */);
      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;
    queryIdRef.current = (0, import_utils.getUniqueId)();
    console.log("开始查询linkly结果---->>>>>>>");
    _log("Start" /* Start */);
    return _resultQuery();
  };
  return { run, stop: reset };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useTimeResultQuery
});
