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/info/clientVariant/vertical/SelectDrawer.tsx
var SelectDrawer_exports = {};
__export(SelectDrawer_exports, {
  default: () => SelectDrawer_default
});
module.exports = __toCommonJS(SelectDrawer_exports);
var import_react = __toESM(require("react"));
var import_drawer = __toESM(require("../../../components/drawer"));
var import_antd = require("antd");
var import_SearchLg = __toESM(require("@pisell/icon/es/SearchLg"));
var import_utils = require("@pisell/utils");
var import_Plus = __toESM(require("@pisell/icon/es/Plus"));
var import_User01 = __toESM(require("@pisell/icon/es/User01"));
var import_utils2 = require("../../../utils");
var import_classnames = __toESM(require("classnames"));
var import_SelectDrawer = require("./SelectDrawer.less");
var import_format = require("../../../forms/format");
var import_utils3 = require("../../utils");
var import_PlusCircle = __toESM(require("@pisell/icon/es/PlusCircle"));
var import_utils4 = require("../utils");
var ActionItem = (props) => {
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: "vertical-client-select-drawer-item-wrap",
      onClick: props.onClick
    },
    /* @__PURE__ */ import_react.default.createElement("span", { className: "vertical-client-item-icon-wrap" }, /* @__PURE__ */ import_react.default.createElement(import_Plus.default, { style: { fontSize: 28, color: "#7F56D9" } })),
    /* @__PURE__ */ import_react.default.createElement("span", { className: "vertical-client-item-title" }, props.title)
  );
};
var Item = ({
  cover,
  onClick,
  title,
  desc,
  coverSize,
  checked,
  style,
  loading,
  waiverForm
}) => {
  const waiverTitle = (0, import_react.useMemo)(() => {
    return (0, import_utils4.getWaiverTitle)(waiverForm);
  }, [waiverForm]);
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: (0, import_classnames.default)("vertical-client-select-drawer-item-wrap", {
        ["checked"]: checked
      }),
      onClick,
      style
    },
    /* @__PURE__ */ import_react.default.createElement(
      import_antd.Avatar,
      {
        className: "pisell-lowcode__booking-client-list-item-avatar",
        src: import_utils.image.ali(cover, 100) || void 0,
        size: coverSize || 56,
        icon: /* @__PURE__ */ import_react.default.createElement(import_User01.default, { className: "pisell-lowcode__booking-client-list-item-avatar-icon" })
      }
    ),
    /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-client-list-item-info" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-client-list-item-info-name" }, title), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-client-list-item-info-desc" }, (desc || []).map((d) => /* @__PURE__ */ import_react.default.createElement("div", { className: "", title: d }, d))), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-client-list-item-info-desc-waiver", title: waiverTitle }, (waiverForm || []).map((item) => {
      return /* @__PURE__ */ import_react.default.createElement("span", null, item.form_title, ":", item.is_filled ? /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-lowcode__booking-client-list-item-info-desc-filled" }, import_utils.locales.getText("pisell2.text.filled")) : /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-lowcode__booking-client-list-item-info-desc-not-filled" }, import_utils.locales.getText("pisell2.text.not-filled")), "; ");
    }))),
    /* @__PURE__ */ import_react.default.createElement(import_antd.Spin, { spinning: !!loading })
  );
};
var defaultArr = [];
var SelectDrawer = (props, ref) => {
  const {
    autoFocus,
    onClose,
    handleSelectClient,
    handleCreateItem,
    childrenValue,
    handleSelectPet,
    formData,
    searchChange,
    options,
    loading,
    holder,
    client,
    loadMore,
    showPet,
    handleAddPet,
    modalOpen,
    franchiseeLoading,
    showHeader,
    showWalkIn
  } = props;
  const form = (formData == null ? void 0 : formData[0]) || {};
  const valList = (childrenValue == null ? void 0 : childrenValue[form.id]) || defaultArr;
  const [_value, setValue] = (0, import_react.useState)(valList);
  const clientRef = (0, import_react.useRef)();
  const searchRef = (0, import_react.useRef)();
  const [open, setOpen] = (0, import_react.useState)(false);
  const [search, setSearch] = (0, import_react.useState)("");
  (0, import_react.useEffect)(() => {
    setValue(
      valList.map((item) => ({
        ...item,
        id: item.id || item.form_record_id
      }))
    );
  }, [valList, open]);
  (0, import_react.useEffect)(() => {
    if (!modalOpen) {
      setOpen(false);
    }
  }, [modalOpen]);
  const closeDrawer = () => {
    setOpen(false);
    setSearch("");
    onClose == null ? void 0 : onClose();
  };
  const handleOpenModal = () => {
    setOpen(true);
    if (autoFocus) {
      setTimeout(() => {
        var _a, _b;
        (_b = (_a = searchRef.current) == null ? void 0 : _a.focus) == null ? void 0 : _b.call(_a);
      }, 400);
    }
  };
  (0, import_react.useImperativeHandle)(ref, () => {
    return {
      open: handleOpenModal,
      close: () => {
        setOpen(false);
      },
      setSearch: (val) => {
        setSearch(val);
      }
      // setValue: set_value,
    };
  });
  (0, import_react.useEffect)(() => {
    if (!open) {
      clientRef.current = null;
    }
  }, [open]);
  const getNickname = (0, import_react.useCallback)(
    (item) => {
      if ((0, import_utils2.isWalkIn)(item == null ? void 0 : item.id)) {
        return import_utils.locales.getText("pisell2.text.select-a-customer");
      }
      const firstLastName = item.first_name || item.last_name ? `${item.first_name} ${item.last_name}` : "";
      return item.name || (item.display_name || "").trim() || (item.nickname || "").trim() || firstLastName.trim() || "";
    },
    [import_utils.locales.localeMap]
  );
  const handleAddClient = () => {
    handleCreateItem(() => {
      setSearch("");
    });
  };
  const handleChildrenValueChange = async (value, item) => {
    var _a;
    let clientId = client.id;
    if (!(client == null ? void 0 : client.id) || client.id === 1) {
      clientId = ((_a = clientRef.current) == null ? void 0 : _a.id) || item.id;
    }
    if (mode === "single") {
      if (!(client == null ? void 0 : client.id) || client.id === 1) {
        await handleSelectClient([item]);
      }
      handleSelectPet({
        [form.id]: (0, import_format.formatAddFormValues)({
          clientId,
          value: [value],
          data_range: holder.data_range
        })
      });
      setTimeout(() => {
        closeDrawer();
      });
    } else {
      const index = _value.findIndex(
        (item2) => item2.id === value.id || item2.form_record_id === value.id
      );
      if (!clientRef.current) {
        clientRef.current = item;
      }
      if (index >= 0) {
        const newList = [..._value];
        newList.splice(index, 1);
        setValue(
          (0, import_format.formatAddFormValues)({
            clientId,
            value: newList,
            data_range: holder.data_range
          })
        );
      } else {
        setValue(
          (0, import_format.formatAddFormValues)({
            clientId,
            value: [..._value, value],
            data_range: holder.data_range
          })
        );
      }
    }
  };
  const mode = (0, import_react.useMemo)(() => {
    if (["form"].includes(holder == null ? void 0 : holder.type)) {
      return "single";
    }
    if (["table"].includes(holder == null ? void 0 : holder.type)) {
      return "multiple";
    }
    return holder == null ? void 0 : holder.type;
  }, [holder == null ? void 0 : holder.type]);
  const handleOk = async () => {
    var _a;
    if (!(client == null ? void 0 : client.id) || (client == null ? void 0 : client.id) === 1) {
      await handleSelectClient([clientRef.current]);
    }
    handleSelectPet({
      [(_a = holder == null ? void 0 : holder.form) == null ? void 0 : _a.id]: _value
    });
    closeDrawer();
  };
  const handleClientClick = async (item) => {
    var _a;
    await handleSelectClient([item]);
    if (mode === "multiple") {
      const isHasChildren = _value.some(
        (val) => item.form_record.some(
          (f) => f.id || f.form_record_id === val.id || val.form_record_id
        )
      );
      handleSelectPet({
        [form.id]: (0, import_utils3.uniqueByField)(
          [
            ...(0, import_format.sortFormValues)(_value, item.id),
            ...isHasChildren ? [] : (0, import_format.formatAddFormValues)({
              clientId: item.id,
              data_range: holder.data_range,
              value: (_a = item.form_record) == null ? void 0 : _a.map((f) => ({
                ...f,
                customer: item
              }))
            })
          ],
          "id"
        )
      });
    }
    closeDrawer();
  };
  return /* @__PURE__ */ import_react.default.createElement(
    import_drawer.default,
    {
      showGoBack: showHeader,
      title: showHeader && import_utils.locales.getText("pisell2.text.select-customer"),
      open,
      onClose: closeDrawer,
      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: { margin: "16px 0", height: 44 },
          placeholder: import_utils.locales.getText("pisell2.text.search"),
          value: search,
          allowClear: true,
          onChange: (e) => {
            setSearch(e.target.value);
            if (searchChange) {
              searchChange(e.target.value);
            }
          }
        }
      )),
      width: 300,
      titleNoWrap: true,
      getContainer: false,
      destroyOnClose: true,
      push: { distance: 180 },
      footer: mode === "multiple" && /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement(
        import_antd.Button,
        {
          block: true,
          type: "primary",
          onClick: handleOk,
          loading: !!franchiseeLoading
        },
        import_utils.locales.getText("pisell2.text.apply")
      ))
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: "vertical-client-select-drawer-content-wrap" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "vertical-client-select-drawer-top" }, /* @__PURE__ */ import_react.default.createElement(
      ActionItem,
      {
        title: import_utils.locales.getText("pisell2.text.create-new-customer"),
        onClick: handleAddClient
      }
    ), showWalkIn ? /* @__PURE__ */ import_react.default.createElement(
      ActionItem,
      {
        title: "Walk-In",
        onClick: () => {
          handleSelectClient([]);
          closeDrawer();
        }
      }
    ) : null), /* @__PURE__ */ import_react.default.createElement(import_antd.Spin, { spinning: !!loading, delay: 500 }, !!options.length ? options.map((item) => {
      var _a;
      return /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: "vertical-client-select-drawer-content-item",
          key: item.id
        },
        /* @__PURE__ */ import_react.default.createElement(
          Item,
          {
            onClick: () => handleClientClick(item),
            cover: item.cover,
            title: getNickname(item),
            desc: [item.email, item.phone],
            checked: item.id === client.id,
            style: showPet ? { marginBottom: 6 } : {},
            loading: franchiseeLoading === item.id,
            waiverForm: item.waiver_form
          }
        ),
        showPet && /* @__PURE__ */ import_react.default.createElement("div", { className: "vertical-client-select-drawer-content-item-children" }, ((item == null ? void 0 : item.form_record) || []).map((f) => {
          const checked = _value.some(
            (item2) => item2.id === f.id || item2.form_record_id === f.id
          );
          return /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              onClick: () => {
                handleChildrenValueChange(
                  { ...f, customer: item },
                  item
                );
              },
              id: `${f.id}`,
              key: f.id,
              className: (0, import_classnames.default)(
                "vertical-client-select-drawer-content-item-children-item",
                {
                  ["checked"]: checked
                }
              )
            },
            mode === "multiple" && /* @__PURE__ */ import_react.default.createElement(import_antd.Checkbox, { checked }),
            /* @__PURE__ */ import_react.default.createElement(
              Item,
              {
                coverSize: 48,
                title: f.main_field,
                loading: false
              }
            )
          );
        }), /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            className: "pisell-lowcode__custom-select-create",
            onClick: () => {
              handleAddPet == null ? void 0 : handleAddPet(item);
            },
            style: { padding: 16 }
          },
          /* @__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" }, `${import_utils.locales.getText("pisell2.text.create-new")} ${((_a = holder.form) == null ? void 0 : _a.title) || "-"}`))
        ), /* @__PURE__ */ import_react.default.createElement("div", null))
      );
    }) : /* @__PURE__ */ import_react.default.createElement(import_antd.Empty, { image: import_antd.Empty.PRESENTED_IMAGE_SIMPLE }), /* @__PURE__ */ import_react.default.createElement("div", null, loadMore)))
  );
};
var SelectDrawer_default = (0, import_react.forwardRef)(SelectDrawer);
