import {BlockImage} from "@/components/article/item.tsx";

import styles from './article.module.scss'

export default function ImageList(props: {
	blocks: BlockContent[];
	editable?: boolean;
	onChange?: (blocks: BlockContent[]) => void;
}) {

	// 处理删除
	const handleRemove = (index: number) => {
		props.onChange?.(props.blocks.filter((_, idx) => index !== idx))
		const newBlocks = [...props.blocks]
		newBlocks.splice(index, 1)
		props.onChange?.(newBlocks)
	}
	// 处理新增
	const handleAdd = (data: BlockContent) => {
		props.onChange?.([...props.blocks, data])
	}
	// 处理更新
	const handleUpdate = (index: number, data: BlockContent) => {
		props.onChange?.(props.blocks.map((it, idx) => idx === index ? data : it))
	}


	return (<div className={styles.imageList}>
		{props.blocks.map((it, index) => (
			it.type === 'image' ? <BlockImage
				key={index} data={it} editable={props.editable}
				onChange={(data) => handleUpdate(index, data)}
				onRemove={() => handleRemove(index)}
			/> : null
		))}
		{props.editable &&
            <BlockImage onlyUpload onChange={handleAdd} data={{type: 'image', content: ''}} editable={true}/>}
	</div>)
}

