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/hooks/useClientFn.tsx
var useClientFn_exports = {};
__export(useClientFn_exports, {
  default: () => useClientFn_default
});
module.exports = __toCommonJS(useClientFn_exports);
var import_react = __toESM(require("react"));
var import_utils = require("../../../utils");
var import_serve = require("../../client/serve");
var import_model = require("../../model");
var import_utils2 = require("@pisell/utils");
var import_antd = require("antd");
var import_useIsLowSpeedNetwork = __toESM(require("./useIsLowSpeedNetwork"));
var isLoadClient = false;
var useClientFn = (_params) => {
  var _a, _b, _c, _d, _e, _f, _g, _h;
  const { state, setGlobalState, modalRef, onRemoveClient } = _params;
  const [loadLoading, setLoadLoading] = (0, import_react.useState)(false);
  const [loading, setLoading] = (0, import_react.useState)(false);
  const [franchiseeLoading, setFranchiseeLoading] = (0, import_react.useState)(0);
  const isLowSpeedNetwork = (0, import_useIsLowSpeedNetwork.default)();
  const [params, setParams] = (0, import_react.useState)({
    skip: 1,
    num: 5,
    total: 0,
    search: "",
    with: ["formRecord", "contactsInfo"],
    relation_form_id: (_d = (_c = (_b = (_a = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _a.config) == null ? void 0 : _b.basic) == null ? void 0 : _c.appointment_subject) == null ? void 0 : _d.form_id
  });
  const paramsRef = (0, import_react.useRef)(params);
  paramsRef.current = params;
  (0, import_react.useEffect)(() => {
    setParams((v) => {
      var _a2, _b2, _c2, _d2;
      return {
        ...v,
        relation_form_id: (_d2 = (_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) == null ? void 0 : _d2.form_id
      };
    });
  }, [(_g = (_f = (_e = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _e.config) == null ? void 0 : _f.basic) == null ? void 0 : _g.appointment_subject]);
  const stateRef = (0, import_react.useRef)(state);
  stateRef.current = state;
  const isWalkIn = (0, import_react.useMemo)(() => {
    var _a2;
    return (0, import_utils.isWalkIn)((_a2 = state.client.value) == null ? void 0 : _a2.id);
  }, [(_h = state.client.value) == null ? void 0 : _h.id]);
  const getClients = async ({
    customer_id,
    customer_ids,
    ...resetParams
  }, returnResult) => {
    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.getClients;
    const withKey = [...(resetParams == null ? void 0 : resetParams.with) || []];
    if (!withKey.includes("contactsInfo")) {
      withKey.push("contactsInfo");
    }
    const data = await api({
      ...resetParams,
      ...resetParams.search ? { num: 10 } : {},
      ...state.isFranchisee ? { franchisee_customer_ids: customer_ids } : { customer_ids },
      ...!state.isFranchisee && !returnResult ? { _config: { abort: true } } : {},
      with: withKey
    });
    const list = ((data == null ? void 0 : data.list) || []).map((d) => {
      var _a3;
      return {
        ...d,
        name: getNickname(d),
        id: d.franchisee_customer_id || d.id,
        form_record: ((_a3 = d.form_record) == null ? void 0 : _a3.map((item) => ({
          ...item,
          ...item.data,
          form_record_id: item.id
        }))) || []
      };
    });
    if (returnResult) {
      return list;
    }
    let _payload = {
      clients: list
    };
    if (!(0, import_utils.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 {
      list.forEach((item) => {
        const index = totalList.findIndex((old) => old.id === item.id);
        if (index > -1) {
          totalList[index] = item;
        } else {
          totalList.push(item);
        }
      });
    }
    _payload.clients = totalList;
    setParams({
      ...params,
      ...resetParams,
      total: (data == null ? void 0 : data.count) || 0
    });
    setGlobalState({
      client: {
        ...stateRef.current.client,
        ..._payload
      }
    });
    isLoadClient = true;
    setLoading(false);
    setLoadLoading(false);
    return {};
  };
  const handleOpenClientModal = (val) => {
    var _a2;
    if (state.disabledEdit) {
      return;
    }
    setClient({
      showModal: true
    });
    getClients({ ...paramsRef.current, search: val || "", skip: 1 });
    (_a2 = modalRef.current) == null ? void 0 : _a2.open();
  };
  const handleViewClient = () => {
    state.action({
      type: "pisell1.handleOpenCustomerModal",
      data: { id: state.client.value.id },
      callback: (data) => {
        var _a2, _b2, _c2;
        if (state.disabledEdit) {
          return;
        }
        if (data === "createBooking") {
          (_c2 = (_b2 = (_a2 = window == null ? void 0 : window.shopApi) == null ? void 0 : _a2.booking) == null ? void 0 : _b2.refreshBookingData) == null ? void 0 : _c2.call(_b2);
          return;
        }
        if (data) {
          handleSelectClient([data]);
        }
        getClients({
          ...state.client.clientsParams,
          search: "",
          customer_id: data == null ? void 0 : data.id,
          skip: 1
        });
      }
    });
  };
  const menus = (0, import_react.useMemo)(() => {
    let list = [
      // { key: "view", label: locales.getText("pisell2.text.view-profile") },
      // { key: "change", label: locales.getText("pisell2.text.change-customer") },
      { key: "remove", label: import_utils2.locales.getText("pisell2.text.remove-customer") }
    ];
    if (state.disabledEdit) {
      list = list.filter((d) => d.key === "view");
    }
    return list;
  }, [state.disabledEdit]);
  const handleRemoveClient = () => {
    if (state.disabledEdit) {
      return;
    }
    handleSelectClient([import_model.walkInData]);
    onRemoveClient == null ? void 0 : onRemoveClient();
  };
  const menuChange = (e) => {
    e.domEvent.stopPropagation();
    let maps = {
      view: handleViewClient,
      change: handleOpenClientModal,
      remove: handleRemoveClient
    };
    maps[e.key]();
  };
  const setClient = (client) => {
    setGlobalState({
      client: {
        ...stateRef.current.client,
        ...client
      }
    });
  };
  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 getNickname = (0, import_react.useCallback)(
    (item) => {
      if ((0, import_utils.isWalkIn)(item == null ? void 0 : item.id)) {
        return import_utils2.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_utils2.locales.localeMap]
  );
  (0, import_react.useEffect)(() => {
    if (state.action) {
      state.action({
        type: "pisell1.registerPlugin",
        data: {
          pluginList: ["CustomerDetailPlugin"]
        }
      });
    }
  }, []);
  const handleSelectClient = 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;
      }
    }
    setClient({
      value: {
        ..._value,
        name: getNickname(_value)
      },
      edit: true
    });
    return new Promise((resolve) => {
      resolve(0);
    });
  };
  const handleCreateItem = (cb) => {
    state.action({
      type: "pisell1.handleOpenAddCustomerModal",
      data: {
        showReceiveAddress: false,
        showAcceptsMarketing: false
      },
      callback: (customer_id, params2) => {
        var _a2, _b2, _c2;
        cb == null ? void 0 : cb();
        setClient({
          clients: [
            ...((_a2 = params2 == null ? void 0 : params2[0]) == null ? void 0 : _a2.customer) ? [{ ...(_b2 = params2 == null ? void 0 : params2[0]) == null ? void 0 : _b2.customer, id: customer_id, form_record: [] }] : [],
            ...((_c2 = state.client) == null ? void 0 : _c2.clients) || []
          ]
        });
      }
    });
  };
  const searchChange = (search) => {
    let _params2 = {
      ...paramsRef.current,
      skip: 1,
      search
    };
    getClients({ ..._params2 });
  };
  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 _params2 = {
            ...params,
            skip: params.skip + 1
          };
          getClients({ ..._params2 });
        }
      },
      import_utils2.locales.getText("pisell2.text.load-more")
    )) : null;
  }, [loadLoading, params, state.client.clients.length]);
  return {
    setClient,
    isWalkIn,
    handleSelectClient,
    menuChange,
    handleViewClient,
    menus,
    handleCreateItem,
    getClients,
    params,
    searchChange,
    loading,
    loadMore,
    handleOpenClientModal,
    getNickname,
    franchiseeLoading
  };
};
var useClientFn_default = useClientFn;
