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/client/index.tsx
var client_exports = {};
__export(client_exports, {
  default: () => client_default
});
module.exports = __toCommonJS(client_exports);
var import_react = __toESM(require("react"));
var import_PlusCircle = __toESM(require("@pisell/icon/es/PlusCircle"));
var import_DotsVertical = __toESM(require("@pisell/icon/es/DotsVertical"));
var import_User01 = __toESM(require("@pisell/icon/es/User01"));
var import_model = require("../model");
var import_antd = require("antd");
var import_customSelect = __toESM(require("../../components/customSelect"));
var import_index = require("./index.less");
var import_utils = require("@pisell/utils");
var import_utils2 = require("../../utils");
var import_serve = require("./serve");
var import_ahooks = require("ahooks");
var import_utils3 = require("../clientVariant/utils");
var import_useGetHolderList = __toESM(require("../hooks/useGetHolderList"));
var isLoadClient = false;
var Client = () => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
  const modalRef = (0, import_react.useRef)();
  const [loadLoading, setLoadLoading] = (0, import_react.useState)(false);
  const [loading, setLoading] = (0, import_react.useState)(false);
  const { state, dispatch } = (0, import_react.useContext)(import_model.Context);
  const [franchiseeLoading, setFranchiseeLoading] = (0, import_react.useState)(0);
  const getHolders = (0, import_useGetHolderList.default)(state, dispatch);
  const [params, setParams] = (0, import_react.useState)({
    skip: 1,
    num: 10,
    total: 0,
    search: "",
    sort_by: "id"
  });
  const menus = (0, import_react.useMemo)(() => {
    let list = [
      { key: "view", label: import_utils.locales.getText("pisell2.text.view-profile") },
      { key: "change", label: import_utils.locales.getText("pisell2.text.change-customer") },
      { key: "remove", label: import_utils.locales.getText("pisell2.text.remove-customer") }
    ];
    if (state.disabledEdit) {
      list = list.filter((d) => d.key === "view");
    }
    return list;
  }, [state.disabledEdit]);
  const getClients = async ({
    customer_id,
    ...resetParams
  }) => {
    var _a2, _b2;
    let _setLoading;
    if (resetParams.skip === 1) {
      if (resetParams.search) {
        _setLoading = setLoading;
      } else {
        _setLoading = isLoadClient || ((_b2 = (_a2 = state == null ? void 0 : state.client) == null ? void 0 : _a2.clients) == null ? void 0 : _b2.length) ? () => {
        } : setLoading;
      }
    } else {
      _setLoading = setLoadLoading;
    }
    _setLoading(true);
    const api = state.isFranchisee ? import_serve.getFranchiseeCustomerList : state.apis.getClientsEs;
    const withKey = [...(resetParams == null ? void 0 : resetParams.with) || []];
    if (!withKey.includes("contactsInfo")) {
      withKey.push("contactsInfo");
    }
    const data = await api({
      ...resetParams,
      with: withKey,
      ...!state.isFranchisee ? { _config: { abort: true } } : {}
    });
    const list = ((data == null ? void 0 : data.list) || []).map((d) => {
      return {
        ...d,
        id: d.franchisee_customer_id || d.id
      };
    });
    let _payload = {
      clients: list
    };
    if (!(0, import_utils2.isWalkIn)(customer_id)) {
      const customerItem = list.find((d) => d.id === customer_id);
      if (customerItem) {
        _payload.value = customerItem;
        _payload.edit = true;
      }
    }
    let totalList = [...state.client.clients];
    if (resetParams.skip === 1) {
      totalList = list;
    } else {
      totalList = totalList.concat(list);
    }
    _payload.clients = totalList;
    setParams({
      ...params,
      ...resetParams,
      total: (data == null ? void 0 : data.count) || 0
    });
    dispatch({
      type: "setClient",
      payload: _payload
    });
    setLoading(false);
    setLoadLoading(false);
    isLoadClient = true;
    return {};
  };
  const handleOpenClientModal = () => {
    var _a2;
    if (state.disabledEdit) {
      return;
    }
    getClients({ ...params, search: "", skip: 1 });
    (_a2 = modalRef.current) == null ? void 0 : _a2.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 _getFranchiseeCustomerInfo = async (customer) => {
    try {
      setFranchiseeLoading(customer.id);
      const res = await (0, import_serve.getFranchiseeCustomerInfo)({
        franchisor_customer_id: customer.id
      });
      setFranchiseeLoading(0);
      return {
        ...customer,
        id: res.franchisee_customer_id
      };
    } catch (err) {
      setFranchiseeLoading(0);
    }
  };
  const handleSelectClient = (0, import_ahooks.useMemoizedFn)(async (value) => {
    let _value = (value == null ? void 0 : value[value.length - 1]) || import_model.walkInData;
    if (_value.loading) {
      return;
    }
    if (state.isFranchisee && _value.franchisee_customer_id === 0) {
      try {
        _value = await _getFranchiseeCustomerInfo(_value);
      } catch (err) {
      }
      if (!_value) {
        return;
      }
    }
    dispatch({
      type: "setClient",
      payload: {
        value: {
          ..._value,
          name: getNickname(_value)
        },
        edit: true
      }
    });
    return new Promise((resolve) => {
      resolve(0);
    });
  });
  const handleViewClient = () => {
    state.action({
      type: "pisell1.handleOpenCustomerModal",
      data: { id: state.client.value.id },
      callback: (data) => {
        if (state.disabledEdit) {
          return;
        }
        if (data) {
          handleSelectClient([data]);
        }
        getHolders();
        getClients({
          ...state.client.clientsParams,
          search: "",
          customer_id: data == null ? void 0 : data.id,
          skip: 1,
          sort_by: "id"
        });
      }
    });
  };
  const handleCreateItem = (0, import_ahooks.useMemoizedFn)(() => {
    state.action({
      type: "pisell1.handleOpenAddCustomerModal",
      data: {
        showReceiveAddress: false,
        showAcceptsMarketing: false
      },
      callback: (customer_id, params2) => {
        var _a2, _b2, _c2, _d2, _e2, _f2, _g2;
        const waiverForm = ((_d2 = (_c2 = (_b2 = (_a2 = state.client) == null ? void 0 : _a2.clients) == null ? void 0 : _b2[0].waiver_form) == null ? void 0 : _c2.map) == null ? void 0 : _d2.call(_c2, (item) => ({
          ...item,
          is_filled: 0
        }))) || [];
        dispatch({
          type: "setClient",
          payload: {
            clients: [
              ...((_e2 = params2 == null ? void 0 : params2[0]) == null ? void 0 : _e2.customer) ? [{ ...(_f2 = params2 == null ? void 0 : params2[0]) == null ? void 0 : _f2.customer, id: customer_id, waiver_form: waiverForm }] : [],
              ...((_g2 = state.client) == null ? void 0 : _g2.clients) || []
            ]
          }
        });
      }
    });
  });
  const handleRemoveClient = () => {
    if (state.disabledEdit) {
      return;
    }
    handleSelectClient([import_model.walkInData]);
  };
  const menuChange = (e) => {
    let maps = {
      view: handleViewClient,
      change: handleOpenClientModal,
      remove: handleRemoveClient
    };
    maps[e.key]();
  };
  const isWalkIn = (0, import_react.useMemo)(() => {
    var _a2;
    return (0, import_utils2.isWalkIn)((_a2 = state.client.value) == null ? void 0 : _a2.id);
  }, [(_a = state.client.value) == null ? void 0 : _a.id]);
  (0, import_react.useEffect)(() => {
    if (state.action) {
      state.action({
        type: "pisell1.registerPlugin",
        data: {
          pluginList: ["CustomerDetailPlugin"]
        }
      });
    }
  }, []);
  const renderList = (0, import_react.useMemo)(() => {
    let _list = [...state.client.clients];
    return _list;
  }, [state.client.clients]);
  const searchChange = (0, import_ahooks.useMemoizedFn)((search) => {
    let _params = {
      ...params,
      skip: 1,
      search
    };
    getClients({ ..._params });
  });
  const loadMore = (0, import_react.useMemo)(() => {
    const show = state.client.clients.length < params.total || 0;
    return show ? /* @__PURE__ */ import_react.default.createElement("div", { className: "", style: { textAlign: "center", padding: "16px 0" } }, /* @__PURE__ */ import_react.default.createElement(
      import_antd.Button,
      {
        loading: loadLoading,
        onClick: () => {
          let _params = {
            ...params,
            skip: params.skip + 1
          };
          getClients({ ..._params });
        }
      },
      import_utils.locales.getText("pisell2.text.load-more")
    )) : null;
  }, [loadLoading, params, state.client.clients.length]);
  const customSelect = (0, import_react.useMemo)(() => {
    console.log("render customSelect");
    return /* @__PURE__ */ import_react.default.createElement(
      import_customSelect.default,
      {
        autoFocus: !state.isTerminal,
        modalOpen: state.modalOpen,
        ref: modalRef,
        rowKey: "id",
        options: renderList,
        loading,
        value: [state.client.value],
        onValueChange: handleSelectClient,
        handleCreateItem,
        isPreview: false,
        drawerProps: {
          title: import_utils.locales.getText("pisell2.text.select-customer"),
          destroyOnClose: true,
          mask: state.drawerMask
        },
        mode: "single",
        createItemText: import_utils.locales.getText("pisell2.text.create-new-customer"),
        closeCallback: () => {
        },
        optionRender: (item) => {
          var _a2, _b2, _c2, _d2, _e2;
          console.log("render_optionRender", item);
          let displayEmail = item == null ? void 0 : item.email;
          let displayPhone = item == null ? void 0 : item.phone;
          if (!displayEmail && !displayPhone) {
            displayEmail = (_b2 = (_a2 = item == null ? void 0 : item.contacts_info) == null ? void 0 : _a2.value) == null ? void 0 : _b2.email;
            displayPhone = (_e2 = (_d2 = (_c2 = item == null ? void 0 : item.contacts_info) == null ? void 0 : _c2.value) == null ? void 0 : _d2.phone) == null ? void 0 : _e2.phone;
          }
          return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
            import_antd.Avatar,
            {
              className: "pisell-lowcode__booking-client-list-item-avatar",
              src: import_utils.image.ali(item.cover, 100) || void 0,
              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" }, getNickname(item)), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-client-list-item-info-desc" }, displayEmail ? /* @__PURE__ */ import_react.default.createElement("div", { className: "" }, displayEmail) : null, displayPhone ? /* @__PURE__ */ import_react.default.createElement("div", { className: "" }, displayPhone) : null), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-client-list-item-info-waiver", title: (0, import_utils3.getWaiverTitle)(item.waiver_form) }, (item.waiver_form || []).map((item2) => {
            return /* @__PURE__ */ import_react.default.createElement("span", null, item2.form_title, ":", item2.is_filled ? /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-lowcode__booking-client-list-item-waiver-filled" }, import_utils.locales.getText("pisell2.text.filled")) : /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-lowcode__booking-client-list-item-waiver-not-filled" }, import_utils.locales.getText("pisell2.text.not-filled")), "; ");
          }))), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-client-list-item-loading" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Spin, { spinning: franchiseeLoading === item.id })));
        },
        searchChange,
        searchValue: params.search,
        loadMore,
        filterItem: (d, search) => {
          return true;
        }
      }
    );
  }, [state.isTerminal, state.modalOpen, (_b = state.client) == null ? void 0 : _b.value, state.drawerMask, renderList, loading, franchiseeLoading, params.search, loadMore]);
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: "pisell-lowcode__booking-client",
      onClick: () => {
        if (!isWalkIn || (state == null ? void 0 : state.disableEventBookingEdit)) {
          return;
        }
        handleOpenClientModal();
      },
      style: state.bookingId ? {} : { marginTop: 12 }
    },
    /* @__PURE__ */ import_react.default.createElement(
      import_antd.Avatar,
      {
        className: "pisell-lowcode__booking-client-list-item-avatar",
        src: import_utils.image.ali((_c = state.client.value) == null ? void 0 : _c.cover, 100),
        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-info" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-client-info-left" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-client-info-name" }, getNickname(state.client.value)), isWalkIn ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-client-info-desc" }, import_utils.locales.getText("pisell2.text.leave-empty-for-walk-in")) : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, ((_d = state.client.value) == null ? void 0 : _d.email) ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-client-info-email" }, (_e = state.client.value) == null ? void 0 : _e.email) : null, ((_f = state.client.value) == null ? void 0 : _f.phone) ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-client-info-phone" }, (_g = state.client.value) == null ? void 0 : _g.phone) : null, !!((_i = (_h = state.client.value) == null ? void 0 : _h.waiver_form) == null ? void 0 : _i.length) && /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-client-waiver", title: (0, import_utils3.getWaiverTitle)((_j = state.client.value) == null ? void 0 : _j.waiver_form) }, (_m = (_l = (_k = state.client.value) == null ? void 0 : _k.waiver_form) == null ? void 0 : _l.map) == null ? void 0 : _m.call(_l, (item) => {
      return /* @__PURE__ */ import_react.default.createElement("span", null, item.form_title, /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-lowcode__booking-client-waiver-colon" }, ":"), item.is_filled ? /* @__PURE__ */ import_react.default.createElement(
        "span",
        {
          className: "pisell-lowcode__booking-client-waiver-filled"
        },
        import_utils.locales.getText("pisell2.text.filled")
      ) : /* @__PURE__ */ import_react.default.createElement(
        "span",
        {
          className: "pisell-lowcode__booking-client-waiver-not-filled"
        },
        import_utils.locales.getText("pisell2.text.not-filled")
      ), `; `);
    })))), !(state == null ? void 0 : state.disableEventBookingEdit) && /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-client-info-right" }, isWalkIn ? /* @__PURE__ */ import_react.default.createElement(import_PlusCircle.default, { className: "pisell-lowcode__booking-client-add-icon" }) : /* @__PURE__ */ import_react.default.createElement(
      import_antd.Dropdown,
      {
        menu: {
          items: menus,
          onClick: menuChange
        },
        placement: "bottomRight"
      },
      /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-client-menu-wrap" }, /* @__PURE__ */ import_react.default.createElement(import_DotsVertical.default, { className: "pisell-lowcode__booking-client-menu-icon" }))
    )))
  ), customSelect);
};
var client_default = import_react.default.memo(Client);
