var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/appointmentBooking/utils.ts
var utils_exports = {};
__export(utils_exports, {
  Toast: () => Toast,
  checkAndGoNext: () => checkAndGoNext,
  checkAndMarkCartRenderError: () => checkAndMarkCartRenderError,
  checkHasFormStep: () => checkHasFormStep,
  currentAppointmentBoard: () => currentAppointmentBoard,
  currentRenderLists: () => currentRenderLists,
  formatCarts: () => formatCarts,
  formatCartsResources: () => formatCartsResources,
  formatCurrentUser: () => formatCurrentUser,
  formatCustomer: () => formatCustomer,
  formatForms: () => formatForms,
  formatGuest: () => formatGuest,
  formatHolder: () => formatHolder,
  getCartCurrentResourceData: () => getCartCurrentResourceData,
  getCurrentBoard: () => getCurrentBoard,
  getCustomer: () => getCustomer,
  getFormInsertBeforeKey: () => getFormInsertBeforeKey,
  getMeAccount: () => getMeAccount,
  getMultiResources: () => getMultiResources,
  getPunctuationMark: () => getPunctuationMark,
  getResourceTitle: () => getResourceTitle,
  hasResourceFormId: () => hasResourceFormId,
  openForm: () => openForm,
  sortResources: () => sortResources,
  updateBookingFormStorage: () => updateBookingFormStorage,
  updateCartResources: () => updateCartResources,
  updateLists: () => updateLists
});
module.exports = __toCommonJS(utils_exports);
var import_utils = require("@pisell/utils");
var import_materials = require("@pisell/materials");
var formatHolder = (data) => {
  return data == null ? void 0 : data.map((d) => {
    return {
      ...d,
      key: d == null ? void 0 : d.id,
      label: d == null ? void 0 : d.username,
      name: d == null ? void 0 : d.username
    };
  });
};
var formatGuest = (data, products) => {
  return data == null ? void 0 : data.map((d) => {
    const children = products.filter((p) => (p == null ? void 0 : p.holder_id) === (d == null ? void 0 : d.id)).map((p) => {
      return {
        name: p == null ? void 0 : p.name
      };
    });
    return {
      ...d,
      key: d == null ? void 0 : d.id,
      name: d == null ? void 0 : d.username,
      children: children || []
    };
  });
};
var formatCartsResources = (carts, resources, setPolicyIds) => {
  try {
    let policyIds = [];
    let newCarts = carts == null ? void 0 : carts.map((d) => {
      var _a, _b;
      const currentResource = resources == null ? void 0 : resources.find((r) => (d == null ? void 0 : d._id) === (r == null ? void 0 : r._id));
      let currentResources = (_b = (_a = currentResource == null ? void 0 : currentResource.resources) == null ? void 0 : _a[0]) == null ? void 0 : _b.renderList;
      const resourceId = d == null ? void 0 : d.resource_id;
      const foundResource = currentResources == null ? void 0 : currentResources.find((resource) => resource.id === resourceId);
      if (foundResource == null ? void 0 : foundResource.resource_form_id) {
        return {
          ...d,
          resource_form_id: foundResource == null ? void 0 : foundResource.resource_form_id
        };
      } else if ((foundResource == null ? void 0 : foundResource.policy_id) && !policyIds.includes(foundResource == null ? void 0 : foundResource.policy_id)) {
        policyIds.push(foundResource == null ? void 0 : foundResource.policy_id);
      }
      return false;
    }).filter(Boolean);
    setPolicyIds(policyIds);
    return newCarts || [];
  } catch (error) {
    console.log(error, "formatCarts");
    return [];
  }
};
var formatCarts = (data, resources, utils, accountLists) => {
  var _a;
  try {
    if (!utils || !(data == null ? void 0 : data.length)) return [];
    const locale = ((_a = utils == null ? void 0 : utils.storage) == null ? void 0 : _a.get("umi_locale")) || "en-US";
    const symbol = (utils == null ? void 0 : utils.getSymbolic()) || "$";
    const newCarts = data == null ? void 0 : data.map((d) => {
      var _a2, _b, _c;
      const currentResource = resources == null ? void 0 : resources.find((r) => (d == null ? void 0 : d._id) === (r == null ? void 0 : r._id));
      let currentResources = (_b = (_a2 = currentResource == null ? void 0 : currentResource.resources) == null ? void 0 : _a2[0]) == null ? void 0 : _b.renderList;
      currentResources = currentResources == null ? void 0 : currentResources.map((d2) => {
        return {
          ...d2,
          label: (d2 == null ? void 0 : d2.main_field) || (d2 == null ? void 0 : d2.id)
        };
      });
      return {
        ...d,
        format: ["HH:mm", "HH:mm"],
        show_time: true,
        duration_type: ((_c = d == null ? void 0 : d.duration) == null ? void 0 : _c.type) || "minutes",
        locale,
        symbol,
        resources: currentResources,
        is_hide_like: true,
        holders: formatHolder(accountLists),
        allowClearHolder: true,
        allowClearResource: true
      };
    });
    return newCarts || [];
  } catch (error) {
    console.log(error, "formatCarts");
    return [];
  }
};
var sortResources = (resources, resourceSort) => {
  try {
    let sortedResources = resources.sort((a, b) => {
      const aIndex = resourceSort.indexOf(a.code);
      const bIndex = resourceSort.indexOf(b.code);
      return aIndex - bIndex;
    });
    sortedResources = sortedResources.map((resource) => {
      var _a;
      const renderList = (_a = resource == null ? void 0 : resource.renderList) == null ? void 0 : _a.map((d) => {
        var _a2, _b;
        return {
          ...d,
          image: (_b = (_a2 = d == null ? void 0 : d.cover) == null ? void 0 : _a2[0]) == null ? void 0 : _b.url,
          title: d == null ? void 0 : d.main_field,
          subtitle: d == null ? void 0 : d.sub_field
        };
      });
      return {
        ...resource,
        renderList
      };
    });
    return sortedResources || [];
  } catch (error) {
    console.log(error, "wh2222");
  }
};
var getMeAccount = (val) => {
  return val == null ? void 0 : val.find((d) => !(d == null ? void 0 : d.isGuest));
};
var getCustomer = (utils) => {
  var _a, _b;
  try {
    if (!utils) return;
    let userInfo = (_b = (_a = utils.getStore().getState()) == null ? void 0 : _a.global) == null ? void 0 : _b.userInfo;
    const localUserInfo = JSON.parse(utils.storage.get("customer") || "{}");
    userInfo = (userInfo == null ? void 0 : userInfo.id) ? userInfo : localUserInfo;
    return userInfo;
  } catch (error) {
    console.log(`getCustomer ${error}`);
  }
};
var formatCustomer = (val) => {
  let currentUserName = `${(val == null ? void 0 : val.first_name) || ""}${(val == null ? void 0 : val.last_name) ? ` ${val == null ? void 0 : val.last_name}` : ""}`;
  currentUserName = currentUserName || (val == null ? void 0 : val.nickname) || "Me";
  return {
    id: (val == null ? void 0 : val.id) || (0, import_utils.getUniqueId)(),
    username: currentUserName
  };
};
var formatCurrentUser = (utils) => {
  let userInfo = getCustomer(utils);
  const customer = formatCustomer(userInfo);
  return customer;
};
var getPunctuationMark = (index, totalLength, isEn) => {
  const isLastItem = index === totalLength - 1;
  const isSecondLastItem = index === totalLength - 2;
  if (isLastItem) {
    return isEn ? "." : "。";
  }
  if (isSecondLastItem) {
    return import_utils.locales.getText("pisell2.appointment.deposit.and");
  }
  return isEn ? ", " : "、";
};
var hasResourceFormId = (array) => {
  try {
    if (!(array == null ? void 0 : array.length)) {
      return false;
    }
    return array.some((item) => {
      var _a;
      const resourceId = item.resource_id;
      const foundResource = (_a = item == null ? void 0 : item.resources) == null ? void 0 : _a.find((resource) => resource.id === resourceId);
      return foundResource == null ? void 0 : foundResource.resource_form_id;
    });
  } catch (error) {
    console.log(error, "hasResourceFormId");
  }
};
var formatForms = (array) => {
  try {
    if (!(array == null ? void 0 : array.length)) {
      return [];
    }
    const mappedResources = array.map((item) => {
      var _a;
      const foundResource = (_a = item == null ? void 0 : item.resources) == null ? void 0 : _a.find((resource) => resource.id === item.resource_id);
      if (foundResource && ((foundResource == null ? void 0 : foundResource.resource_form_id) || (foundResource == null ? void 0 : foundResource.policy_id))) {
        return {
          form_id: foundResource.resource_form_id,
          policy_id: foundResource.policy_id,
          id: foundResource == null ? void 0 : foundResource.id,
          cart_id: item == null ? void 0 : item._id
        };
      }
      return null;
    }).filter(Boolean);
    return mappedResources;
  } catch (error) {
    console.log(error, "hasResourceFormId");
    return [];
  }
};
var openForm = ({ form_id, title, callback, utils }) => {
  utils.action({
    type: "pisell1.form",
    data: {
      form_id,
      form_title: title,
      isV2API: true
    },
    callback
  });
};
function updateLists(list, key, value, newData) {
  const idx = list.findIndex((item) => item[key] === value);
  if (idx > -1) {
    const updated = { ...list[idx], ...newData };
    const newList = [...list];
    newList[idx] = updated;
    return newList;
  } else {
    return [...list, { ...newData, [key]: value }];
  }
}
var updateBookingFormStorage = (bookingForm, id, newData) => {
  const newBookingForm = { ...bookingForm };
  if (newBookingForm[id]) {
    newBookingForm[id] = { ...newBookingForm[id], ...newData };
  } else {
    newBookingForm[id] = { ...newData };
  }
  return newBookingForm;
};
var Toast = (text) => {
  try {
    (0, import_materials.PisellToast)({
      content: text
    });
  } catch (error) {
    window == null ? void 0 : window.alert(text);
  }
};
var checkHasFormStep = ({ setIsErrorHolder, nextStep, isSkip, checkHolder, checkAccount, carts, setCarts, hasResourceFormId: hasResourceFormId2, currentStep, stepList, appointmentBooking, locales: locales2, isLogin, openLoginModal, isFormSubject, utils, accountLists, getHolders }) => {
  var _a, _b, _c;
  let isNext = false;
  const stepLists = (_c = (_b = (_a = appointmentBooking == null ? void 0 : appointmentBooking.store) == null ? void 0 : _a.step) == null ? void 0 : _b.store) == null ? void 0 : _c.stepList;
};
var getCartCurrentResourceData = (cart, currentKey, resources) => {
  var _a, _b, _c, _d, _e, _f, _g;
  try {
    const currentFormId = (_b = (_a = currentKey == null ? void 0 : currentKey.split("_@")) == null ? void 0 : _a[1]) == null ? void 0 : _b.split("-");
    const form_id = Number((currentFormId == null ? void 0 : currentFormId[0]) || ((_e = (_d = (_c = resources == null ? void 0 : resources[0]) == null ? void 0 : _c.resources) == null ? void 0 : _d[0]) == null ? void 0 : _e.id));
    if (!form_id || !resources.length) return;
    const cartId = cart._id;
    const cartOriginResources = ((_f = cart._origin) == null ? void 0 : _f.resources) || [];
    const resourceData = resources.find((r) => String(r._id) === String(cartId));
    if (!resourceData) return;
    let resourceItem = (resourceData.resources || []).find((r) => Number(r.id) === form_id);
    if (!resourceItem) return;
    resourceItem = {
      ...resourceItem,
      renderList: ((_g = resourceItem == null ? void 0 : resourceItem.renderList) == null ? void 0 : _g.map((r) => {
        return {
          ...r,
          label: (r == null ? void 0 : r.main_field) || (r == null ? void 0 : r.id)
        };
      })) || []
    };
    const cartResource = cartOriginResources.find((r) => Number(r.form_id) === form_id);
    const renderId = (cartResource == null ? void 0 : cartResource.id) || 0;
    const renderItem = ((resourceItem == null ? void 0 : resourceItem.renderList) || []).find((r) => Number(r == null ? void 0 : r.id) === Number(renderId));
    return {
      cartItem: cart,
      resourceItem: {
        ...resourceItem,
        originRenderLists: resourceData.resources
      },
      renderItem
    };
  } catch (error) {
    return cart;
  }
};
var getMultiResources = (cart, currentSelectedResource, currentKey) => {
  var _a;
  const resourceItem = currentSelectedResource == null ? void 0 : currentSelectedResource.resourceItem;
  if (!resourceItem || !cart) return [];
  const isCurrentResourceStep = currentKey.startsWith("select-resource");
  let resources = ((_a = cart == null ? void 0 : cart._origin) == null ? void 0 : _a.resources) || [];
  let selectedResources = isCurrentResourceStep ? resources.filter((r) => (r == null ? void 0 : r.form_id) !== (resourceItem == null ? void 0 : resourceItem.form_id)) : resources;
  selectedResources = selectedResources.map((r) => {
    return {
      ...r,
      name: (r == null ? void 0 : r.main_field) || (r == null ? void 0 : r.id),
      isShowChangeResource: false,
      is_hide_like: true
    };
  });
  let currentResources = resources.find((r) => (r == null ? void 0 : r.form_id) === (resourceItem == null ? void 0 : resourceItem.form_id));
  const errorTip = (currentSelectedResource == null ? void 0 : currentSelectedResource.errorTip) || {};
  let currentResource = isCurrentResourceStep ? [{
    allowClearResource: true,
    lists: (resourceItem == null ? void 0 : resourceItem.renderList) || [],
    is_hide_like: true,
    id: currentResources == null ? void 0 : currentResources.id,
    isErrorResource: (errorTip == null ? void 0 : errorTip.isErrorResource) || false,
    resourceErrorText: (errorTip == null ? void 0 : errorTip.resourceErrorText) || ""
  }] : [];
  return [...selectedResources, ...currentResource];
};
var getCurrentBoard = (appointmentBooking, code) => {
  var _a;
  const { appointmentBoard } = (appointmentBooking == null ? void 0 : appointmentBooking.otherParams) || {};
  const resourceConfig = (_a = appointmentBoard == null ? void 0 : appointmentBoard.resource_tab) == null ? void 0 : _a[code];
  return resourceConfig;
};
var getResourceTitle = (appointmentBooking, code, utils, originResource) => {
  const resourceConfig = getCurrentBoard(appointmentBooking, code);
  let name = "";
  if (resourceConfig == null ? void 0 : resourceConfig.resource_type_title) {
    name = utils.translation(resourceConfig == null ? void 0 : resourceConfig.resource_type_title);
  } else {
    name = (originResource == null ? void 0 : originResource.title) || "";
  }
  return name;
};
var checkAndMarkCartRenderError = (carts, appointmentBooking, utils) => {
  try {
    let hasError = false;
    carts = carts.filter((n) => !appointmentBooking.isTargetCartIdNormalProduct(n._id));
    const updatedCartList = carts == null ? void 0 : carts.map((cart) => {
      const currentResource = cart == null ? void 0 : cart.currentSelectedResource;
      if (!(currentResource == null ? void 0 : currentResource.renderItem)) {
        hasError = true;
        const resourceItem = (currentResource == null ? void 0 : currentResource.resourceItem) || {};
        const name = getResourceTitle(appointmentBooking, resourceItem == null ? void 0 : resourceItem.code, utils, resourceItem);
        return {
          ...cart,
          currentSelectedResource: {
            ...currentResource,
            errorTip: {
              isErrorResource: true,
              resourceErrorText: name
            }
          }
        };
      }
      return cart;
    });
    return {
      hasError,
      updatedCartList
    };
  } catch (error) {
    console.error(error);
    return {};
  }
};
var getFormInsertBeforeKey = (currentKey, stepList) => {
  const isFirstResource = currentKey === "select-resource";
  const timeStep = stepList.find((item) => item.key.startsWith("select-time"));
  if (isFirstResource && timeStep) {
    return timeStep.key;
  } else {
    return currentKey;
  }
};
var checkAndGoNext = (isFormSubject, checkAccount, carts) => {
  let hasError = false;
  let updatedCartList = [...carts];
  if (isFormSubject && !checkAccount("holder")) {
    updatedCartList = carts == null ? void 0 : carts.map((item) => {
      if (!(item == null ? void 0 : item.holder_id)) {
        hasError = true;
        return {
          ...item,
          isErrorHolder: true
        };
      }
      return item;
    });
  }
  return {
    hasError,
    updatedCartList
  };
};
var currentAppointmentBoard = (currentKey, resources, appointmentBooking) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
  try {
    const currentStepKey = (_b = (_a = currentKey == null ? void 0 : currentKey.split("_@")) == null ? void 0 : _a[1]) == null ? void 0 : _b.split("-");
    const form_id = Number((currentStepKey == null ? void 0 : currentStepKey[0]) || ((_e = (_d = (_c = resources == null ? void 0 : resources[0]) == null ? void 0 : _c.resources) == null ? void 0 : _d[0]) == null ? void 0 : _e.id));
    const form_code = (currentStepKey == null ? void 0 : currentStepKey[1]) || ((_h = (_g = (_f = resources == null ? void 0 : resources[0]) == null ? void 0 : _f.resources) == null ? void 0 : _g[0]) == null ? void 0 : _h.code);
    const cart_id = currentStepKey == null ? void 0 : currentStepKey[2];
    const resource_form_id = currentStepKey == null ? void 0 : currentStepKey[3];
    const policy_id = currentStepKey == null ? void 0 : currentStepKey[4];
    const resource_tab = (_j = (_i = appointmentBooking == null ? void 0 : appointmentBooking.otherParams) == null ? void 0 : _i.appointmentBoard) == null ? void 0 : _j.resource_tab;
    const config = resource_tab == null ? void 0 : resource_tab[form_code];
    const isRequired = (config == null ? void 0 : config.customer_resource) === "customer_resource_required";
    const isSystem = (config == null ? void 0 : config.customer_resource) === "customer_resource_system";
    const isSkip = (config == null ? void 0 : config.hasOwnProperty("resource_skip_select")) ? !!(config == null ? void 0 : config.resource_skip_select) : true;
    return {
      isRequired,
      isSystem,
      isSkip,
      form_id,
      form_code,
      cart_id,
      resource_form_id,
      policy_id
    };
  } catch (error) {
    return {};
  }
};
var currentRenderLists = (resources, code) => {
  var _a;
  if (!(resources == null ? void 0 : resources.length) || !code) return [];
  const _resources = ((_a = resources == null ? void 0 : resources[0]) == null ? void 0 : _a.resources) || [];
  const currentResource = _resources == null ? void 0 : _resources.find((item) => item.code === code);
  return (currentResource == null ? void 0 : currentResource.renderList) || [];
};
var updateCartResources = (item, value, currentSelectedResources) => {
  var _a, _b, _c;
  let newResource = [];
  let resources = ((_a = item == null ? void 0 : item._origin) == null ? void 0 : _a.resources) || [];
  if (value) {
    const currentResourceIndex = resources.findIndex(
      (item2) => item2.form_id === value.form_id
    );
    if (currentResourceIndex > -1) {
      newResource = resources.map(
        (item2) => item2.form_id === value.form_id ? value : item2
      );
    } else {
      newResource = [...resources, value];
    }
  } else {
    const currentResource = currentSelectedResources == null ? void 0 : currentSelectedResources.find(
      (resource) => (resource == null ? void 0 : resource._id) === (item == null ? void 0 : item._id)
    );
    const form_id = (_c = (_b = currentResource == null ? void 0 : currentResource.currentSelectedResource) == null ? void 0 : _b.renderItem) == null ? void 0 : _c.form_id;
    newResource = resources.filter((item2) => item2.form_id !== form_id);
  }
  return newResource || [];
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  Toast,
  checkAndGoNext,
  checkAndMarkCartRenderError,
  checkHasFormStep,
  currentAppointmentBoard,
  currentRenderLists,
  formatCarts,
  formatCartsResources,
  formatCurrentUser,
  formatCustomer,
  formatForms,
  formatGuest,
  formatHolder,
  getCartCurrentResourceData,
  getCurrentBoard,
  getCustomer,
  getFormInsertBeforeKey,
  getMeAccount,
  getMultiResources,
  getPunctuationMark,
  getResourceTitle,
  hasResourceFormId,
  openForm,
  sortResources,
  updateBookingFormStorage,
  updateCartResources,
  updateLists
});
