import React, { useEffect, useRef, useState } from 'react';
import ImportUtil from '@/webPublic/one_stop_public/App/ImportUtil';
import ExportCurrentInfo from '@/webPublic/one_stop_public/App/ExportCurrentInfo';
import { Base16Encode } from '@/webPublic/one_stop_public/Base16';
import SplitButton from '@/webPublic/one_stop_public/libs/formList/SplitButton';

export function FormListButtons(props) {
	const [ConcatButtons, setConCatButtons] = useState([]);
	const {
		btns,
		loading,
		importConfig,
		getPage,
		objId,
		query,
		custom,
		sql,
		exportConfig,
		selectedRows,
		obj,
	} = props;
	const Before = (btns && btns.before) || [];
	useEffect(
		() => {
			let buttons = [];
			buttons = Before.map((g) => {
				g.ButtonType = 'Normal';
				return g;
			});
			for (let item of importConfig) {
				buttons.push({
					...item,
					ButtonType: 'import',
				});
			}
			let i = 0;
			for (let item of exportConfig) {
				buttons.push({
					...item,
					ButtonType: 'export',
					index: i++,
				});
			}
			buttons.sort((a, b) => {
				let priorityA = a.priority || 0;
				let priorityB = b.priority || 0;
				return priorityA - priorityB;
			});
			setConCatButtons(buttons);
		},
		[exportConfig, importConfig, btns],
	);

	if (!ConcatButtons || !ConcatButtons.length) {
		return null;
	}
	// console.log(ConcatButtons);

	return ConcatButtons.map((r, i) => {
		if (r.ButtonType === 'Normal') {
			const propsR = { ...r };
			delete propsR.ButtonType;
			return (
				<SplitButton
					{...propsR}
					loading={loading}
					key={r.children}
					selectedRows={selectedRows}
					obj={obj}
				/>
			);
		} else if (r.ButtonType === 'import') {
			return (
				<ImportUtil
					btn={r.btn}
					key={r.btn?.name || '导入'}
					ext={r.ext ? r.ext : 'xlsx'}
					importConfig={r}
					objId={objId}
					callback={() => {
						getPage();
						if (r.callback && typeof r.callback === 'function') {
							r.callback();
						}
					}}
				/>
			);
		} else if (r.ButtonType === 'export') {
			return (
				<ExportCurrentInfo
					{...r}
					objId={objId}
					key={r.children || '到处'}
					query={query}
					custom={custom}
					index={r.index}
					btn={r.btn}
					ext={r.ext ? r.ext : 'xlsx'}
					openSelectFieldsModal={r.openSelectFieldsModal || false}
					sql={Base16Encode(sql)}
				/>
			);
		}
	});

	// return Before.map((r) => <Button {...r} loading={loading} key={r.children} />);
}
