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/pet/index.tsx
var pet_exports = {};
__export(pet_exports, {
  default: () => pet_default
});
module.exports = __toCommonJS(pet_exports);
var import_User01 = __toESM(require("@pisell/icon/es/User01"));
var import_utils = require("@pisell/utils");
var import_ahooks = require("ahooks");
var import_antd = require("antd");
var import_react = __toESM(require("react"));
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_format = require("../../forms/format");
var import_forms = __toESM(require("../../forms/forms"));
var import_utils2 = require("../../info/service2/utils");
var import_utils3 = require("../../utils");
var import_model = require("../model");
var import_ChangePetModal = __toESM(require("./ChangePetModal"));
var import_index = require("./index.less");
var import_useAddHolder = __toESM(require("../hooks/useAddHolder"));
var import_useGetHolderList = __toESM(require("../hooks/useGetHolderList"));
var import_dayjs = __toESM(require("dayjs"));
var import_date = require("../../../../utils/date");
var defaultParams = {
  skip: 1,
  num: 20,
  total: 0,
  keyword: ""
};
var Pet = (props) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
  const {
    hideTitle,
    addButtonProps,
    handleOpenModal,
    clientChangeNotSetPet,
    previewItemTitleRender
  } = props;
  const [loadLoading, setLoadLoading] = (0, import_react.useState)(false);
  const [loading, setLoading] = (0, import_react.useState)(false);
  let { state, dispatch } = (0, import_react.useContext)(import_model.Context);
  const [valueLoading, setValueLoading] = (0, import_react.useState)(false);
  const context = (0, import_useEngineContext.default)();
  const { isTerminal } = ((_a = context.appHelper) == null ? void 0 : _a.utils) || {};
  const [params, setParams] = (0, import_react.useState)(defaultParams);
  const changePetRef = (0, import_react.useRef)(null);
  state = state || (props == null ? void 0 : props.state);
  dispatch = dispatch || (props == null ? void 0 : props.dispatch);
  const { waiverForm } = (0, import_useAddHolder.default)(state, dispatch);
  const { isMinorAndWaiver } = (0, import_useAddHolder.useFormDataConfig)(state);
  const getHolders = (0, import_useGetHolderList.default)(state, dispatch);
  console.log("waiver", props, state);
  const boardParams = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2;
    return ((_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) || {};
  }, [(_d = (_c = (_b = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _b.config) == null ? void 0 : _c.basic) == null ? void 0 : _d.appointment_subject]);
  const petForm = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2;
    let _holder = (_a2 = state.bookingConfig) == null ? void 0 : _a2.holder;
    if (!_holder) {
      return null;
    }
    return {
      ..._holder,
      ..._holder == null ? void 0 : _holder.form,
      options: [],
      form_id: (_b2 = _holder == null ? void 0 : _holder.form) == null ? void 0 : _b2.id,
      field: (_c2 = _holder == null ? void 0 : _holder.form) == null ? void 0 : _c2.form_field,
      relation_type: "appointment_booking",
      form_record: []
    };
  }, [(_e = state.bookingConfig) == null ? void 0 : _e.holder]);
  const getFormData = async ({ formData }, _params = defaultParams) => {
    var _a2, _b2, _c2, _d2;
    setLoading(true);
    let _list = [];
    const noClient = formData.data_range === "customer" && (0, import_utils3.isWalkIn)((_b2 = (_a2 = state.client) == null ? void 0 : _a2.value) == null ? void 0 : _b2.id);
    if (!noClient) {
      let _values = {
        form_id: boardParams.form_id,
        ..._params,
        source_shop_customer: petForm == null ? void 0 : petForm.is_franchisor
      };
      if (formData.data_range === "customer") {
        _values.customer_id = (_d2 = (_c2 = state.client) == null ? void 0 : _c2.value) == null ? void 0 : _d2.id;
      }
      const data = await state.apis.getPetsData(_values);
      _list = [...formData.options];
      if (_params.skip === 1) {
        _list = (data == null ? void 0 : data.list) || [];
      } else {
        ((data == null ? void 0 : data.list) || []).forEach((item) => {
          const index = _list.findIndex((old) => old.id === item.id);
          if (index > -1) {
            _list[index] = item;
          } else {
            _list.push(item);
          }
        });
      }
      setParams({
        ...params,
        ..._params,
        total: (data == null ? void 0 : data.count) || 0
      });
    } else {
      setParams((o) => ({ ...o, total: 0 }));
    }
    dispatch({
      type: "setPet",
      payload: {
        formData: [
          {
            ...formData,
            options: _list
          }
        ],
        pets: _list
      }
    });
    setLoading(false);
  };
  const setPetOptions = (options) => {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g2;
    const noClient = ((_b2 = (_a2 = state.pet) == null ? void 0 : _a2.formData) == null ? void 0 : _b2[0].data_range) === "customer" && (0, import_utils3.isWalkIn)((_d2 = (_c2 = state.client) == null ? void 0 : _c2.value) == null ? void 0 : _d2.id);
    if (noClient) {
      return;
    }
    dispatch({
      type: "setPet",
      payload: {
        formData: [
          {
            ...(_f2 = (_e2 = state.pet) == null ? void 0 : _e2.formData) == null ? void 0 : _f2[0],
            options
          }
        ],
        pets: options,
        holders: [options[0], ...(_g2 = state.pet) == null ? void 0 : _g2.holders]
      }
    });
  };
  const getForms = async (isUpdateValue = true) => {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g2;
    let values = {
      ...state.pet.value
    };
    let recordIds = [];
    if ((0, import_utils2.isEventBooking)(state)) {
      recordIds = (_a2 = state.bookingDetail) == null ? void 0 : _a2.bookings.list.reduce(
        (acc, cur) => {
          return Array.from(/* @__PURE__ */ new Set([...acc, ...cur.holder.form_record]));
        },
        []
      );
    } else {
      recordIds = ((_c2 = (_b2 = state.bookingDetail) == null ? void 0 : _b2.holder) == null ? void 0 : _c2.form_record) || [];
    }
    let isSetValue = isUpdateValue && values[boardParams == null ? void 0 : boardParams.form_id] === void 0 && (recordIds == null ? void 0 : recordIds.length);
    if (isSetValue) {
      setValueLoading(true);
    }
    try {
      let formData = petForm;
      if (state.renderType === "eventBooking") {
        formData = await state.apis.getForms({
          relation_type: "event_booking_v2",
          relation_id: ((_e2 = (_d2 = state.bookingDetail) == null ? void 0 : _d2.bookings) == null ? void 0 : _e2.id) || 0
          // _config: { useCache: true },
        });
        formData = (formData || []).filter(
          (d) => d.form_id === (boardParams == null ? void 0 : boardParams.form_id)
        )[0];
        formData = {
          ...formData,
          ...formData.form,
          form_id: formData.form.id,
          options: [],
          type: formData.type
        };
      }
      let payload = {
        formData: [formData]
      };
      if (isSetValue) {
        let records = await state.apis.getFormRecords({
          form_record_ids: recordIds,
          with: ["customer"]
        });
        console.log("records", records);
        values[boardParams == null ? void 0 : boardParams.form_id] = (0, import_format.sortFormValues)(
          records,
          (_g2 = (_f2 = state.client) == null ? void 0 : _f2.value) == null ? void 0 : _g2.id
        );
        payload.value = values;
        setValueLoading(false);
      }
      dispatch({
        type: "setPet",
        payload
      });
    } catch (err) {
      setValueLoading(false);
      setLoading(false);
      console.log("form_error", err);
    }
  };
  const updateResult = (res, item) => {
    var _a2, _b2, _c2;
    let cur = [...state.pet.value[petForm.form_id] || []];
    let options = ((_c2 = (_b2 = (_a2 = state.pet) == null ? void 0 : _a2.formData) == null ? void 0 : _b2[0]) == null ? void 0 : _c2.options) || [];
    if (res.type === "delete") {
      const isDay = (0, import_utils2.isDayBooking)(state);
      if (isDay && state.disabledEdit) return cur;
      cur = cur.filter((d) => d.form_record_id !== item.form_record_id);
      addCallback();
      if (isDay) {
        handleDayChange(item);
      }
    } else {
      let obj = {
        customer: item == null ? void 0 : item.customer,
        form_id: petForm == null ? void 0 : petForm.form_id
      };
      for (let item2 of res) {
        obj[item2.key] = item2.value;
      }
      cur = cur.map(
        (d) => d.form_record_id === item.form_record_id ? obj : d
      );
      options = options.map((d) => {
        if (d.form_record_id === item.form_record_id) {
          return obj;
        }
        return d;
      });
    }
    onValueChange({
      values: {
        [petForm.form_id]: cur
      },
      options
    });
  };
  const handleViewItem = (0, import_ahooks.useMemoizedFn)((item) => {
    var _a2, _b2, _c2, _d2;
    let _data = {
      formDataConfig: { ...petForm },
      record: item
    };
    if (petForm.data_range === "customer" && !(0, import_utils3.isWalkIn)((_b2 = (_a2 = state.client) == null ? void 0 : _a2.value) == null ? void 0 : _b2.id)) {
      _data.customerId = (_d2 = (_c2 = state.client) == null ? void 0 : _c2.value) == null ? void 0 : _d2.id;
    }
    state.action({
      type: "pisell1.goCustomFormDetail",
      data: _data,
      callback: (res) => {
        updateResult(res, item);
      }
    });
  });
  const handleEditItem = (0, import_ahooks.useMemoizedFn)((item) => {
    var _a2, _b2, _c2, _d2;
    let _data = {
      formDataConfig: { ...petForm },
      record: item
    };
    if (petForm.data_range === "customer" && !(0, import_utils3.isWalkIn)((_b2 = (_a2 = state.client) == null ? void 0 : _a2.value) == null ? void 0 : _b2.id)) {
      _data.customerId = (_d2 = (_c2 = state.client) == null ? void 0 : _c2.value) == null ? void 0 : _d2.id;
    }
    state.action({
      type: "pisell1.editCustomFormRecord",
      data: _data,
      callback: (res) => {
        console.log(res, "ressss");
        updateResult(res, item);
      }
    });
  });
  const onValueChange = (0, import_ahooks.useMemoizedFn)(
    ({ values, edit = true, options }) => {
      var _a2, _b2;
      const updateObj = {};
      if (options) {
        updateObj.formData = [
          {
            ...(_b2 = (_a2 = state.pet) == null ? void 0 : _a2.formData) == null ? void 0 : _b2[0],
            options
          }
        ];
        updateObj.pets = options;
      }
      dispatch({
        type: "setPet",
        payload: {
          edit,
          value: values,
          ...updateObj
        }
      });
    }
  );
  (0, import_react.useEffect)(() => {
    var _a2, _b2, _c2, _d2;
    if (clientChangeNotSetPet) return;
    let changeFormValuesData = (0, import_format.changeFormValues)({
      values: ((_a2 = state.pet) == null ? void 0 : _a2.value) || {},
      clientId: (_c2 = (_b2 = state.client) == null ? void 0 : _b2.value) == null ? void 0 : _c2.id,
      forms: ((_d2 = state.pet) == null ? void 0 : _d2.formData) || []
    });
    setTimeout(() => {
      dispatch({
        type: "setPet",
        payload: { value: changeFormValuesData }
      });
    });
  }, [(_f = state.client.value) == null ? void 0 : _f.id, clientChangeNotSetPet]);
  const handleUpdateForm = () => {
    if (state.bookingId || state.isEditTicketMode) {
      if (!state.bookingDetail) {
        return;
      }
    }
    if (boardParams.form_id && boardParams.type === "form") {
      getForms(true);
    }
  };
  (0, import_react.useEffect)(() => {
    setTimeout(() => {
      handleUpdateForm();
    }, 10);
  }, [
    state.isEditTicketMode,
    state.bookingId,
    state.bookingDetail,
    boardParams.form_id,
    boardParams.type,
    state.renderType,
    petForm,
    clientChangeNotSetPet ? (_h = (_g = state.client) == null ? void 0 : _g.value) == null ? void 0 : _h.id : void 0
  ]);
  const addCallback = (0, import_ahooks.useMemoizedFn)((_params) => {
    var _a2, _b2;
    let _formData = (_b2 = (_a2 = state.pet) == null ? void 0 : _a2.formData) == null ? void 0 : _b2[0];
    getFormData({ formData: _formData }, _params || params);
  });
  const searchChange = (0, import_ahooks.useMemoizedFn)((keyword) => {
    let _params = {
      ...params,
      skip: 1,
      keyword
    };
    addCallback(_params);
  });
  const loadMore = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2, _d2;
    const show = ((_d2 = (_c2 = (_b2 = (_a2 = state.pet) == null ? void 0 : _a2.formData) == null ? void 0 : _b2[0]) == null ? void 0 : _c2.options) == null ? void 0 : _d2.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
          };
          addCallback(_params);
        }
      },
      import_utils.locales.getText("pisell2.text.load-more")
    )) : null;
  }, [loadLoading, params, (_l = (_k = (_j = (_i = state.pet) == null ? void 0 : _i.formData) == null ? void 0 : _j[0]) == null ? void 0 : _k.options) == null ? void 0 : _l.length]);
  const handleDayChange = (e) => {
    var _a2, _b2;
    const id = e == null ? void 0 : e.form_record_id;
    const service = (_a2 = state.service.value) == null ? void 0 : _a2.filter(
      (item) => item._extend.holder_id === id
    );
    if (id && (service == null ? void 0 : service.length)) {
      changePetRef == null ? void 0 : changePetRef.current.open({
        ids: [id],
        dispatch,
        service: ((_b2 = state.service) == null ? void 0 : _b2.value) || []
      });
    }
  };
  const dayCustomSelect = (0, import_react.useMemo)(() => {
    const isDay = (0, import_utils2.isDayBooking)(state);
    if (isDay) {
      return {
        handleDayChange
      };
    }
    return {};
  }, [state.renderType, state.service.value]);
  const ignoreValidity = (0, import_react.useMemo)(() => {
    var _a2;
    return !((_a2 = petForm == null ? void 0 : petForm.setting) == null ? void 0 : _a2.validity) || petForm.setting.validity.type === "no_expiry";
  }, [petForm]);
  const getExpireStatus = (expiredAt) => {
    if (ignoreValidity || !expiredAt) return null;
    const now = (0, import_dayjs.default)();
    const expireDate = (0, import_dayjs.default)(expiredAt).endOf("day");
    const diffDays = expireDate.diff(now, "day");
    let cnDate = "YYYY-MM-DD";
    let enDate = "DD/MM/YYYY";
    const formattedDate = (0, import_date.formatDate)(expireDate, cnDate, enDate);
    if (now.isAfter(expireDate)) {
      return /* @__PURE__ */ import_react.default.createElement("div", { style: { color: "#999999", fontSize: "14px", lineHeight: "20px" } }, /* @__PURE__ */ import_react.default.createElement(import_antd.Tag, { color: "red", style: { borderRadius: 16, marginRight: 8 } }, import_utils.locales.getText("pisell2.text.status.expired")), import_utils.locales.getText("pisell2.text.validity.expired")(formattedDate));
    }
    if (diffDays < 7) {
      return /* @__PURE__ */ import_react.default.createElement("div", { style: { color: "#FFA940", fontSize: "14px", lineHeight: "20px" } }, import_utils.locales.getText("pisell2.text.validity.expiring_soon")(
        formattedDate
      ));
    }
    return /* @__PURE__ */ import_react.default.createElement("div", { style: { color: "#999999", fontSize: "14px", lineHeight: "20px" } }, import_utils.locales.getText("pisell2.text.validity.valid_through")(formattedDate));
  };
  return (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2;
    let canEdit = true;
    if ((_a2 = petForm == null ? void 0 : petForm.setting) == null ? void 0 : _a2.permissions) {
      const { staff = [] } = ((_b2 = petForm == null ? void 0 : petForm.setting) == null ? void 0 : _b2.permissions) || {};
      canEdit = staff.includes("edit");
    }
    return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-pet-wraps" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Skeleton, { loading: valueLoading, active: true, round: true }, /* @__PURE__ */ import_react.default.createElement(
      import_forms.default,
      {
        isMinorAndWaiver,
        waiverForm,
        hideTitle,
        watch: { value: state.pet.value },
        addCallback: (formDataConfig, data) => {
          var _a3, _b3, _c3;
          setPetOptions([
            { ...data, form_id: formDataConfig == null ? void 0 : formDataConfig.form_id },
            ...((_c3 = (_b3 = (_a3 = state.pet) == null ? void 0 : _a3.formData) == null ? void 0 : _b3[0]) == null ? void 0 : _c3.options) || []
          ]);
        },
        drawerProps: {
          mask: state.drawerMask
        },
        getHolders,
        addCallbackService: addCallback,
        loading: valueLoading,
        forms: state.pet.formData,
        action: state.action,
        modalOpen: state.modalOpen,
        value: state.pet.value,
        onChange: onValueChange,
        client: (_c2 = state.client) == null ? void 0 : _c2.value,
        customSelectProps: {
          loading,
          handleViewItem,
          virtualListHeight: window.innerHeight - 213 - 57 - 16,
          disabled: state.disabledEdit,
          autoFocus: !state.isTerminal,
          closeCallback: () => {
            searchChange("");
          },
          showDropDown: !state.disableEventBookingEdit,
          searchChange,
          searchValue: params.search,
          loadMore,
          filterItem: () => {
            return true;
          },
          handleOpenModal,
          previewItemTitleRender,
          ...dayCustomSelect
        },
        optionRender: (item) => {
          console.log("waiver", petForm, item);
          return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
            import_antd.Avatar,
            {
              className: "pisell-lowcode__booking-pet-list-item-avatar",
              src: item.cover,
              icon: /* @__PURE__ */ import_react.default.createElement(import_User01.default, { className: "pisell-lowcode__booking-pet-list-item-avatar-icon" })
            }
          ), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-pet-list-item-info" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-pet-list-item-info-name" }, item.main_field), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-pet-list-item-info-desc" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "" }, item.key_age)), /* @__PURE__ */ import_react.default.createElement("div", null, getExpireStatus(item.expired_at))), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-pet-list-item-actions" }, /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              className: "pisell-lowcode__booking-pet-list-item-actions-view",
              onClick: (e) => {
                e.preventDefault();
                e.stopPropagation();
                handleViewItem(item);
              }
            },
            import_utils.locales.getText("pisell2.text.view")
          ), canEdit ? /* @__PURE__ */ import_react.default.createElement(
            "div",
            {
              className: "pisell-lowcode__booking-pet-list-item-actions-edit",
              onClick: (e) => {
                e.preventDefault();
                e.stopPropagation();
                handleEditItem(item);
              }
            },
            import_utils.locales.getText("pisell2.text.edit")
          ) : null));
        },
        addButtonProps: {
          style: { margin: 0 },
          disabled: state.disableEventBookingEdit,
          showDisabledMessage: !state.disableEventBookingEdit,
          addCallback: async () => {
            addCallback();
          },
          ...addButtonProps
        }
      }
    )), /* @__PURE__ */ import_react.default.createElement(import_ChangePetModal.default, { ref: changePetRef }));
  }, [
    valueLoading,
    hideTitle,
    state.pet.value,
    state.pet.formData,
    state.action,
    state.modalOpen,
    state.pet.value,
    (_m = state.client) == null ? void 0 : _m.value,
    loading,
    state.disabledEdit,
    state.isTerminal,
    state.disableEventBookingEdit,
    params.search,
    loadMore,
    addButtonProps,
    state.isBookingCreatePage,
    isMinorAndWaiver,
    waiverForm,
    petForm
  ]);
};
var pet_default = Pet;
