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"));
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_utils3 = require("./utils");
var import_serve = require("./serve");
var import_ClientSelector = require("./ClientSelector.less");
var ModalButton = import_antd.Button;
function getErrorMessage(error) {
  if (error instanceof Error) return error.message;
  return String(error || "");
}
function getValidFranchiseeCustomerId(record) {
  const franchiseeCustomerId = record == null ? void 0 : record.franchisee_customer_id;
  if (typeof franchiseeCustomerId === "number" && franchiseeCustomerId !== 0) {
    return franchiseeCustomerId;
  }
  return void 0;
}
var ClientSelector = (0, import_react.memo)(
  (0, import_react.forwardRef)(
    ({
      className,
      value,
      list = [],
      loading = false,
      loadingMore = false,
      resultLoading,
      hasMore = false,
      pagination,
      isShowAvatar,
      showClientCard = true,
      readOnly = false,
      clientCardProps,
      beforeSwitchModalOpen,
      variant,
      onSearch,
      onLoadMore,
      onChangePage,
      onSelect,
      onAddToFirst,
      onClientChange,
      resolveContactsInfo,
      onContactsInfoChange,
      onOpenCustomerDetail
    }, ref) => {
      var _a, _b, _c, _d;
      const context = (0, import_useEngineContext.default)();
      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 [selectingCustomerId, setSelectingCustomerId] = (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 isFranchisee = Boolean(
        (_d = (_c = (_b = (_a = context.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.businessUtils) == null ? void 0 : _c.getAppByModal) == null ? void 0 : _d.call(_c, "franchisee")
      );
      const selectedCustomer = value || null;
      const isSelectingClient = selectingCustomerId !== null;
      const clientList = (0, import_react.useMemo)(
        () => isFranchisee ? list.map((item) => ({
          ...item,
          id: item.franchisee_customer_id || item.id
        })) : list,
        [list, isFranchisee]
      );
      const customer = (0, import_react.useMemo)(
        () => (0, import_utils3.normalizeCustomer)(selectedCustomer),
        [selectedCustomer]
      );
      const refreshClientList = (0, import_ahooks.useMemoizedFn)(async (nextKeyword) => {
        var _a2, _b2, _c2;
        try {
          await onSearch(nextKeyword, { showLoading: false });
          (_b2 = (_a2 = clientSearchRef.current) == null ? void 0 : _a2.resetScrollPosition) == null ? void 0 : _b2.call(_a2);
        } catch (error) {
          console.error(
            "[ClientSelector] refresh customer list failed:",
            error
          );
          (_c2 = Toast == null ? void 0 : Toast.error) == null ? void 0 : _c2.call(Toast, getErrorMessage(error));
        }
      });
      const handleSearchClient = (0, import_ahooks.useMemoizedFn)(async (nextKeyword) => {
        var _a2, _b2, _c2;
        try {
          await onSearch(nextKeyword, { showLoading: true });
          (_b2 = (_a2 = clientSearchRef.current) == null ? void 0 : _a2.resetScrollPosition) == null ? void 0 : _b2.call(_a2);
        } catch (error) {
          console.error("[ClientSelector] search customer failed:", error);
          (_c2 = Toast == null ? void 0 : Toast.error) == null ? void 0 : _c2.call(Toast, getErrorMessage(error));
        }
      });
      const debouncedSearch = (0, import_ahooks.useDebounceFn)(
        async (nextKeyword) => {
          await refreshClientList(nextKeyword);
        },
        { wait: 500 }
      );
      const showDisabledSwitchTip = (0, import_ahooks.useMemoizedFn)(() => {
        var _a2;
        (_a2 = Toast == null ? void 0 : Toast.info) == null ? void 0 : _a2.call(
          Toast,
          import_utils.locales.getText("pisell2.checkout.client-card.tip.partially-paid")
        );
      });
      const openSearchModal = (0, import_ahooks.useMemoizedFn)(() => {
        if (readOnly) {
          showDisabledSwitchTip();
          return;
        }
        if (!searchModalVisible) {
          void handleSearchClient(keyword);
        }
        setSearchModalVisible(true);
      });
      const closeSearchModal = (0, import_ahooks.useMemoizedFn)(() => {
        if (isSelectingClient) return;
        debouncedSearch.cancel();
        if (keyword) setKeyword("");
        setSearchModalVisible(false);
      });
      const handleKeywordChange = (0, import_ahooks.useMemoizedFn)((nextKeyword) => {
        setKeyword(nextKeyword);
        if (searchModalVisible) {
          debouncedSearch.run(nextKeyword);
        }
      });
      const resolveSelectableClient = (0, import_ahooks.useMemoizedFn)(
        async (record) => {
          if (!record || !isFranchisee) {
            return {
              customer: record,
              shouldRefreshList: false
            };
          }
          const franchiseeCustomerId = getValidFranchiseeCustomerId(record);
          if (franchiseeCustomerId !== void 0) {
            return {
              customer: {
                ...record,
                id: franchiseeCustomerId
              },
              shouldRefreshList: false
            };
          }
          const franchisorCustomerId = record.id;
          if (!franchisorCustomerId) {
            throw new Error(
              "[ClientSelector] franchisee customer id is missing"
            );
          }
          const franchiseeCustomer = await (0, import_serve.getFranchiseeCustomerInfo)({
            franchisor_customer_id: franchisorCustomerId
          });
          if (!(franchiseeCustomer == null ? void 0 : franchiseeCustomer.franchisee_customer_id)) {
            throw new Error("[ClientSelector] franchisee customer sync failed");
          }
          return {
            customer: {
              ...record,
              id: franchiseeCustomer.franchisee_customer_id
            },
            shouldRefreshList: true
          };
        }
      );
      const applySelectedClient = (0, import_ahooks.useMemoizedFn)(
        async (record) => {
          const originCustomer = selectedCustomer;
          const currentKeyword = keyword;
          const { customer: nextRecord, shouldRefreshList } = await resolveSelectableClient(record);
          await onSelect(nextRecord, originCustomer);
          onContactsInfoChange == null ? void 0 : onContactsInfoChange(
            resolveContactsInfo ? resolveContactsInfo(nextRecord) : (0, import_utils3.extractContactsInfo)(nextRecord)
          );
          await (onClientChange == null ? void 0 : onClientChange(nextRecord, originCustomer));
          setSearchModalVisible(false);
          if (shouldRefreshList) {
            await refreshClientList(currentKeyword);
          }
        }
      );
      const applySelectedClientWithLoading = (0, import_ahooks.useMemoizedFn)(
        async (record) => {
          var _a2;
          const nextCustomerId = (0, import_utils3.getCustomerId)(record);
          if (nextCustomerId !== void 0 && nextCustomerId !== null) {
            setSelectingCustomerId(nextCustomerId);
          }
          try {
            await applySelectedClient(record);
            return true;
          } catch (error) {
            console.error("[ClientSelector] select customer failed:", error);
            (_a2 = Toast == null ? void 0 : Toast.error) == null ? void 0 : _a2.call(Toast, getErrorMessage(error));
            return false;
          } finally {
            setSelectingCustomerId(null);
          }
        }
      );
      const handleSetClient = (0, import_ahooks.useMemoizedFn)(
        async (originalRecord, options) => {
          var _a2, _b2;
          if (readOnly) {
            showDisabledSwitchTip();
            return;
          }
          const record = originalRecord;
          if ((0, import_utils3.isWalkInCustomer)(selectedCustomer)) {
            const switched = await applySelectedClientWithLoading(record);
            if (switched && record) {
              (_a2 = Toast == null ? void 0 : Toast.success) == null ? void 0 : _a2.call(
                Toast,
                import_utils.locales.getText("pisell2.text.add-client-success")
              );
            }
            return;
          }
          const selectedCustomerId = isFranchisee ? getValidFranchiseeCustomerId(selectedCustomer) ?? (0, import_utils3.getCustomerId)(selectedCustomer) : (0, import_utils3.getCustomerId)(selectedCustomer);
          const recordCustomerId = isFranchisee ? getValidFranchiseeCustomerId(record) ?? (0, import_utils3.getCustomerId)(record) : (0, import_utils3.getCustomerId)(record);
          if (String(selectedCustomerId) === String(recordCustomerId)) {
            if (options == null ? void 0 : options.sameClientTip) (_b2 = Toast == null ? void 0 : Toast.info) == null ? void 0 : _b2.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 (readOnly) {
          showDisabledSwitchTip();
          return;
        }
        void 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 () => {
        const switched = pendingCustomer ? await applySelectedClientWithLoading(pendingCustomer) : true;
        if (!switched) return;
        setSwitchModalVisible(false);
        setPendingCustomer(null);
      });
      const handleCancelSwitch = (0, import_ahooks.useMemoizedFn)(() => {
        if (isSelectingClient) return;
        setSwitchModalVisible(false);
        setPendingCustomer(null);
      });
      const handleLoadMore = (0, import_ahooks.useMemoizedFn)(async () => {
        var _a2;
        try {
          await (onLoadMore == null ? void 0 : onLoadMore());
        } catch (error) {
          console.error("[ClientSelector] load more customers failed:", error);
          (_a2 = Toast == null ? void 0 : Toast.error) == null ? void 0 : _a2.call(Toast, getErrorMessage(error));
        }
      });
      const handleChangePage = (0, import_ahooks.useMemoizedFn)(async (nextPagination) => {
        var _a2;
        try {
          await (onChangePage == null ? void 0 : onChangePage(nextPagination.current, nextPagination.pageSize));
        } catch (error) {
          console.error("[ClientSelector] change customer page failed:", error);
          (_a2 = Toast == null ? void 0 : Toast.error) == null ? void 0 : _a2.call(Toast, getErrorMessage(error));
        }
      });
      const handleViewClient = (0, import_ahooks.useMemoizedFn)(
        (record) => {
          if (!onOpenCustomerDetail || !(0, import_utils3.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 resolvedClientCardProps = (0, import_react.useMemo)(() => {
        var _a2, _b2, _c2;
        if (!readOnly) return clientCardProps;
        return {
          ...clientCardProps,
          dropdown: {
            ...clientCardProps == null ? void 0 : clientCardProps.dropdown,
            buttonProps: {
              ...(_a2 = clientCardProps == null ? void 0 : clientCardProps.dropdown) == null ? void 0 : _a2.buttonProps,
              style: {
                ...(_c2 = (_b2 = clientCardProps == null ? void 0 : clientCardProps.dropdown) == null ? void 0 : _b2.buttonProps) == null ? void 0 : _c2.style,
                display: "none"
              }
            }
          }
        };
      }, [clientCardProps, readOnly]);
      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]
      );
      const clientCardStyle = (0, import_react.useMemo)(
        () => ({
          border: "solid",
          borderColor: "#D0D5DD",
          borderWidth: "1px",
          display: "flex",
          boxSizing: "border-box",
          height: "auto",
          ...(resolvedClientCardProps == null ? void 0 : resolvedClientCardProps.style) || {}
        }),
        [resolvedClientCardProps == null ? void 0 : resolvedClientCardProps.style]
      );
      const clientCardAvatar = (0, import_react.useMemo)(
        () => ({
          size: "lg",
          useTextAvatar: true,
          ...(resolvedClientCardProps == null ? void 0 : resolvedClientCardProps.avatar) || {}
        }),
        [resolvedClientCardProps == null ? void 0 : resolvedClientCardProps.avatar]
      );
      const clientSearchContainerProps = (0, import_react.useMemo)(
        () => ({
          open: searchModalVisible,
          onCancel: closeSearchModal,
          destroyOnClose: true,
          width: 880
        }),
        [closeSearchModal, searchModalVisible]
      );
      const switchModalFooterButtonStyle = (0, import_react.useMemo)(() => ({ flex: 1 }), []);
      const switchModalFooterStyle = (0, import_react.useMemo)(
        () => ({
          display: "flex",
          gap: 12,
          paddingBottom: "calc(12px + env(safe-area-inset-bottom))"
        }),
        []
      );
      const switchModalFooter = (0, import_react.useMemo)(
        () => /* @__PURE__ */ import_react.default.createElement("div", { style: switchModalFooterStyle }, /* @__PURE__ */ import_react.default.createElement(
          ModalButton,
          {
            style: switchModalFooterButtonStyle,
            onClick: handleCancelSwitch,
            disabled: isSelectingClient
          },
          import_utils.locales.getText("pisell2.text.cancel")
        ), /* @__PURE__ */ import_react.default.createElement(
          ModalButton,
          {
            style: switchModalFooterButtonStyle,
            type: "primary",
            onClick: handleConfirmSwitch,
            loading: isSelectingClient
          },
          import_utils.locales.getText("pisell2.text.switch-account")
        )),
        [
          handleCancelSwitch,
          handleConfirmSwitch,
          isSelectingClient,
          switchModalFooterButtonStyle,
          switchModalFooterStyle
        ]
      );
      const switchModalProps = (0, import_react.useMemo)(
        () => isPhoneVariant ? {
          className: "cart-client-card_switch-modal",
          open: switchModalVisible,
          placement: "bottom",
          width: "100%",
          height: "auto",
          onClose: handleCancelSwitch,
          closable: false,
          title: import_utils.locales.getText("pisell2.text.cart-client-card")(
            (0, import_utils2.getClientName)(pendingCustomer)
          ),
          destroyOnClose: true,
          maskClosable: !isSelectingClient,
          bodyStyle: {
            padding: 0
          },
          footer: switchModalFooter
        } : {
          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,
          confirmLoading: isSelectingClient,
          cancelButtonProps: { disabled: isSelectingClient },
          maskClosable: !isSelectingClient,
          title: import_utils.locales.getText("pisell2.text.cart-client-card")(
            (0, import_utils2.getClientName)(pendingCustomer)
          ),
          footerDivider: false,
          destroyOnClose: true
        },
        [
          handleCancelSwitch,
          handleConfirmSwitch,
          isPhoneVariant,
          isSelectingClient,
          switchModalFooter,
          switchModalVisible
        ]
      );
      (0, import_react.useImperativeHandle)(ref, () => ({
        handleSetClient,
        openSearchModal
      }));
      return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, showClientCard ? /* @__PURE__ */ import_react.default.createElement(
        "section",
        {
          className: (0, import_classnames.default)(
            "pisell-sale-detail-client",
            `pisell-sale-detail-client--${currentVariant}`,
            readOnly && "pisell-sale-detail-client--interaction-disabled",
            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: readOnly ? void 0 : openSearchModal,
            onChangeClient: readOnly ? void 0 : openSearchModal,
            onRemoveClient: readOnly ? void 0 : handleRemoveClient,
            onViewClient: readOnly ? void 0 : handleViewClient,
            style: clientCardStyle,
            isShowAvatar: Boolean(isShowAvatar),
            dropdown: (resolvedClientCardProps == null ? void 0 : resolvedClientCardProps.dropdown) || defaultDropdownProps,
            avatar: clientCardAvatar,
            tag: resolvedClientCardProps == null ? void 0 : resolvedClientCardProps.tag,
            tags: resolvedClientCardProps == null ? void 0 : resolvedClientCardProps.tags
          }
        )))
      ) : null, /* @__PURE__ */ import_react.default.createElement(
        import_clinetSearch.default,
        {
          ref: clientSearchRef,
          loading,
          dataSource: clientList,
          onSearch: handleSearchClient,
          keyword,
          onKeywordChange: handleKeywordChange,
          onRowClick: handleSelectClient,
          containerProps: clientSearchContainerProps,
          isShowNewButton: false,
          resultProps,
          onAddClient: handleAddClientSuccess,
          onLoadMore: handleLoadMore,
          hasMore,
          resultLoading: resultLoading ?? loadingMore,
          rowLoadingId: searchModalVisible ? selectingCustomerId : null
        }
      ), /* @__PURE__ */ import_react.default.createElement(
        import_compensatedPisellContainer.default,
        {
          renderType: isPhoneVariant ? "drawer" : "modal",
          showHandlerBar: isPhoneVariant,
          props: switchModalProps
        }
      ));
    }
  )
);
ClientSelector.displayName = "ClientSelector";
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ClientSelector
});
