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/editBookingModal/index.tsx
var editBookingModal_exports = {};
__export(editBookingModal_exports, {
  default: () => editBookingModal_default
});
module.exports = __toCommonJS(editBookingModal_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_materials = require("@pisell/materials");
var import_dayjs = __toESM(require("dayjs"));
var import_utils = require("@pisell/utils");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_utils2 = require("../../../utils");
var import_ResourcesV2 = __toESM(require("../info2/service/editService/ResourcesV2"));
var import_utils3 = require("../info2/service/addService/utils");
var import_serve = require("./serve");
var import_serve2 = require("./serve");
var import_utils4 = require("../../booking/components/footer/utils");
var import_locales = __toESM(require("./locales"));
var import_index = require("./index.less");
var EditBookingModal = (props, ref) => {
  const [open, setOpen] = (0, import_react.useState)(false);
  const [params, setParams] = (0, import_react.useState)({});
  const [loading, setLoading] = (0, import_react.useState)(false);
  const [updating, setUpdating] = (0, import_react.useState)(false);
  const [data, setData] = (0, import_react.useState)(null);
  const context = (0, import_useEngineContext.default)();
  const [form] = import_antd.Form.useForm();
  const useToDate = import_antd.Form.useWatch("toDate", form);
  const useResource = import_antd.Form.useWatch("resource", form);
  const isResourceOnlyMode = (params == null ? void 0 : params.mode) === "resource-only";
  (0, import_react.useImperativeHandle)(ref, () => {
    return {
      open: (params2) => {
        console.log("change", params2);
        form.resetFields();
        setParams(params2);
        setOpen(true);
      }
    };
  });
  const getInitData = async (params2) => {
    var _a, _b, _c, _d, _e;
    let mockProps = params2;
    const _data = await (0, import_serve2.init)(mockProps);
    setData(_data);
    let _initResourceVal = _data.childrenBooking._extend.resource;
    const fromResourceFormId = (_a = _data.fromResource) == null ? void 0 : _a.form_id;
    const toResourceFormId = (_b = _data.toResource) == null ? void 0 : _b.form_id;
    const _form_id = toResourceFormId || fromResourceFormId;
    if (params2.fromResourceId !== params2.toResourceId && !!_form_id) {
      const { list, maps } = (0, import_utils3.formatResources)({
        cacheItem: _data.childrenBooking,
        resourcesOrigin: _data.resourcesOrigin
      });
      const currentForm = maps[_form_id];
      const relation_id = (_c = _data.toResource) == null ? void 0 : _c.id;
      if (currentForm && (relation_id || relation_id === 0)) {
        const targetRenderItem = (_d = currentForm.renderListMaps) == null ? void 0 : _d[relation_id];
        let _targetResource = {
          relation_type: ((_e = targetRenderItem == null ? void 0 : targetRenderItem.usable) == null ? void 0 : _e.relation_type) || "form",
          form_id: _form_id,
          relation_id,
          like_status: "common",
          children: targetRenderItem == null ? void 0 : targetRenderItem.children,
          metadata: {
            ...targetRenderItem == null ? void 0 : targetRenderItem.metadata,
            form_name: currentForm.title,
            resource_name: targetRenderItem == null ? void 0 : targetRenderItem.main_field
          }
        };
        if (Array.isArray(_initResourceVal[_form_id])) {
          const _cloned = [..._initResourceVal[_form_id]];
          const _idx = _cloned.findIndex((rs) => {
            var _a2;
            return rs.relation_id == params2.fromResourceId || ((_a2 = rs.children) == null ? void 0 : _a2.find(
              (child) => child.relation_id == params2.fromResourceId
            ));
          });
          if (_idx !== -1) {
            const _sameResource = _cloned.find(
              (_clonedItem) => _clonedItem.relation_id === (_targetResource == null ? void 0 : _targetResource.relation_id)
            );
            if (_sameResource) {
              _cloned.splice(_idx, 1);
            } else {
              _cloned[_idx] = _targetResource;
            }
          } else {
            const _targetIdx = _cloned.findIndex((rs) => {
              return rs.relation_id == (_targetResource == null ? void 0 : _targetResource.relation_id);
            });
            if (_targetIdx === -1) {
              _cloned.push(_targetResource);
            }
          }
          _initResourceVal = {
            ..._initResourceVal,
            [_form_id]: _cloned
          };
        } else {
          _initResourceVal = {
            ..._initResourceVal,
            [_form_id]: [_targetResource]
          };
        }
      }
    }
    setTimeout(() => {
      form.setFieldsValue({
        resource: _initResourceVal,
        fromDate: [
          (0, import_dayjs.default)(`${mockProps.event.start_date} ${mockProps.event.start_time}`),
          (0, import_dayjs.default)(`${mockProps.event.end_date} ${mockProps.event.end_time}`)
        ],
        toDate: [(0, import_dayjs.default)(mockProps.toStartDate), (0, import_dayjs.default)(mockProps.toEndDate)]
      });
    }, 100);
  };
  (0, import_react.useLayoutEffect)(() => {
    var _a, _b;
    import_utils.locales.init(
      import_locales.default,
      ((_b = (_a = context.appHelper.utils) == null ? void 0 : _a.storage) == null ? void 0 : _b.get("umi_locale")) || "en"
    );
    import_utils2.request.setRequest(context.appHelper.utils.request);
  }, []);
  (0, import_react.useEffect)(() => {
    if (!open) return;
    getInitData(params);
  }, [params, open]);
  const resourceData = (0, import_react.useMemo)(() => {
    if (!data) {
      return;
    }
    return (0, import_utils3.formatResources)({
      cacheItem: data.childrenBooking,
      resourcesOrigin: data.resourcesOrigin
    });
  }, [data]);
  const updateResource = (resource) => {
    form.setFieldValue("resource", resource);
  };
  const originCacheItem = (0, import_react.useMemo)(() => {
    if (!data) {
      return null;
    }
    const _cacheItem = (0, import_serve.createCacheItem)(data.childrenBooking, {
      toDate: [
        data.childrenBooking._extend.start_date,
        data.childrenBooking._extend.end_date
      ],
      resource: data.childrenBooking._extend.resource
    });
    console.log("_origin_cacheItem", _cacheItem);
    const { list, maps } = (0, import_utils3.formatResources)({
      cacheItem: _cacheItem,
      resourcesOrigin: data.resourcesOrigin
    });
    return {
      ..._cacheItem,
      _data: {
        resources: list,
        resourceMaps: maps
      }
    };
  }, [data]);
  const cacheItem = (0, import_react.useMemo)(() => {
    if (!data) {
      return null;
    }
    const _cacheItem = (0, import_serve.createCacheItem)(data.childrenBooking, {
      toDate: useToDate,
      resource: useResource
    });
    console.log("_cacheItem", _cacheItem);
    const { list, maps } = (0, import_utils3.formatResources)({
      cacheItem: _cacheItem,
      resourcesOrigin: data.resourcesOrigin
    });
    const resource = (0, import_serve2.updateResourceErrors)(maps, _cacheItem);
    updateResource(resource);
    return {
      ..._cacheItem,
      _data: {
        resources: list,
        resourceMaps: maps
      }
    };
  }, [data, useToDate, useResource]);
  const initState = () => {
    setData(null);
    setOpen(false);
    form.resetFields();
  };
  const onCancel = () => {
    initState();
    props == null ? void 0 : props.onCancel();
  };
  const onOk = async () => {
    const values = form.getFieldsValue();
    setUpdating(true);
    try {
      const { _extend, order_id } = data.childrenBooking;
      const start_date = values.toDate[0].format("YYYY-MM-DD");
      const start_time = values.toDate[0].format("HH:mm");
      const end_date = values.toDate[1].format("YYYY-MM-DD");
      const end_time = values.toDate[1].format("HH:mm");
      console.log("extend data", _extend);
      const {
        id,
        relation_id,
        like_status,
        relation_type,
        is_all,
        schedule_id,
        sub_type,
        select_date,
        number,
        metadata
      } = _extend;
      await (0, import_serve.updateChildBooking)(order_id, {
        id,
        relation_id,
        like_status,
        relation_type,
        is_all,
        schedule_id,
        sub_type: sub_type || "minutes",
        select_date,
        number,
        metadata,
        resources: Object.values(values.resource).reduce(
          (pre, cur) => {
            const newList = (0, import_utils4.checkResourcesFormat)(cur, cacheItem);
            pre = pre.concat(newList);
            return pre;
          },
          []
        ),
        start_date,
        start_time,
        end_date,
        end_time,
        duration: values.toDate[1].diff(values.toDate[0], "minutes")
      });
      initState();
      props == null ? void 0 : props.onOk();
    } catch (error) {
      console.error(error);
    }
    setUpdating(false);
  };
  console.log("data", data);
  return /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellContainer,
    {
      renderType: "modal",
      props: {
        title: import_utils.locales.getText("pisell2.text.booking.confirm-changes"),
        open,
        cancelVisible: false,
        bodyStyle: {
          padding: 24
        },
        width: 680,
        onCancel,
        okButtonProps: {},
        onOk: () => {
        },
        footer: null,
        className: "pisell-edit-booking-modal",
        wrapClassName: "pisell-edit-booking-modal-wrap",
        zIndex: 1001
      }
    },
    /* @__PURE__ */ import_react.default.createElement(import_materials.Spin, { spinning: !data }, /* @__PURE__ */ import_react.default.createElement(import_antd.Form, { form, layout: "vertical" }, !isResourceOnlyMode ? /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        style: {
          display: "flex",
          alignItems: "center",
          gap: 8,
          color: "#1b1b1b",
          fontWeight: "500"
        }
      },
      /* @__PURE__ */ import_react.default.createElement(import_materials.Iconfont, { type: "pisell2-copy-03", style: { fontSize: 16 } }),
      import_utils.locales.getText("pisell2.text.booking.time-change")
    ) : null, /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { name: "fromDate", label: isResourceOnlyMode ? void 0 : "From" }, /* @__PURE__ */ import_react.default.createElement(
      import_antd.DatePicker.RangePicker,
      {
        format: "YYYY-MM-DD HH:mm",
        showTime: true,
        presets: [],
        disabled: true,
        style: { width: "100%" },
        size: "large"
      }
    )), /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { name: "toDate", label: "To", hidden: isResourceOnlyMode }, /* @__PURE__ */ import_react.default.createElement(
      import_antd.DatePicker.RangePicker,
      {
        format: "YYYY-MM-DD HH:mm",
        showTime: true,
        presets: [],
        style: { width: "100%" },
        size: "large"
      }
    )), /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        style: {
          display: "flex",
          alignItems: "center",
          gap: 8,
          color: "#1b1b1b",
          fontWeight: "500"
        }
      },
      /* @__PURE__ */ import_react.default.createElement(import_materials.Iconfont, { type: "pisell2-mark", style: { fontSize: 16 } }),
      import_utils.locales.getText("pisell2.text.booking.resource-change.detail")
    ), data ? /* @__PURE__ */ import_react.default.createElement("div", { style: { marginTop: 16 } }, /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { name: "resource" }, /* @__PURE__ */ import_react.default.createElement(
      import_ResourcesV2.default,
      {
        state: {},
        resourceData,
        cacheItem,
        getCurrentCacheItem: () => {
          return cacheItem;
        },
        config: {
          autoAllocation: false,
          labelCol: { span: 24 },
          resourceErrorIcon: true,
          disabled: false
        },
        originCacheItem,
        originValue: originCacheItem._extend.resource
      }
    ))) : null)),
    /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: "",
        style: {
          display: "flex",
          gap: 12
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Button,
        {
          onClick: onCancel,
          block: true,
          size: "large",
          style: {
            borderRadius: 20
          }
        },
        import_utils.locales.getText("pisell2.text.cancel")
      ),
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Button,
        {
          type: "primary",
          onClick: onOk,
          block: true,
          size: "large",
          disabled: !data,
          loading: updating,
          style: { borderRadius: 20 }
        },
        import_utils.locales.getText("pisell2.text.confirm")
      )
    )
  );
};
var editBookingModal_default = (0, import_react.forwardRef)(EditBookingModal);
