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_antd = require("antd");
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_lodash = require("lodash");
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 import_IsActiveContext = require("../../../ticketBooking/context/IsActiveContext");
var import_serve = require("../serve");
var import_compensatedPisellContainer = __toESM(require("../../../../pro/compensatedPisellContainer"));
var import_responsive = require("../../../../responsive");
var CartClientCard = (0, import_react.forwardRef)(({
  clientCardProps = {},
  displayClient,
  beforeSwitchModalOpen,
  onClientChange,
  disabledSwitch = false,
  variant
}, ref) => {
  var _a, _b, _c, _d, _e, _f;
  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)("");
  const isActive = (0, import_IsActiveContext.useIsActive)();
  const [resultLoading, setResultLoading] = (0, import_react.useState)(false);
  const isPhoneVariant = variant === "phone";
  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 boardConfig = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2;
    return ((_c2 = (_b2 = (_a2 = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _a2.config) == null ? void 0 : _b2.basic) == null ? void 0 : _c2.appointment_subject) || {};
  }, [(_e = (_d = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _d.config) == null ? void 0 : _e.basic]);
  const {
    customers,
    loading,
    pagination,
    changePage,
    selectCustomer,
    addCustomerToFirst,
    initLoad,
    hasMore,
    loadMore
  } = (0, import_useCustomer.useCustomer)({});
  const selectedCustomer = displayClient || ((_f = state.client) == null ? void 0 : _f.value);
  const handleSearchClient = async (keyword2) => {
    var _a2, _b2;
    await initLoad(keyword2, boardConfig == null ? void 0 : boardConfig.form_id);
    (_b2 = (_a2 = clientSearchRef.current) == null ? void 0 : _a2.resetScrollPosition) == null ? void 0 : _b2.call(_a2);
  };
  const _debouncedSearch = (0, import_ahooks.useDebounceFn)(
    async (_keyword, formId) => {
      var _a2, _b2;
      await initLoad(keyword, formId);
      (_b2 = (_a2 = clientSearchRef.current) == null ? void 0 : _a2.resetScrollPosition) == null ? void 0 : _b2.call(_a2);
    },
    { wait: 500 }
  );
  (0, import_react.useEffect)(() => {
    _debouncedSearch.run(keyword, boardConfig == null ? void 0 : boardConfig.form_id);
  }, [keyword, boardConfig == null ? void 0 : boardConfig.form_id]);
  (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 = () => {
    var _a2;
    if (disabledSwitch) {
      (_a2 = Toast == null ? void 0 : Toast.info) == null ? void 0 : _a2.call(
        Toast,
        import_utils.locales.getText(
          "pisell2.checkout.client-card.tip.disabled-switch"
        )
      );
      return;
    }
    setSearchModalVisible(true);
  };
  const handleChangeClient = (data) => {
    setSearchModalVisible(true);
  };
  const handleRemoveClient = (data) => {
    selectCustomer(null);
  };
  const handleViewClient = (data) => {
    const newSelectedCustomer = (0, import_lodash.cloneDeep)(selectedCustomer);
    state.action({
      type: "pisell1.handleOpenCustomerModal",
      data: { id: state.client.value.id },
      callback: (data2) => {
        console.log("data>>>>>", data2);
        const _selectedCustomer = {
          ...newSelectedCustomer || {},
          display_name: (data2 == null ? void 0 : data2.display_name) || "",
          email: (data2 == null ? void 0 : data2.email) || "",
          phone: (data2 == null ? void 0 : data2.phone) || "",
          nickname: (data2 == null ? void 0 : data2.nickname) || "",
          country_calling_code: (data2 == null ? void 0 : data2.country_calling_code) || "",
          first_name: (data2 == null ? void 0 : data2.first_name) || "",
          last_name: (data2 == null ? void 0 : data2.last_name) || "",
          contacts_info: (data2 == null ? void 0 : data2.contacts_info) || null
        };
        selectCustomer(_selectedCustomer);
        if (JSON.stringify((newSelectedCustomer == null ? void 0 : newSelectedCustomer.contacts_info) || {}) !== JSON.stringify((data2 == null ? void 0 : data2.contacts_info) || {})) {
          dispatch({
            type: "setContactsInfo",
            payload: {
              value: (data2 == null ? void 0 : data2.contacts_info) || {},
              client_id: data2 == null ? void 0 : data2.id
            }
          });
        }
        handleSearchClient("");
      }
    });
  };
  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, _e2;
    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) {
        (_e2 = Toast == null ? void 0 : Toast.info) == null ? void 0 : _e2.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)(() => {
    if (isActive) {
      (0, import_utils3.setHandleSetClient)(handleSetClient);
    }
  }, [isActive]);
  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
  }));
  const handleRowClick = (0, import_ahooks.useMemoizedFn)(
    async (record, options) => {
      var _a2;
      try {
        if ((state == null ? void 0 : state.isFranchisee) && (record == null ? void 0 : record.is_franchisor_customer) == 1) {
          setResultLoading(true);
          let franchiseeCustomerId = record == null ? void 0 : record.franchisee_customer_id;
          if (!franchiseeCustomerId) {
            const res = await (0, import_serve.getFranchiseeCustomer)({
              franchisor_customer_id: record.id
            });
            franchiseeCustomerId = res == null ? void 0 : res.franchisee_customer_id;
          }
          if (franchiseeCustomerId) {
            const listRes = await (0, import_serve.getCustomerList)({
              sort_by: "id",
              with: [
                "latestWalletDetail.wallet",
                "contactsInfo",
                "formRecord"
              ],
              search_wallet_flag: 1,
              search_wallet_pass_flag: 1,
              skip: 1,
              num: 20,
              customer_ids: [franchiseeCustomerId]
            });
            if ((_a2 = listRes == null ? void 0 : listRes.list) == null ? void 0 : _a2.length) {
              await handleSetClient(listRes == null ? void 0 : listRes.list[0], options);
            }
          }
          return;
        }
        await handleSetClient(record, options);
      } catch (error) {
        console.error("handleRowClick error:", error);
      } finally {
        setResultLoading(false);
      }
    }
  );
  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: handleRowClick,
      containerProps: {
        open: searchModalVisible,
        onCancel: handleModalCancel,
        // 同时存在两个搜索弹窗时，内部的无限滚动组件会发生冲突
        destroyOnClose: true,
        width: 880
      },
      isShowNewButton: false,
      resultProps,
      onAddClient: handleAddClientSuccess,
      onLoadMore: loadMore,
      hasMore,
      state,
      resultLoading
    }
  ), /* @__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: 12
        },
        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 } }, import_utils.locales.getText("pisell2.text.cart-client-card")(
      (0, import_utils4.getClientName)(pendingCustomer)
    ))
  ));
});
CartClientCard.displayName = "CartClientCard";
var cartClientCard_default = (0, import_responsive.withResponsive)(CartClientCard);
