import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _asyncToGenerator } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { formatResources } from "../info2/service/addService/utils.js";
import { checkResourcesFormat } from "../components/footer/utils.js";
import useEngineContext from "../../../hooks/useEngineContext.js";
import { request } from "../../../utils/index.js";
import ResourcesV2_default from "../info2/service/editService/ResourcesV2/index.js";
import { createCacheItem, init, updateChildBooking, updateResourceErrors } from "./serve.js";
import locales_default from "./locales.js";
import dayjs from "dayjs";
import React, { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useState } from "react";
import { Button, DatePicker, Form } from "antd";
import { locales } from "@pisell/utils";
import { Iconfont, PisellContainer, Spin as Spin$1 } from "@pisell/materials";
import "./index.less";
//#region src/components/booking/editBookingModal/index.tsx
const EditBookingModal = (props, ref) => {
	const [open, setOpen] = useState(false);
	const [params, setParams] = useState({});
	const [loading, setLoading] = useState(false);
	const [updating, setUpdating] = useState(false);
	const [data, setData] = useState(null);
	const context = useEngineContext();
	const [form] = Form.useForm();
	const useToDate = Form.useWatch("toDate", form);
	const useResource = Form.useWatch("resource", form);
	useImperativeHandle(ref, () => {
		return { open: (params) => {
			console.log("change", params);
			form.resetFields();
			setParams(params);
			setOpen(true);
		} };
	});
	const getInitData = function() {
		var _ref = _asyncToGenerator(function* (params) {
			var _data$fromResource, _data$toResource;
			let mockProps = params;
			const _data = yield init(mockProps);
			setData(_data);
			let _initResourceVal = _data.childrenBooking._extend.resource;
			const fromResourceFormId = (_data$fromResource = _data.fromResource) === null || _data$fromResource === void 0 ? void 0 : _data$fromResource.form_id;
			const _form_id = ((_data$toResource = _data.toResource) === null || _data$toResource === void 0 ? void 0 : _data$toResource.form_id) || fromResourceFormId;
			if (params.fromResourceId !== params.toResourceId && !!_form_id) {
				var _data$toResource2;
				const { list, maps } = formatResources({
					cacheItem: _data.childrenBooking,
					resourcesOrigin: _data.resourcesOrigin
				});
				const currentForm = maps[_form_id];
				const relation_id = (_data$toResource2 = _data.toResource) === null || _data$toResource2 === void 0 ? void 0 : _data$toResource2.id;
				if (currentForm && (relation_id || relation_id === 0)) {
					var _currentForm$renderLi, _currentForm$renderLi2, _currentForm$renderLi3, _currentForm$renderLi4;
					let _targetResource = {
						relation_type: ((_currentForm$renderLi = currentForm.renderListMaps[relation_id]) === null || _currentForm$renderLi === void 0 || (_currentForm$renderLi = _currentForm$renderLi.usable) === null || _currentForm$renderLi === void 0 ? void 0 : _currentForm$renderLi.relation_type) || "form",
						form_id: _form_id,
						relation_id,
						like_status: "common",
						children: (_currentForm$renderLi2 = currentForm.renderListMaps) === null || _currentForm$renderLi2 === void 0 || (_currentForm$renderLi2 = _currentForm$renderLi2[relation_id]) === null || _currentForm$renderLi2 === void 0 ? void 0 : _currentForm$renderLi2.children,
						metadata: _objectSpread2(_objectSpread2({}, (_currentForm$renderLi3 = currentForm.renderListMaps) === null || _currentForm$renderLi3 === void 0 || (_currentForm$renderLi3 = _currentForm$renderLi3[relation_id]) === null || _currentForm$renderLi3 === void 0 ? void 0 : _currentForm$renderLi3.metadata), {}, {
							form_name: currentForm.title,
							resource_name: (_currentForm$renderLi4 = currentForm.renderListMaps[relation_id]) === null || _currentForm$renderLi4 === void 0 ? void 0 : _currentForm$renderLi4.main_field
						})
					};
					if (Array.isArray(_initResourceVal[_form_id])) {
						const _cloned = [..._initResourceVal[_form_id]];
						const _idx = _cloned.findIndex((rs) => {
							var _rs$children;
							return rs.relation_id == params.fromResourceId || ((_rs$children = rs.children) === null || _rs$children === void 0 ? void 0 : _rs$children.find((child) => child.relation_id == params.fromResourceId));
						});
						if (_idx !== -1) if (_cloned.find((_clonedItem) => _clonedItem.relation_id === (_targetResource === null || _targetResource === void 0 ? void 0 : _targetResource.relation_id))) _cloned.splice(_idx, 1);
						else _cloned[_idx] = _targetResource;
						else if (_cloned.findIndex((rs) => {
							return rs.relation_id == (_targetResource === null || _targetResource === void 0 ? void 0 : _targetResource.relation_id);
						}) === -1) _cloned.push(_targetResource);
						_initResourceVal = _objectSpread2(_objectSpread2({}, _initResourceVal), {}, { [_form_id]: _cloned });
					} else _initResourceVal = _objectSpread2(_objectSpread2({}, _initResourceVal), {}, { [_form_id]: [_targetResource] });
				}
			}
			setTimeout(() => {
				form.setFieldsValue({
					resource: _initResourceVal,
					fromDate: [dayjs(`${mockProps.event.start_date} ${mockProps.event.start_time}`), dayjs(`${mockProps.event.end_date} ${mockProps.event.end_time}`)],
					toDate: [dayjs(mockProps.toStartDate), dayjs(mockProps.toEndDate)]
				});
			}, 100);
		});
		return function getInitData(_x) {
			return _ref.apply(this, arguments);
		};
	}();
	useLayoutEffect(() => {
		var _context$appHelper$ut;
		locales.init(locales_default, ((_context$appHelper$ut = context.appHelper.utils) === null || _context$appHelper$ut === void 0 || (_context$appHelper$ut = _context$appHelper$ut.storage) === null || _context$appHelper$ut === void 0 ? void 0 : _context$appHelper$ut.get("umi_locale")) || "en");
		request.setRequest(context.appHelper.utils.request);
	}, []);
	useEffect(() => {
		if (!open) return;
		getInitData(params);
	}, [params, open]);
	const resourceData = useMemo(() => {
		if (!data) return;
		return formatResources({
			cacheItem: data.childrenBooking,
			resourcesOrigin: data.resourcesOrigin
		});
	}, [data]);
	const updateResource = (resource) => {
		form.setFieldValue("resource", resource);
	};
	const originCacheItem = useMemo(() => {
		if (!data) return null;
		const _cacheItem = 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 } = formatResources({
			cacheItem: _cacheItem,
			resourcesOrigin: data.resourcesOrigin
		});
		return _objectSpread2(_objectSpread2({}, _cacheItem), {}, { _data: {
			resources: list,
			resourceMaps: maps
		} });
	}, [data]);
	const cacheItem = useMemo(() => {
		if (!data) return null;
		const _cacheItem = createCacheItem(data.childrenBooking, {
			toDate: useToDate,
			resource: useResource
		});
		console.log("_cacheItem", _cacheItem);
		const { list, maps } = formatResources({
			cacheItem: _cacheItem,
			resourcesOrigin: data.resourcesOrigin
		});
		updateResource(updateResourceErrors(maps, _cacheItem));
		return _objectSpread2(_objectSpread2({}, _cacheItem), {}, { _data: {
			resources: list,
			resourceMaps: maps
		} });
	}, [
		data,
		useToDate,
		useResource
	]);
	const initState = () => {
		setData(null);
		setOpen(false);
		form.resetFields();
	};
	const onCancel = () => {
		initState();
		props === null || props === void 0 || props.onCancel();
	};
	const onOk = function() {
		var _ref2 = _asyncToGenerator(function* () {
			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;
				yield updateChildBooking(order_id, {
					id,
					relation_id,
					like_status,
					relation_type,
					is_all,
					schedule_id,
					sub_type,
					select_date,
					number,
					metadata,
					resources: Object.values(values.resource).reduce((pre, cur) => {
						const newList = 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 || props === void 0 || props.onOk();
			} catch (error) {
				console.error(error);
			}
			setUpdating(false);
		});
		return function onOk() {
			return _ref2.apply(this, arguments);
		};
	}();
	console.log("data", data);
	return /* @__PURE__ */ React.createElement(PisellContainer, {
		renderType: "modal",
		props: {
			title: 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"
		}
	}, /* @__PURE__ */ React.createElement(Spin$1, { spinning: !data }, /* @__PURE__ */ React.createElement(Form, {
		form,
		layout: "vertical"
	}, /* @__PURE__ */ React.createElement("div", { style: {
		display: "flex",
		alignItems: "center",
		gap: 8,
		color: "#1b1b1b",
		fontWeight: "500"
	} }, /* @__PURE__ */ React.createElement(Iconfont, {
		type: "pisell2-copy-03",
		style: { fontSize: 16 }
	}), locales.getText("pisell2.text.booking.time-change")), /* @__PURE__ */ React.createElement(Form.Item, {
		name: "fromDate",
		label: "From"
	}, /* @__PURE__ */ React.createElement(DatePicker.RangePicker, {
		format: "YYYY-MM-DD HH:mm",
		showTime: true,
		presets: [],
		disabled: true,
		style: { width: "100%" },
		size: "large"
	})), /* @__PURE__ */ React.createElement(Form.Item, {
		name: "toDate",
		label: "To"
	}, /* @__PURE__ */ React.createElement(DatePicker.RangePicker, {
		format: "YYYY-MM-DD HH:mm",
		showTime: true,
		presets: [],
		style: { width: "100%" },
		size: "large"
	})), /* @__PURE__ */ React.createElement("div", { style: {
		display: "flex",
		alignItems: "center",
		gap: 8,
		color: "#1b1b1b",
		fontWeight: "500"
	} }, /* @__PURE__ */ React.createElement(Iconfont, {
		type: "pisell2-mark",
		style: { fontSize: 16 }
	}), locales.getText("pisell2.text.booking.resource-change.detail")), data ? /* @__PURE__ */ React.createElement("div", { style: { marginTop: 16 } }, /* @__PURE__ */ React.createElement(Form.Item, { name: "resource" }, /* @__PURE__ */ React.createElement(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__ */ React.createElement("div", {
		className: "",
		style: {
			display: "flex",
			gap: 12
		}
	}, /* @__PURE__ */ React.createElement(Button, {
		onClick: onCancel,
		block: true,
		size: "large",
		style: { borderRadius: 20 }
	}, locales.getText("pisell2.text.cancel")), /* @__PURE__ */ React.createElement(Button, {
		type: "primary",
		onClick: onOk,
		block: true,
		size: "large",
		disabled: !data,
		loading: updating,
		style: { borderRadius: 20 }
	}, locales.getText("pisell2.text.confirm"))));
};
var editBookingModal_default = forwardRef(EditBookingModal);
//#endregion
export { editBookingModal_default as default };
