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/plus/saleDetail/components/Client/ClientSelector.tsx
var ClientSelector_exports = {};
__export(ClientSelector_exports, {
  ClientSelector: () => ClientSelector
});
module.exports = __toCommonJS(ClientSelector_exports);
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_ahooks = require("ahooks");
var import_antd = require("antd");
var import_classnames = __toESM(require("classnames"));
var import_react = __toESM(require("react"));
var import_clientCard = __toESM(require("../../../clientCard"));
var import_clinetSearch = __toESM(require("../../../clinetSearch"));
var import_utils2 = require("../../../clientName/utils");
var import_compensatedPisellContainer = __toESM(require("../../../../pro/compensatedPisellContainer"));
function getErrorMessage(error) {
  if (error instanceof Error) return error.message;
  return String(error || "");
}
function getCustomerId(customer) {
  return (customer == null ? void 0 : customer.id) ?? (customer == null ? void 0 : customer.customer_id);
}
function isWalkInCustomer(customer) {
  const id = getCustomerId(customer);
  if (id === void 0 || id === null) return true;
  if (typeof id === "string") return ["", "0", "1"].includes(id);
  return [0, 1].includes(id);
}
function normalizeCustomer(customer) {
  if (!customer) return void 0;
  const displayName = customer.display_name || customer.name || [customer.first_name, customer.last_name].filter(Boolean).join(" ");
  return {
    ...customer,
    customer_id: getCustomerId(customer),
    name: customer.name || displayName,
    display_name: displayName,
    nickname: customer.nickname || displayName
  };
}
function extractContactsInfo(customer) {
  const contactsInfo = customer == null ? void 0 : customer.contacts_info;
  if (!contactsInfo) return null;
  return contactsInfo.value || contactsInfo;
}
var ClientSelector = (0, import_react.forwardRef)(
  ({
    className,
    value,
    list = [],
    loading = false,
    loadingMore = false,
    resultLoading,
    hasMore = false,
    pagination,
    isShowAvatar,
    disabledSwitch,
    disabledSwitchText,
    clientCardProps,
    beforeSwitchModalOpen,
    variant,
    onSearch,
    onLoadMore,
    onChangePage,
    onSelect,
    onAddToFirst,
    onClientChange,
    resolveContactsInfo,
    onContactsInfoChange,
    onOpenCustomerDetail
  }, ref) => {
    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 [keyword, setKeyword] = (0, import_react.useState)("");
    const Toast = (0, import_materials.useToast)();
    const currentVariant = variant || "desktop";
    const isPhoneVariant = currentVariant === "phone";
    const selectedCustomer = value || null;
    const customer = (0, import_react.useMemo)(
      () => normalizeCustomer(selectedCustomer),
      [selectedCustomer]
    );
    const refreshClientList = (0, import_ahooks.useMemoizedFn)(async (nextKeyword) => {
      var _a, _b, _c;
      try {
        await onSearch(nextKeyword, { showLoading: false });
        (_b = (_a = clientSearchRef.current) == null ? void 0 : _a.resetScrollPosition) == null ? void 0 : _b.call(_a);
      } catch (error) {
        console.error("[ClientSelector] refresh customer list failed:", error);
        (_c = Toast == null ? void 0 : Toast.error) == null ? void 0 : _c.call(Toast, getErrorMessage(error));
      }
    });
    const handleSearchClient = (0, import_ahooks.useMemoizedFn)(async (nextKeyword) => {
      var _a, _b, _c;
      try {
        await onSearch(nextKeyword, { showLoading: true });
        (_b = (_a = clientSearchRef.current) == null ? void 0 : _a.resetScrollPosition) == null ? void 0 : _b.call(_a);
      } catch (error) {
        console.error("[ClientSelector] search customer failed:", error);
        (_c = Toast == null ? void 0 : Toast.error) == null ? void 0 : _c.call(Toast, getErrorMessage(error));
      }
    });
    const debouncedSearch = (0, import_ahooks.useDebounceFn)(
      async (nextKeyword) => {
        await refreshClientList(nextKeyword);
      },
      { wait: 500 }
    );
    (0, import_react.useEffect)(() => {
      debouncedSearch.run(keyword);
    }, [keyword]);
    (0, import_react.useEffect)(() => {
      if (searchModalVisible) return;
      if (keyword) setKeyword("");
    }, [searchModalVisible, keyword]);
    const showDisabledSwitchTip = (0, import_ahooks.useMemoizedFn)(() => {
      var _a;
      (_a = Toast == null ? void 0 : Toast.info) == null ? void 0 : _a.call(
        Toast,
        disabledSwitchText || import_utils.locales.getText("pisell2.checkout.client-card.tip.partially-paid")
      );
    });
    const openSearchModal = (0, import_ahooks.useMemoizedFn)(() => {
      if (disabledSwitch) {
        showDisabledSwitchTip();
        return;
      }
      setSearchModalVisible(true);
    });
    const closeSearchModal = (0, import_ahooks.useMemoizedFn)(() => {
      setSearchModalVisible(false);
    });
    const applySelectedClient = (0, import_ahooks.useMemoizedFn)(
      async (record) => {
        const originCustomer = selectedCustomer;
        await onSelect(record, originCustomer);
        onContactsInfoChange == null ? void 0 : onContactsInfoChange(
          resolveContactsInfo ? resolveContactsInfo(record) : extractContactsInfo(record)
        );
        onClientChange == null ? void 0 : onClientChange(record, originCustomer);
        setSearchModalVisible(false);
      }
    );
    const handleSetClient = (0, import_ahooks.useMemoizedFn)(
      async (record, options) => {
        var _a, _b;
        if (disabledSwitch) {
          showDisabledSwitchTip();
          return;
        }
        if (isWalkInCustomer(selectedCustomer)) {
          await applySelectedClient(record);
          if (record) {
            (_a = Toast == null ? void 0 : Toast.success) == null ? void 0 : _a.call(Toast, import_utils.locales.getText("pisell2.text.add-client-success"));
          }
          return;
        }
        if (String(getCustomerId(selectedCustomer)) === String(getCustomerId(record))) {
          if (options == null ? void 0 : options.sameClientTip) (_b = Toast == null ? void 0 : Toast.info) == null ? void 0 : _b.call(Toast, options.sameClientTip);
          setSearchModalVisible(false);
          return;
        }
        if (beforeSwitchModalOpen) {
          try {
            const shouldContinue = await beforeSwitchModalOpen();
            if (shouldContinue === false) return;
          } catch (error) {
            console.error("[ClientSelector] before switch callback failed:", error);
            return;
          }
        }
        setPendingCustomer(record);
        setSwitchModalVisible(true);
      }
    );
    const handleSelectClient = (0, import_ahooks.useMemoizedFn)((record) => {
      return handleSetClient(record);
    });
    const handleRemoveClient = (0, import_ahooks.useMemoizedFn)(() => {
      if (disabledSwitch) {
        showDisabledSwitchTip();
        return;
      }
      applySelectedClient(null);
    });
    const handleAddClientSuccess = (0, import_ahooks.useMemoizedFn)(
      (record, isChecked) => {
        onAddToFirst == null ? void 0 : onAddToFirst(record);
        if (isChecked) handleSetClient(record);
      }
    );
    const handleConfirmSwitch = (0, import_ahooks.useMemoizedFn)(async () => {
      if (pendingCustomer) await applySelectedClient(pendingCustomer);
      setSwitchModalVisible(false);
      setPendingCustomer(null);
    });
    const handleCancelSwitch = (0, import_ahooks.useMemoizedFn)(() => {
      setSwitchModalVisible(false);
      setPendingCustomer(null);
    });
    const handleLoadMore = (0, import_ahooks.useMemoizedFn)(async () => {
      var _a;
      try {
        await (onLoadMore == null ? void 0 : onLoadMore());
      } catch (error) {
        console.error("[ClientSelector] load more customers failed:", error);
        (_a = Toast == null ? void 0 : Toast.error) == null ? void 0 : _a.call(Toast, getErrorMessage(error));
      }
    });
    const handleChangePage = (0, import_ahooks.useMemoizedFn)(async (nextPagination) => {
      var _a;
      try {
        await (onChangePage == null ? void 0 : onChangePage(nextPagination.current, nextPagination.pageSize));
      } catch (error) {
        console.error("[ClientSelector] change customer page failed:", error);
        (_a = Toast == null ? void 0 : Toast.error) == null ? void 0 : _a.call(Toast, getErrorMessage(error));
      }
    });
    const handleViewClient = (0, import_ahooks.useMemoizedFn)((record) => {
      if (!onOpenCustomerDetail || !getCustomerId(record)) return;
      const originContactsInfo = record.contacts_info || null;
      onOpenCustomerDetail(record, (detail) => {
        const nextContactsInfo = (detail == null ? void 0 : detail.contacts_info) || null;
        const displayName = (detail == null ? void 0 : detail.display_name) || record.display_name || "";
        const nextCustomer = {
          ...record,
          display_name: displayName,
          name: (detail == null ? void 0 : detail.name) || record.name || displayName,
          email: (detail == null ? void 0 : detail.email) || "",
          phone: (detail == null ? void 0 : detail.phone) || "",
          nickname: (detail == null ? void 0 : detail.nickname) || displayName,
          country_calling_code: (detail == null ? void 0 : detail.country_calling_code) || "",
          first_name: (detail == null ? void 0 : detail.first_name) || "",
          last_name: (detail == null ? void 0 : detail.last_name) || "",
          contacts_info: nextContactsInfo
        };
        void onSelect(nextCustomer, selectedCustomer);
        onClientChange == null ? void 0 : onClientChange(nextCustomer, selectedCustomer);
        if (JSON.stringify(originContactsInfo) !== JSON.stringify(nextContactsInfo)) {
          onContactsInfoChange == null ? void 0 : onContactsInfoChange(nextContactsInfo);
        }
        void handleSearchClient("");
      });
    });
    const defaultDropdownProps = (0, import_react.useMemo)(
      () => ({
        buttonProps: {
          icon: /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-sale-detail-client__switch-icon" }, /* @__PURE__ */ import_react.default.createElement(import_materials.Iconfont, { type: "pisell2-switch-horizontal-01", size: 24 })),
          size: "default",
          onClick: () => {
          }
        }
      }),
      []
    );
    const resultProps = (0, import_react.useMemo)(
      () => ({
        loading,
        onChange: handleChangePage,
        pagination: {
          pageSize: (pagination == null ? void 0 : pagination.pageSize) || 20,
          current: (pagination == null ? void 0 : pagination.page) || 1,
          total: (pagination == null ? void 0 : pagination.total) || 0,
          size: "default",
          showSizeChanger: false
        }
      }),
      [loading, pagination, handleChangePage]
    );
    (0, import_react.useImperativeHandle)(ref, () => ({
      handleSetClient
    }));
    return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
      "section",
      {
        className: (0, import_classnames.default)(
          "pisell-sale-detail-client",
          `pisell-sale-detail-client--${currentVariant}`,
          className
        )
      },
      /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-sale-detail-client__line" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-sale-detail-client__card-wrap" }, /* @__PURE__ */ import_react.default.createElement(
        import_clientCard.default,
        {
          dataSource: customer,
          onAddClient: openSearchModal,
          onChangeClient: openSearchModal,
          onRemoveClient: handleRemoveClient,
          onViewClient: handleViewClient,
          style: {
            border: "solid",
            borderColor: "#D0D5DD",
            borderWidth: "1px",
            display: "flex",
            boxSizing: "border-box",
            height: "auto",
            ...(clientCardProps == null ? void 0 : clientCardProps.style) || {}
          },
          isShowAvatar: Boolean(isShowAvatar),
          dropdown: (clientCardProps == null ? void 0 : clientCardProps.dropdown) || defaultDropdownProps,
          avatar: {
            size: "lg",
            useTextAvatar: true,
            ...(clientCardProps == null ? void 0 : clientCardProps.avatar) || {}
          },
          tag: clientCardProps == null ? void 0 : clientCardProps.tag,
          tags: clientCardProps == null ? void 0 : clientCardProps.tags
        }
      )))
    ), /* @__PURE__ */ import_react.default.createElement(
      import_clinetSearch.default,
      {
        ref: clientSearchRef,
        loading,
        dataSource: list,
        onSearch: handleSearchClient,
        keyword,
        onKeywordChange: setKeyword,
        onRowClick: handleSelectClient,
        containerProps: {
          open: searchModalVisible,
          onCancel: closeSearchModal,
          destroyOnClose: true,
          width: 880
        },
        isShowNewButton: false,
        resultProps,
        onAddClient: handleAddClientSuccess,
        onLoadMore: handleLoadMore,
        hasMore,
        resultLoading: resultLoading ?? loadingMore
      }
    ), /* @__PURE__ */ import_react.default.createElement(
      import_compensatedPisellContainer.default,
      {
        renderType: isPhoneVariant ? "drawer" : "modal",
        showHandlerBar: isPhoneVariant,
        props: isPhoneVariant ? {
          className: "cart-client-card_switch-modal",
          open: switchModalVisible,
          placement: "bottom",
          width: "100%",
          height: "auto",
          onClose: handleCancelSwitch,
          closable: false,
          title: null,
          destroyOnClose: true,
          bodyStyle: {
            padding: 0
          },
          footer: /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              style: {
                display: "flex",
                gap: 12,
                paddingBottom: "calc(12px + env(safe-area-inset-bottom))"
              }
            },
            /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { style: { flex: 1 }, onClick: handleCancelSwitch }, import_utils.locales.getText("pisell2.text.cancel")),
            /* @__PURE__ */ import_react.default.createElement(
              import_antd.Button,
              {
                style: { flex: 1 },
                type: "primary",
                onClick: handleConfirmSwitch
              },
              import_utils.locales.getText("pisell2.text.switch-account")
            )
          )
        } : {
          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,
            padding: variant === "phone" ? "16px 0" : "16px 0 0"
          }
        },
        import_utils.locales.getText("pisell2.text.cart-client-card")(
          (0, import_utils2.getClientName)(pendingCustomer)
        )
      )
    ));
  }
);
ClientSelector.displayName = "ClientSelector";
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ClientSelector
});
