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/windcave/helper.tsx
var helper_exports = {};
__export(helper_exports, {
  useFail: () => useFail,
  useValidate: () => useValidate
});
module.exports = __toCommonJS(helper_exports);
var import_utils = require("@pisell/utils");
var import_react = require("react");
var import_const = require("../const");
var import_store = require("../store");
var import_const2 = require("./const");
var import_hooks = require("../hooks");
var import_timer = __toESM(require("./timer"));
var Max4004 = 1;
var useFail = () => {
  const dispatch = (0, import_store.useDispatch)();
  const { custom } = (0, import_store.useContextData)();
  const { modeRef, clientRef } = (0, import_hooks.useStoreRef)();
  const ref = (0, import_react.useRef)((custom == null ? void 0 : custom.retry) || 0);
  (0, import_react.useEffect)(() => {
    ref.current = (custom == null ? void 0 : custom.retry) || 0;
  }, [custom == null ? void 0 : custom.retry]);
  return (0, import_react.useCallback)(
    (res, isMark = false) => {
      if (!res || !res.code) {
        dispatch(
          (0, import_store.updateCustom)({
            errorStatus: "unknow"
            // unknow know
          })
        );
        dispatch((0, import_store.updateComponent)("UnknowFail"));
        return;
      }
      const [code] = [`${res.code}`];
      if (`${res.code}` === import_const.PayStatus.Unknown) {
        dispatch(
          (0, import_store.updateCustom)({
            failCustom: {
              isPosNetworkError: false,
              status: "fail",
              fail: import_utils.locales.getText("page.eftpos-pay.text.transaction.fail"),
              warn: null,
              title: import_utils.locales.getText("page.eftpos-pay.text.failed")(
                modeRef.current
              )
            }
          })
        );
        dispatch((0, import_store.updateComponent)("FailCustom"));
        return;
      }
      console.log(code, ref.current, Max4004);
      if (code === import_const.PayStatus.NoPay) {
        if (ref.current > Max4004) {
          dispatch(
            (0, import_store.updateCustom)({
              retry: 0,
              failCustom: {
                isPosNetworkError: false,
                status: "fail",
                fail: import_utils.locales.getText("page.eftpos-pay.text.transaction.fail"),
                warn: null,
                titl: import_utils.locales.getText("page.eftpos-pay.text.failed")(
                  modeRef.current
                )
              }
            })
          );
          dispatch((0, import_store.updateComponent)("FailCustom"));
          return;
        }
        ref.current += 1;
        dispatch(
          (0, import_store.updateState)({
            number: ""
          })
        );
        dispatch(
          (0, import_store.updateCustom)({
            retry: ref.current,
            list: []
          })
        );
        dispatch((0, import_store.updateKey)(Date.now()));
        return;
      }
      if (code === import_const.PayStatus.PayTimeout) {
        dispatch(
          (0, import_store.updateCustom)({
            failCustom: {
              isPosNetworkError: false,
              status: "fail",
              fail: import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.fail.timeout"
              ),
              title: import_utils.locales.getText("page.eftpos-pay.text.failed")(
                modeRef.current
              ),
              warn: null
            }
          })
        );
        dispatch((0, import_store.updateComponent)("FailCustom"));
        return;
      }
      if (code === import_const.PayStatus.Timeout) {
        if (isMark) {
          if (clientRef.current === import_const.ClientEnum.User) {
            dispatch(
              (0, import_store.updateCustom)({
                failCustom: {
                  isPosNetworkError: true,
                  status: "warn",
                  fail: null,
                  title: import_utils.locales.getText("page.eftpos-pay.text.timedout.title"),
                  warn: import_utils.locales.getText(
                    "page.eftpos-pay.text.transaction.eftpos.fail.other"
                  )
                }
              })
            );
            dispatch((0, import_store.updateComponent)("FailCustom"));
            return;
          }
          dispatch(
            (0, import_store.updateState)({
              manual: {
                title: import_utils.locales.getText("page.eftpos-pay.text.timedout.title"),
                text: import_utils.locales.getText("page.eftpos-pay.text.timedout.text")(
                  modeRef.current
                )
              }
            })
          );
          dispatch((0, import_store.updateComponent)("Manual"));
          return;
        }
        dispatch(
          (0, import_store.updateCustom)({
            failCustom: {
              isPosNetworkError: false,
              status: "fail",
              fail: import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.fail.timeout"
              ),
              title: import_utils.locales.getText("page.eftpos-pay.text.failed")(
                modeRef.current
              ),
              warn: null
            }
          })
        );
        dispatch((0, import_store.updateComponent)("FailCustom"));
        return;
      }
      if (code === import_const.PayStatus.PayOtherEftposFailed) {
        dispatch(
          (0, import_store.updateCustom)({
            failCustom: {
              isPosNetworkError: false,
              status: "fail",
              fail: import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.fail.terminal"
              ),
              title: import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.fail.terminal.title"
              ),
              warn: null
            }
          })
        );
        dispatch((0, import_store.updateComponent)("FailCustom"));
        return;
      }
      if (code === import_const.PayStatus.PayCardErrorFailed) {
        dispatch(
          (0, import_store.updateCustom)({
            failCustom: {
              status: "fail",
              fail: import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.fail.cancel"
              ),
              title: import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.fail.cancel.title"
              ),
              warn: null
            }
          })
        );
        dispatch((0, import_store.updateComponent)("FailCustom"));
        return;
      }
      if (code === import_const.PayStatus.NoNetWork || code === import_const.PayStatus.SocketError) {
        dispatch(
          (0, import_store.updateCustom)({
            failCustom: {
              isPosNetworkError: true,
              status: "warn",
              fail: null,
              title: import_utils.locales.getText("page.eftpos-pay.text.interrupted"),
              warn: clientRef.current === import_const.ClientEnum.Merchant ? `${import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.eftpos.fail.title"
              )}
${import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.eftpos.fail.power"
              )}
 ${import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.eftpos.fail.device"
              )}
${import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.eftpos.fail.network"
              )}
${import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.eftpos.fail.if"
              )(modeRef.current)}` : import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.eftpos.fail.other"
              )
            }
          })
        );
        dispatch((0, import_store.updateComponent)("FailCustom"));
        return;
      }
      if (code === import_const.PayStatus.PayBankRefuses) {
        dispatch(
          (0, import_store.updateCustom)({
            failCustom: {
              isPosNetworkError: false,
              status: "fail",
              fail: import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.back.declined.text"
              ),
              title: import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.back.declined.title"
              ),
              warn: null
            }
          })
        );
        dispatch((0, import_store.updateComponent)("FailCustom"));
        return;
      }
      if (code === import_const.PayStatus.SignatureDeclined) {
        dispatch(
          (0, import_store.updateCustom)({
            failCustom: {
              isPosNetworkError: false,
              status: "fail",
              fail: import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.user.declined.text"
              ),
              title: import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.user.declined.title"
              ),
              warn: null
            }
          })
        );
        dispatch((0, import_store.updateComponent)("FailCustom"));
        return;
      }
      if (code === import_const.PayStatus.UserConfigError) {
        dispatch(
          (0, import_store.updateCustom)({
            failCustom: {
              isPosNetworkError: false,
              status: "fail",
              fail: import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.user.config.text"
              ),
              title: import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.user.config.title"
              ),
              warn: null
            }
          })
        );
        dispatch((0, import_store.updateComponent)("FailCustom"));
        return;
      }
      dispatch(
        (0, import_store.updateCustom)({
          errorStatus: "unknow"
          // unknow know
        })
      );
      dispatch((0, import_store.updateComponent)("UnknowFail"));
    },
    [dispatch]
  );
};
var useValidate = (check, num, onChange) => {
  const unloadRef = (0, import_react.useRef)(false);
  const dispatch = (0, import_store.useDispatch)();
  const fail = useFail();
  const failRef = (0, import_react.useRef)(fail);
  const ref = (0, import_react.useRef)();
  const { custom } = (0, import_store.useContextData)();
  const { netRef, payRef, numRef, modeRef, clientRef } = (0, import_hooks.useStoreRef)();
  const stepRef = (0, import_react.useRef)(custom == null ? void 0 : custom.step);
  const listRef = (0, import_react.useRef)(custom == null ? void 0 : custom.list);
  (0, import_react.useEffect)(() => {
    listRef.current = custom == null ? void 0 : custom.list;
  }, [custom == null ? void 0 : custom.list]);
  (0, import_react.useEffect)(() => {
    stepRef.current = custom == null ? void 0 : custom.step;
  }, [custom == null ? void 0 : custom.step]);
  const watchRef = (0, import_react.useRef)();
  const run = (0, import_react.useCallback)(
    (timeout) => {
      var _a, _b, _c;
      if (timeout === -1) {
        console.log("无限加载");
      } else {
        console.log("计时加载 ", typeof timeout === "number" ? timeout : num);
      }
      if (unloadRef.current) {
        (_a = ref.current) == null ? void 0 : _a.close();
        return;
      }
      if (!watchRef.current || !netRef.current) {
        return;
      }
      (_b = ref.current) == null ? void 0 : _b.close();
      ref.current = new import_timer.default({
        xhr: check,
        timeout: typeof timeout === "number" ? timeout : num,
        callback: watchRef.current
      });
      (_c = ref.current) == null ? void 0 : _c.run({ number: numRef.current }).then((res) => {
        if (unloadRef.current) {
          return;
        }
        if (!netRef.current) {
          return;
        }
        if (!res || Number(res.code) !== 200) {
          return Promise.reject(res);
        }
      }).catch((res) => {
        var _a2;
        if (unloadRef.current) {
          return;
        }
        if (!netRef.current) {
          return;
        }
        if (res && res.code === -1) {
          return;
        }
        (_a2 = failRef.current) == null ? void 0 : _a2.call(
          failRef,
          res,
          stepRef.current >= import_const2.StepStatusEnum.Account
        );
      });
    },
    [check, num]
  );
  (0, import_react.useEffect)(() => {
    watchRef.current = (res, isRun) => {
      var _a, _b, _c, _d, _e, _f;
      if (unloadRef.current) {
        (_a = ref.current) == null ? void 0 : _a.close();
        return;
      }
      if (!res || !res.data || !res.data.txn_status_id) {
        (_b = ref.current) == null ? void 0 : _b.close();
      }
      const [txn_status_id, status_id, complete] = [
        Number(res.data.txn_status_id),
        Number(res.data.status_id),
        Number(res.data.complete)
      ];
      if (txn_status_id === import_const2.StepStatusEnum.Wait && status_id === 6 && complete === 1) {
        (_c = ref.current) == null ? void 0 : _c.close();
        if (stepRef.current !== txn_status_id && listRef.current.every(({ index }) => txn_status_id !== index)) {
          const current = listRef.current.map((item) => {
            if (Number(item == null ? void 0 : item.index) < Number(stepRef.current)) {
              return {
                ...item,
                status: "resolve"
              };
            }
            return item;
          });
          const nextStep = (0, import_const2.getStepMapping)(txn_status_id, {
            money: (_d = payRef.current) == null ? void 0 : _d.totalUnit,
            mode: modeRef.current
          });
          if (nextStep) {
            current.push(nextStep);
          }
          dispatch((0, import_store.updateCustom)({ list: current, step: txn_status_id }));
        }
        onChange(res.data);
        return;
      }
      if (stepRef.current !== txn_status_id && listRef.current.every(({ index }) => txn_status_id !== index)) {
        console.log(
          "self.flag  stepRef.current, txn_status_id ",
          stepRef.current,
          txn_status_id
        );
        stepRef.current = txn_status_id;
        (_e = ref.current) == null ? void 0 : _e.close();
        const current = listRef.current.map((item) => {
          if (Number(item == null ? void 0 : item.index) < Number(stepRef.current)) {
            return {
              ...item,
              status: "resolve"
            };
          }
          return item;
        });
        const nextStep = (0, import_const2.getStepMapping)(txn_status_id, {
          money: (_f = payRef.current) == null ? void 0 : _f.totalUnit,
          mode: modeRef.current
        });
        if (nextStep) {
          current.push(nextStep);
          if (nextStep.type === import_const2.StemTypeEnum.Passive) {
            dispatch((0, import_store.updateStatus)(import_const.StatusEnum.Question));
          }
          if (nextStep.index === import_const2.StepStatusEnum.Receipt) {
            dispatch(
              (0, import_store.updateState)({
                title: import_utils.locales.getText(
                  "page.eftpos-pay.text.waiting.signature"
                )
              })
            );
          }
        }
        dispatch((0, import_store.updateCustom)({ list: current, step: txn_status_id }));
        txn_status_id === import_const2.StepStatusEnum.Receipt ? run(-1) : run();
        return;
      }
      if (isRun) {
        run();
      }
    };
  }, [dispatch, onChange, run]);
  (0, import_react.useEffect)(
    () => () => {
      var _a;
      (_a = ref.current) == null ? void 0 : _a.close();
      unloadRef.current = true;
    },
    []
  );
  return [run, watchRef, ref];
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useFail,
  useValidate
});
