import { getText } from "../../locales/index.js";
import { _objectSpread2 } from "../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import useEngineContext from "../../hooks/useEngineContext.js";
import table_default from "../table/index.js";
import Price from "./fields/Price/index.js";
import fields_default from "./fields/index.js";
import React, { useCallback, useMemo, useState } from "react";
import { Button, Form, Modal, Popover, Select, Tooltip } from "antd";
import { useDebounceFn } from "ahooks";
import "./index.less";
//#region src/components/batch-editor/index.tsx
const BatchEditor = (props) => {
	var _context$appHelper, _store$getState, _otherTableProps$filt;
	const { columns, dataSource = [], onChange, rowKey, otherTableProps } = props;
	const [form] = Form.useForm();
	const [openModal, setOpenModal] = useState(false);
	const [selectList, setSelectList] = useState([]);
	const { store } = ((_context$appHelper = useEngineContext().appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	const symbol = (store === null || store === void 0 || (_store$getState = store.getState) === null || _store$getState === void 0 || (_store$getState = _store$getState.call(store)) === null || _store$getState === void 0 || (_store$getState = _store$getState.global) === null || _store$getState === void 0 ? void 0 : _store$getState.symbol) || "$";
	/**
	* @title: 渲染column
	* @description:
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-06-17 13:21
	*/
	const renderColumnItem = useCallback((_item) => {
		return (text, record) => {
			if (!_item.type) {
				const Com = fields_default["text"];
				return /* @__PURE__ */ React.createElement("div", { className: "editor-item" }, /* @__PURE__ */ React.createElement(Com, null, text));
			}
			if ((record.disabledList || []).includes(_item.dataIndex)) return /* @__PURE__ */ React.createElement("div", {
				className: "editor-item",
				style: { padding: `0 11px` }
			}, /* @__PURE__ */ React.createElement(Tooltip, { overlay: (record === null || record === void 0 ? void 0 : record.disabledTexts) ? (record === null || record === void 0 ? void 0 : record.disabledTexts[_item.dataIndex]) || text : text }, /* @__PURE__ */ React.createElement("div", { className: "name" }, (record === null || record === void 0 ? void 0 : record.disabledTexts) ? (record === null || record === void 0 ? void 0 : record.disabledTexts[_item.dataIndex]) || text : text)));
			const Com = fields_default[_item.type];
			if (Com) return /* @__PURE__ */ React.createElement("div", { className: "editor-item" }, /* @__PURE__ */ React.createElement(Com, _objectSpread2(_objectSpread2({
				status: record.status,
				value: text
			}, _item.componentProps), {}, {
				placeholder: _item.placeholder || record[_item.dataIndex + "placeholder"],
				symbol,
				onChange: (e) => {
					handleChange(e, _item.dataIndex, record[rowKey]);
				}
			})));
			return /* @__PURE__ */ React.createElement("div", { className: "editor-item" }, "-");
		};
	}, [
		dataSource,
		rowKey,
		columns
	]);
	/**
	* dataSource 的返回事件
	* @param newDataSource
	*/
	const _onChange = (newDataSource) => {
		onChange === null || onChange === void 0 || onChange(newDataSource);
	};
	/**
	* @title: 编辑某个字段
	* @description:
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-06-17 13:22
	*/
	const handleChange = (val, key, id) => {
		let _dataSource = JSON.parse(JSON.stringify(dataSource));
		let fn = (_list) => {
			for (let d of _list) {
				if (d[rowKey] === id) {
					d[key] = val;
					break;
				}
				if (d.children && d.children.length) fn(d.children);
			}
		};
		fn(_dataSource || []);
		_onChange(_dataSource);
	};
	/**
	* @title: 批量编辑
	* @description:
	* @param {any} val
	* @param {any} key
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-06-17 13:22
	*/
	const handleBatchEditChange = (val, key) => {
		let _dataSource = JSON.parse(JSON.stringify(dataSource));
		let fn = (_list) => {
			for (let d of _list) {
				if (selectList.includes(d[rowKey]) && !(d.disabledList || []).includes(key)) d[key] = val;
				if (d.children && d.children.length) fn(d.children);
			}
		};
		fn(_dataSource || []);
		_onChange(_dataSource);
	};
	/**
	* @title: 删除record
	* @description:
	* @param {any} ids
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-06-17 13:22
	*/
	const handleRemove = (ids) => {
		let _dataSource = JSON.parse(JSON.stringify(dataSource));
		if (_dataSource.some((d) => ids.includes(d[rowKey]))) _dataSource = _dataSource.filter((d) => !ids.includes(d[rowKey]));
		else _dataSource.forEach((d) => {
			if (d.children) d.children = d.children.filter((d) => !ids.includes(d[rowKey]));
		});
		_onChange(_dataSource);
	};
	useDebounceFn((_dataSource) => {
		_onChange(_dataSource);
	}, { wait: 300 });
	const renderPopoverContent = useCallback((_item) => {
		const Com = fields_default[_item.type];
		let val;
		return /* @__PURE__ */ React.createElement("div", { className: "batch-popover-content" }, /* @__PURE__ */ React.createElement("div", { className: "editor-item" }, /* @__PURE__ */ React.createElement(Com, {
			symbol,
			onBlur: () => {
				if (val !== void 0) handleBatchEditChange(val, _item.dataIndex);
			},
			onChange: (e) => {
				val = e;
			}
		})));
	}, [dataSource, selectList]);
	/**
	* @title: 渲染表格列标题
	* @description:
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-06-17 13:23
	*/
	const renderColumnTitle = useCallback((item) => {
		return /* @__PURE__ */ React.createElement("div", { className: "column-title" }, /* @__PURE__ */ React.createElement("span", null, item.title), selectList.length && item.batchEdit ? /* @__PURE__ */ React.createElement(Popover, {
			destroyTooltipOnHide: true,
			trigger: ["click"],
			placement: "bottom",
			title: `${getText("batch-editor-batch-edit")}: ${item.title}`,
			content: renderPopoverContent(item)
		}, /* @__PURE__ */ React.createElement("a", { style: { marginLeft: 4 } }, getText("batch-editor-batch-edit"))) : null);
	}, [
		dataSource,
		rowKey,
		selectList
	]);
	/**
	* @title: 表格列
	* @description:
	* @param {*} useMemo
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-06-17 13:23
	*/
	const _columns = useMemo(() => {
		return columns.filter((d) => !d.hide).map((d) => {
			return _objectSpread2(_objectSpread2({}, d), {}, {
				titleStr: d.title,
				title: renderColumnTitle(d),
				render: renderColumnItem(d)
			});
		}).concat([{
			title: getText("batch-editor-actions"),
			dataIndex: rowKey,
			key: "actions",
			align: "center",
			fixed: "right",
			width: 100,
			dataSource,
			selectList,
			render: (text, record) => {
				return /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(Button, { onClick: () => {
					handleRemove([text]);
				} }, getText("batch-editor-remove")));
			}
		}]);
	}, [
		renderColumnItem,
		rowKey,
		dataSource,
		selectList
	]);
	const selectOptions = useMemo(() => {
		return _columns.filter((d) => d.batchEdit).map((d) => {
			return {
				label: d.titleStr,
				value: d.dataIndex
			};
		});
	}, [_columns]);
	const onFinish = (values) => {
		handleBatchEditChange(values.value, values.key);
		onCancel();
		setSelectList([]);
	};
	const onCancel = () => {
		form.resetFields();
		setOpenModal(false);
	};
	const onOpenMOdal = () => {
		setOpenModal(true);
		form.setFieldsValue({ key: selectOptions[0].value });
	};
	const modalTitle = useMemo(() => {
		let str = "";
		let selectItems = [];
		selectList.forEach((item) => {
			let productItem = dataSource.find((d) => d[rowKey] === item);
			if (productItem) selectItems.push(productItem);
			else dataSource.forEach((d) => {
				if (d.children) {
					let childProductItem = d.children.find((t) => t[rowKey] === item);
					if (childProductItem) selectItems.push(childProductItem);
				}
			});
		});
		str = ``;
		if (selectItems.length > 1) {
			var _selectItems$;
			str = getText("batch-editor-quick-edit-title")((_selectItems$ = selectItems[0]) === null || _selectItems$ === void 0 ? void 0 : _selectItems$.title, selectItems.length);
		} else {
			var _selectItems$2;
			str = getText("batch-editor-quick-edit-title-2")((_selectItems$2 = selectItems[0]) === null || _selectItems$2 === void 0 ? void 0 : _selectItems$2.title);
		}
		return str;
	}, [selectList, dataSource]);
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(table_default, _objectSpread2(_objectSpread2({
		actionButtons: !!selectList.length && [{
			title: getText("batch-editor-batch-remove"),
			size: "large",
			onClick: () => {
				handleRemove(selectList);
				setSelectList([]);
			}
		}, {
			title: getText("batch-editor-batch-edit"),
			onClick: onOpenMOdal,
			size: "large",
			type: "primary"
		}],
		bordered: true,
		dataSource,
		columns: _columns,
		className: "batch-editor-table",
		rowKey,
		rowSelection: {
			type: "checkbox",
			selectedRowKeys: selectList,
			onChange: (keys) => {
				setSelectList(keys);
			}
		},
		scroll: { autoCalc: true },
		pagination: {
			localPagination: true,
			showSizeChanger: true,
			size: "default"
		}
	}, otherTableProps), {}, {
		onValuesChange: (values) => {
			var _otherTableProps$onVa;
			setSelectList([]);
			otherTableProps === null || otherTableProps === void 0 || (_otherTableProps$onVa = otherTableProps.onValuesChange) === null || _otherTableProps$onVa === void 0 || _otherTableProps$onVa.call(otherTableProps, values);
		},
		filter: _objectSpread2(_objectSpread2({
			show: true,
			sortButtonShow: false,
			quickFilterMaxLength: 3,
			storageMode: "localStorage"
		}, (otherTableProps === null || otherTableProps === void 0 ? void 0 : otherTableProps.filter) || {}), {}, { list: [{
			type: "search",
			name: "keywords",
			key: "keywords",
			localFilter: true,
			other: {
				trigger: ["onChange"],
				allowClear: true,
				size: "large",
				placeholder: getText("batch-editor-search"),
				onChange: () => {
					setSelectList([]);
				}
			}
		}, ...(otherTableProps === null || otherTableProps === void 0 || (_otherTableProps$filt = otherTableProps.filter) === null || _otherTableProps$filt === void 0 ? void 0 : _otherTableProps$filt.list) || []] })
	})), /* @__PURE__ */ React.createElement(Modal, {
		title: getText("batch-editor-quick-edit"),
		open: openModal,
		footer: null,
		onCancel: () => {
			setOpenModal(false);
		}
	}, /* @__PURE__ */ React.createElement("div", {
		className: "title",
		style: { marginBottom: 20 }
	}, modalTitle), /* @__PURE__ */ React.createElement(Form, {
		layout: "vertical",
		form,
		onFinish
	}, /* @__PURE__ */ React.createElement(Form.Item, {
		label: getText("batch-editor-what-price"),
		name: "key"
	}, /* @__PURE__ */ React.createElement(Select, {
		size: "large",
		options: selectOptions
	})), /* @__PURE__ */ React.createElement(Form.Item, {
		label: getText("batch-editor-price"),
		name: "value"
	}, /* @__PURE__ */ React.createElement(Price, { symbol }))), /* @__PURE__ */ React.createElement("div", {
		className: "",
		style: {
			display: "flex",
			gap: 20,
			width: "100%"
		}
	}, /* @__PURE__ */ React.createElement(Button, {
		size: "large",
		style: { flex: 1 },
		onClick: onCancel
	}, getText("batch-editor-cancel")), /* @__PURE__ */ React.createElement(Button, {
		size: "large",
		type: "primary",
		onClick: () => {
			form.submit();
		},
		style: { flex: 1 }
	}, getText("batch-editor-confirm")))));
};
//#endregion
export { BatchEditor as default };
