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/booking/info2/cartClientCard/index.tsx
var cartClientCard_exports = {};
__export(cartClientCard_exports, {
  default: () => cartClientCard_default
});
module.exports = __toCommonJS(cartClientCard_exports);
var import_react = __toESM(require("react"));
var import_ahooks = require("ahooks");
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_locales = __toESM(require("./locales"));
var import_clientCard = __toESM(require("../../../../plus/clientCard"));
var import_clinetSearch = __toESM(require("../../../../plus/clinetSearch"));
var import_useCustomer = require("../../../../components/ticketBooking/hooks/pisellos/useCustomer");
var import_utils2 = require("../../../../components/booking/utils");
var import_useScanCustomer = __toESM(require("../../../../components/ticketBooking/hooks/pisellos/useScanCustomer"));
var import_utils3 = require("./utils");
var import_utils4 = require("../../../../plus/clientName/utils");
var import_useTranslationOriginal = __toESM(require("../../../../hooks/useTranslationOriginal"));
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_model = require("../../info/model");
var import_index = require("./index.less");
var CartClientCard = (0, import_react.forwardRef)(({
  clientCardProps = {},
  beforeSwitchModalOpen,
  onClientChange
}, ref) => {
  var _a, _b, _c, _d;
  const clientSearchRef = (0, import_react.useRef)(null);
  const [searchModalVisible, setSearchModalVisible] = (0, import_react.useState)(false);
  const [switchModalVisible, setSwitchModalVisible] = (0, import_react.useState)(false);
  const [pendingCustomer, setPendingCustomer] = (0, import_react.useState)(
    null
  );
  const { state, dispatch } = (0, import_react.useContext)(import_model.Context);
  const translationOriginal = (0, import_useTranslationOriginal.default)();
  const [keyword, setKeyword] = (0, import_react.useState)("");
  const keywordRef = (0, import_react.useRef)("");
  keywordRef.current = keyword;
  const Toast = (0, import_materials.useToast)();
  const { openScan, closeScan } = (0, import_useScanCustomer.default)();
  const context = (0, import_useEngineContext.default)();
  import_utils.locales.init(
    import_locales.default,
    ((_c = (_b = (_a = context.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.storage) == null ? void 0 : _c.get("umi_locale")) || "en"
  );
  const changeCustomerToGlobalState = (0, import_ahooks.useMemoizedFn)((value) => {
    dispatch({
      type: "setClient",
      payload: {
        value,
        edit: true
      }
    });
  });
  const {
    customers,
    loading,
    pagination,
    changePage,
    selectCustomer,
    addCustomerToFirst,
    initLoad,
    hasMore,
    loadMore
  } = (0, import_useCustomer.useCustomer)({
    changeCustomerToGlobalState
  });
  const selectedCustomer = (_d = state.client) == null ? void 0 : _d.value;
  const handleSearchClient = async (keyword2) => {
    var _a2, _b2;
    await initLoad(keyword2);
    (_b2 = (_a2 = clientSearchRef.current) == null ? void 0 : _a2.resetScrollPosition) == null ? void 0 : _b2.call(_a2);
  };
  const _debouncedSearch = (0, import_ahooks.useDebounceFn)(
    async (_keyword) => {
      var _a2, _b2;
      await initLoad(keyword);
      (_b2 = (_a2 = clientSearchRef.current) == null ? void 0 : _a2.resetScrollPosition) == null ? void 0 : _b2.call(_a2);
    },
    { wait: 500 }
  );
  (0, import_react.useEffect)(() => {
    _debouncedSearch.run(keyword);
  }, [keyword]);
  (0, import_react.useEffect)(() => {
    if (state.action) {
      state.action({
        type: "pisell1.registerPlugin",
        data: {
          pluginList: ["CustomerDetailPlugin"]
        }
      });
    }
  }, []);
  const handleScanCustomer = (customer) => {
    if (customer == null ? void 0 : customer.scanCode) {
      setKeyword(customer.scanCode);
    }
  };
  (0, import_react.useEffect)(() => {
    if (searchModalVisible) {
      openScan(handleScanCustomer);
    } else {
      closeScan();
      if (keywordRef.current) {
        setKeyword("");
      }
    }
  }, [searchModalVisible, initLoad]);
  const handleAddClient = () => {
    setSearchModalVisible(true);
  };
  const handleChangeClient = (data) => {
    setSearchModalVisible(true);
  };
  const handleRemoveClient = (data) => {
    selectCustomer(null);
  };
  const handleViewClient = (data) => {
    state.action({
      type: "pisell1.handleOpenCustomerModal",
      data: { id: state.client.value.id },
      callback: (data2) => {
      }
    });
  };
  const handleModalCancel = () => {
    setSearchModalVisible(false);
  };
  const handleAddClientSuccess = (record, isChecked) => {
    addCustomerToFirst(record);
    if (isChecked) {
      selectCustomer(record);
      setSearchModalVisible(false);
    }
  };
  const resultProps = (0, import_react.useMemo)(() => {
    return {
      loading,
      onChange: (pagination2) => {
        changePage(pagination2.current, pagination2.pageSize);
      },
      pagination: {
        pageSize: pagination.pageSize,
        current: pagination.page,
        total: pagination.total,
        size: "default",
        showSizeChanger: false
      }
    };
  }, [pagination, loading]);
  const handleSetClient = (0, import_ahooks.useMemoizedFn)(async (record, options) => {
    var _a2, _b2, _c2, _d2, _e;
    if ((0, import_utils2.isWalkIn)(selectedCustomer == null ? void 0 : selectedCustomer.id) && ((_a2 = options == null ? void 0 : options.fullData) == null ? void 0 : _a2.searchType) === "walletPass" && ((_b2 = options == null ? void 0 : options.fullData) == null ? void 0 : _b2.scanCode)) {
      window.dispatchEvent(
        new CustomEvent("onScanWallPassCode", {
          detail: {
            code: (_c2 = options == null ? void 0 : options.fullData) == null ? void 0 : _c2.scanCode
          }
        })
      );
      return;
    }
    if ((0, import_utils2.isWalkIn)(selectedCustomer == null ? void 0 : selectedCustomer.id)) {
      selectCustomer(record);
      setSearchModalVisible(false);
      (_d2 = Toast == null ? void 0 : Toast.success) == null ? void 0 : _d2.call(Toast, import_utils.locales.getText("pisell2.text.add-client-success"));
      return;
    }
    if ((selectedCustomer == null ? void 0 : selectedCustomer.id) === (record == null ? void 0 : record.id)) {
      if (options == null ? void 0 : options.sameClientTip) {
        (_e = Toast == null ? void 0 : Toast.info) == null ? void 0 : _e.call(Toast, options.sameClientTip);
      }
      setSearchModalVisible(false);
      return;
    }
    if (beforeSwitchModalOpen) {
      try {
        const shouldContinue = await beforeSwitchModalOpen();
        if (shouldContinue === false) {
          return;
        }
      } catch (error) {
        console.error("beforeSwitchModalOpen callback error:", error);
        return;
      }
    }
    setPendingCustomer(record);
    setSwitchModalVisible(true);
  });
  const handleConfirmSwitch = () => {
    if (pendingCustomer) {
      selectCustomer(pendingCustomer);
    }
    setSwitchModalVisible(false);
    setPendingCustomer(null);
    setSearchModalVisible(false);
    onClientChange == null ? void 0 : onClientChange(pendingCustomer);
  };
  const handleCancelSwitch = () => {
    setSwitchModalVisible(false);
    setPendingCustomer(null);
  };
  (0, import_react.useMemo)(() => {
    (0, import_utils3.setHandleSetClient)(handleSetClient);
  }, []);
  (0, import_react.useEffect)(() => {
    return () => {
      (0, import_utils3.setHandleSetClient)(null);
    };
  }, []);
  const tags = (0, import_react.useMemo)(() => {
    var _a2;
    if (!selectedCustomer) return;
    const { latest_wallet_detail } = selectedCustomer;
    const _name = (_a2 = latest_wallet_detail == null ? void 0 : latest_wallet_detail.wallet) == null ? void 0 : _a2.name;
    if (_name) {
      return [{ children: translationOriginal(_name), color: "gold" }];
    }
  }, [selectedCustomer]);
  (0, import_react.useImperativeHandle)(ref, () => ({
    handleSetClient
  }));
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
    import_clientCard.default,
    {
      dataSource: selectedCustomer,
      onAddClient: handleAddClient,
      onChangeClient: handleChangeClient,
      onRemoveClient: handleRemoveClient,
      onViewClient: handleViewClient,
      style: {
        border: "solid",
        borderColor: "#D0D5DD",
        borderWidth: "1px",
        minHeight: 64,
        display: "flex",
        boxSizing: "border-box",
        height: 64,
        ...clientCardProps.style || {}
      },
      avatar: {
        size: "lg",
        useTextAvatar: !(selectedCustomer == null ? void 0 : selectedCustomer.cover),
        ...clientCardProps.avatar || {}
      },
      tag: {
        placement: "inline"
      },
      tags,
      dropdown: clientCardProps.dropdown
    }
  ), /* @__PURE__ */ import_react.default.createElement(
    import_clinetSearch.default,
    {
      ref: clientSearchRef,
      loading,
      dataSource: customers,
      onSearch: handleSearchClient,
      keyword,
      onKeywordChange: (_keyword) => {
        setKeyword(_keyword);
      },
      onRowClick: handleSetClient,
      containerProps: {
        open: searchModalVisible,
        onCancel: handleModalCancel,
        // 同时存在两个搜索弹窗时，内部的无限滚动组件会发生冲突
        destroyOnClose: true
      },
      isShowNewButton: false,
      resultProps,
      onAddClient: handleAddClientSuccess,
      onLoadMore: loadMore,
      hasMore
    }
  ), /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellModal,
    {
      className: "cart-client-card_switch-modal",
      open: switchModalVisible,
      okText: import_utils.locales.getText("pisell2.text.switch-account"),
      cancelText: import_utils.locales.getText("pisell2.text.cancel"),
      onOk: handleConfirmSwitch,
      onCancel: handleCancelSwitch,
      closable: false,
      header: null,
      footerDivider: false,
      destroyOnClose: true
    },
    /* @__PURE__ */ import_react.default.createElement("div", { style: { textAlign: "center", fontWeight: 600, paddingTop: 24 } }, import_utils.locales.getText("pisell2.text.cart-client-card")(
      (0, import_utils4.getClientName)(pendingCustomer)
    ))
  ));
});
var cartClientCard_default = CartClientCard;
