import { C as p, a as c, a9 as m } from "./index-162fd1aa.mjs";
import { P as d } from "./PendingOrdersAppManager-4782fef4.mjs";
class f extends p {
  constructor(n) {
    super(), this.orderExpiredTimeout = async () => {
      const { order: t } = this.state;
      if (!t || !t.expireTime)
        return;
      const e = new Date().getTime(), s = new Date(t.expireTime).getTime() - e;
      setTimeout(() => {
        this.setState({ orderIsExpired: !0 });
      }, s);
    }, this.fetchOrder = async (t) => {
      const { userId: e } = this.props;
      try {
        if (!e || !t)
          return;
        const i = await this.sdk.Platform.Order().getOrderByOrderNo({ userId: e, orderNo: t }).then((s) => {
          if (s.error)
            throw s.error;
          return s.response.data;
        });
        this.setState({ order: i });
      } catch (i) {
        this.setState({ error: i });
      }
    }, this.cancelAllOrders = () => {
      var t;
      return (t = this.pendingOrdersAppManager) == null ? void 0 : t.cancelAll();
    }, this.props = n, this.state = {
      isFetching: !1,
      error: null,
      order: null,
      orderIsExpired: !1,
      item: null,
      ...d.DEFAULT_STATE
    }, this.sdk = c.getAppState().getSdk();
  }
  async init() {
    const { userId: n, orderNo: t } = this.props;
    try {
      if (this.state.isFetching)
        return;
      this.setState({
        isFetching: !0,
        error: null,
        order: null
      });
      const e = await this.sdk.Platform.Order().getOrderByOrderNo({ userId: n, orderNo: t }).then((r) => {
        if (r.error)
          throw r.error;
        return r.response.data;
      }), i = await this.sdk.Platform.Item().getItemsByItemIds({
        queryParams: { itemIds: e == null ? void 0 : e.itemId }
      }).then((r) => {
        if (r.error)
          throw r.error;
        const [a] = r.response.data;
        return a;
      });
      this.pendingOrdersAppManager = new d(this.sdk, {
        userId: this.props.userId,
        itemId: e.itemId
      }), this.pendingOrdersAppManager.subscribe(() => {
        const r = Object.keys(d.DEFAULT_STATE).reduce(
          (a, o) => {
            var h;
            return a[o] = (h = this.pendingOrdersAppManager) == null ? void 0 : h.state[o], a;
          },
          {}
        );
        this.setState(r);
      }), await this.pendingOrdersAppManager.init();
      const { fetchOrdersError: s } = this.pendingOrdersAppManager.state;
      if (s)
        throw s;
      await this.setState({ order: e, item: i });
    } catch (e) {
      this.setState({ error: e });
    } finally {
      await this.setState({ isFetching: !1 }), this.state.order && this.state.order.status === m.enum.INIT && this.orderExpiredTimeout();
    }
  }
}
export {
  f as O
};
