import SelectModal from "../../../selectModal/index.js";
import { getProductList } from "./server.js";
import ProductItem from "./ProductItem/index.js";
import ProductItemPreview from "./ProductItemPreview/index.js";
import React, { useEffect, useMemo, useState } from "react";
import { locales } from "@pisell/utils";
import { useRequest } from "ahooks";
import "./index.less";
//#region src/components/productExtension/fields/SelectProducts/index.tsx
const SelectProducts = ({ value, onChange }) => {
	const [listMap, setListMap] = useState({});
	const _getProductList = useRequest(getProductList, {
		manual: true,
		onSuccess: (res) => {
			let obj = {};
			res.forEach((d) => {
				obj[d.id] = d;
			});
			setListMap(obj);
		}
	});
	const _value = useMemo(() => {
		if (value && value.length) return value.map((d) => listMap[d.product_id] || d);
		return value;
	}, [value, listMap]);
	useEffect(() => {
		_getProductList.run({
			skip: 1,
			num: 500,
			with: ["category"],
			open_quotation: 1,
			exclude_extension_type: ["event_item"],
			status: "published"
		});
	}, []);
	const onRemove = (item) => {
		onChange === null || onChange === void 0 || onChange((value || []).filter((d) => (d.id || d.product_id) !== item.id));
	};
	return /* @__PURE__ */ React.createElement(SelectModal, {
		value: _value,
		loading: _getProductList.loading,
		onChange: (arr) => {
			onChange === null || onChange === void 0 || onChange(arr.map((d) => {
				return {
					product_collection_id: 0,
					product_id: d.id || d.product_id,
					product_variant_id: 0
				};
			}));
		},
		dataSource: _getProductList.data,
		renderValueItem: (item, onSelect) => {
			return /* @__PURE__ */ React.createElement(ProductItemPreview, {
				key: item === null || item === void 0 ? void 0 : item.id,
				item,
				onClick: onSelect,
				onRemove
			});
		},
		renderOptionItem: (item, onSelect) => {
			return /* @__PURE__ */ React.createElement(ProductItem, {
				key: item === null || item === void 0 ? void 0 : item.id,
				item,
				onClick: onSelect
			});
		},
		buttonProps: {
			showSub: !!(value === null || value === void 0 ? void 0 : value.length),
			title: locales.getText("pisell2.text.product-extension.add-product"),
			subTitle: locales.getText("pisell2.text.product-extension.add-other-product")
		},
		drawerProps: {
			width: 500,
			title: locales.getText("pisell2.text.product-extension.add-product"),
			rootClassName: "select-product-drawer"
		},
		tabProductProps: {
			warpClassName: "select-product-warp",
			stickyTop: 188,
			scrollDom: ".select-product-drawer .pisell-lowcode-drawer-body"
		}
	});
};
//#endregion
export { SelectProducts as default };
