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/components/customSelect/index.tsx
var customSelect_exports = {};
__export(customSelect_exports, {
  default: () => customSelect_default
});
module.exports = __toCommonJS(customSelect_exports);
var import_react = __toESM(require("react"));
var import_PlusCircle = __toESM(require("@pisell/icon/es/PlusCircle"));
var import_SearchLg = __toESM(require("@pisell/icon/es/SearchLg"));
var import_DotsVertical = __toESM(require("@pisell/icon/es/DotsVertical"));
var import_utils = require("@pisell/utils");
var import_drawer = __toESM(require("../drawer"));
var import_addButton = __toESM(require("../addButton"));
var import_classnames = __toESM(require("classnames"));
var import_antd = require("antd");
var import_index = require("./index.less");
var import_utils2 = require("@pisell/utils");
var CustomSelect = (props, ref) => {
  const {
    loading,
    options,
    onValueChange,
    value,
    rowKey = "id",
    addButtonProps,
    drawerProps,
    createItemText = "",
    previewItemRender,
    previewItemTitleRender,
    addButtonRender,
    optionRender,
    filterItem,
    previewItemClassName,
    optionClassName,
    mode = "single",
    isPreview = true,
    name = "item",
    handleCreateItem,
    handleViewItem,
    virtualListHeight = window.innerHeight - 213 - 16,
    disabled = false,
    searchValue,
    searchChange,
    onVirtualListScroll,
    loadMore,
    modalOpen,
    closeCallback,
    autoFocus,
    showDropDown = true,
    handleOpenModal: propsHandleOpenModal,
    handleDayChange
  } = props;
  console.log("custom select");
  const searchRef = (0, import_react.useRef)();
  const [_value, set_value] = (0, import_react.useState)([]);
  const [search, setSearch] = (0, import_react.useState)("");
  const [open, setOpen] = (0, import_react.useState)(false);
  (0, import_react.useEffect)(() => {
    if (modalOpen === false) {
      setOpen(false);
    }
  }, [modalOpen]);
  const strValue = (0, import_react.useMemo)(() => {
    return JSON.stringify(value);
  }, [value]);
  (0, import_react.useEffect)(() => {
    initValue();
  }, [strValue]);
  const initValue = () => {
    let _val = value;
    if (!value) {
      _val = [];
    } else {
      if (!Array.isArray(value)) {
        _val = [value];
      }
    }
    set_value(_val);
  };
  const closeDrawer = (reset) => {
    setOpen(false);
    setSearch("");
    if (reset) {
      initValue();
    }
    closeCallback == null ? void 0 : closeCallback();
  };
  const handleOpenModal = (item) => {
    if (disabled) {
      return;
    }
    if (propsHandleOpenModal) {
      propsHandleOpenModal();
      return;
    }
    if (addButtonProps == null ? void 0 : addButtonProps.addCallback) {
      addButtonProps == null ? void 0 : addButtonProps.addCallback();
    }
    setOpen(true);
    initValue();
    if (autoFocus) {
      setTimeout(() => {
        var _a, _b;
        (_b = (_a = searchRef.current) == null ? void 0 : _a.focus) == null ? void 0 : _b.call(_a);
      }, 100);
    }
  };
  const _onValueChange = async (_val) => {
    await onValueChange(_val);
  };
  const handleSelectItem = (item) => {
    let _val = (0, import_utils.changeArray)(_value, item, rowKey);
    if (mode === "single") {
      handleApply([item]);
    }
    set_value(_val);
  };
  const _handleViewItem = (item) => {
    handleViewItem == null ? void 0 : handleViewItem(item);
  };
  const handleRemoveItem = (item) => {
    if (handleDayChange) {
      handleDayChange(item);
    }
    let _arr = (0, import_utils.changeArray)(_value, item, rowKey);
    _onValueChange(_arr);
    set_value(_arr);
  };
  const menuChange = (e, item) => {
    let maps = {
      view: _handleViewItem,
      change: handleOpenModal,
      remove: handleRemoveItem
    };
    maps[e.key](item);
  };
  const renderList = (0, import_react.useMemo)(() => {
    let _list = [...options];
    if (search) {
      const isIncludes = (item) => {
        try {
          const q = search.toLowerCase();
          const numericKeys = Object.keys(item).filter((k) => /^\d+$/.test(k));
          const customerKeys = [
            "customer_nickname",
            "customer_first_name",
            "customer_last_name",
            "customer_phone",
            "customer_email"
          ];
          const allKeys = [...numericKeys, ...customerKeys];
          return allKeys.some((k) => {
            const val = item[k];
            if (val === null || val === void 0) return false;
            try {
              const str = JSON.stringify(val);
              return str.includes(q) || str.toLocaleLowerCase().includes(q);
            } catch (error) {
              return false;
            }
          });
        } catch (e) {
          return false;
        }
      };
      _list = _list.filter((d) => {
        if (filterItem) {
          return filterItem(d, search);
        }
        return isIncludes(d);
      });
    }
    return _list;
  }, [options, loading, search]);
  const isMore = (0, import_react.useMemo)(() => {
    return _value.length > 0;
  }, [_value]);
  const handleApply = async (_val) => {
    await _onValueChange(_val || _value);
    closeDrawer();
  };
  (0, import_react.useImperativeHandle)(ref, () => {
    return {
      open: handleOpenModal,
      setValue: set_value
    };
  });
  const menuItems = (0, import_react.useMemo)(() => {
    let list = [
      {
        key: "view",
        label: `${import_utils2.locales.getText("pisell2.text.view")} ${name}`
      },
      {
        key: "change",
        label: `${import_utils2.locales.getText("pisell2.text.change")} ${name}`
      },
      {
        key: "remove",
        label: `${import_utils2.locales.getText("pisell2.text.remove")} ${name}`
      }
    ];
    if (disabled) {
      list = list.filter((d) => d.key === "view");
    }
    return list;
  }, [name, disabled, import_utils2.locales]);
  const isShowAddButton = (0, import_react.useMemo)(() => {
    return (mode === "multiple" || mode === "single" && !isMore) && !disabled;
  }, [mode, isMore, disabled]);
  return /* @__PURE__ */ import_react.default.createElement("div", null, isPreview ? /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__custom-select-cards" }, _value.map((d, index) => {
    return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, previewItemTitleRender == null ? void 0 : previewItemTitleRender(d, index, _value), /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: (0, import_classnames.default)(
          "pisell-lowcode__custom-select-card",
          previewItemClassName
        ),
        key: d[rowKey]
      },
      previewItemRender == null ? void 0 : previewItemRender(d),
      showDropDown && /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          onClick: (e) => {
            e.preventDefault();
            e.stopPropagation();
          }
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_antd.Dropdown,
          {
            menu: {
              items: menuItems,
              onClick: (e) => {
                menuChange(e, d);
              }
            },
            placement: "bottomRight"
          },
          /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__custom-select-card-menu-wrap" }, /* @__PURE__ */ import_react.default.createElement(import_DotsVertical.default, { className: "pisell-lowcode__custom-select-card-menu-icon" }))
        )
      )
    ));
  })), isShowAddButton ? addButtonRender ? addButtonRender() : /* @__PURE__ */ import_react.default.createElement(
    import_addButton.default,
    {
      showSub: isMore,
      ...addButtonProps,
      onClick: () => {
        if (addButtonProps.onClick) {
          addButtonProps.onClick();
          return;
        }
        handleOpenModal();
      }
    }
  ) : disabled ? /* @__PURE__ */ import_react.default.createElement("div", { style: { height: 20 } }) : null) : null, /* @__PURE__ */ import_react.default.createElement(
    import_drawer.default,
    {
      open,
      onClose: () => {
        closeDrawer(true);
      },
      titleNoWrap: true,
      header: /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement(
        import_antd.Input,
        {
          ref: searchRef,
          prefix: /* @__PURE__ */ import_react.default.createElement(import_SearchLg.default, null),
          style: { marginTop: 16, height: 44 },
          placeholder: import_utils2.locales.getText("pisell2.booking.text.search-placeholder"),
          value: search,
          allowClear: true,
          onChange: (e) => {
            setSearch(e.target.value);
            if (searchChange) {
              searchChange(e.target.value);
            }
          }
        }
      ), /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: "pisell-lowcode__custom-select-create",
          onClick: () => {
            handleCreateItem == null ? void 0 : handleCreateItem();
          },
          style: { padding: createItemText ? 16 : "16px 0 0 0" }
        },
        createItemText && /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(import_PlusCircle.default, { className: "pisell-lowcode__custom-select-create-icon" }), /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-lowcode__custom-select-create-txt" }, createItemText))
      )),
      ...drawerProps,
      footer: mode === "multiple" && /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement(
        import_antd.Button,
        {
          style: { width: "100%" },
          type: "primary",
          size: "large",
          onClick: () => {
            handleApply();
          }
        },
        import_utils2.locales.getText("pisell2.text.apply")
      ))
    },
    /* @__PURE__ */ import_react.default.createElement(
      import_antd.List,
      {
        itemLayout: "horizontal",
        dataSource: renderList,
        loading: { spinning: !!loading, delay: 500 },
        loadMore,
        renderItem: (item) => /* @__PURE__ */ import_react.default.createElement(
          import_antd.List.Item,
          {
            className: (0, import_classnames.default)(
              "pisell-lowcode__custom-select-card-list-item",
              optionClassName,
              {
                "pisell-lowcode__custom-select-card-list-item-active": (0, import_utils.getItemByArray)(_value, item, rowKey)
              }
            ),
            onClick: () => {
              if ((item == null ? void 0 : item.status) === "expired") return;
              handleSelectItem(item);
            },
            id: item[rowKey]
          },
          item.loading ? /* @__PURE__ */ import_react.default.createElement(
            import_antd.Skeleton,
            {
              active: true,
              round: true,
              loading: item.loading,
              avatar: true,
              paragraph: false
            }
          ) : /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__custom-select-card-list-item-content" }, mode === "multiple" && /* @__PURE__ */ import_react.default.createElement(
            import_antd.Checkbox,
            {
              disabled: (item == null ? void 0 : item.status) === "expired",
              className: "custom-select-checkbox",
              checked: (0, import_utils.getItemByArray)(_value, item, rowKey)
            }
          ), optionRender(item))
        )
      }
    )
  ));
};
var customSelect_default = (0, import_react.forwardRef)(CustomSelect);
