import { MaterialLibraryModal } from '@/components';
import { UploadOutlined } from '@ant-design/icons';
import { Upload } from 'antd';
import React, { useEffect, useState } from 'react';
import useStyle from './style.style';

export interface UploadMaterialProps {
	maxCount: number;
	onChange: (fileList: any[]) => void;
	fileList?: any[];
}

const UploadMaterial: React.FC<UploadMaterialProps> = (props) => {
	const { maxCount, onChange, fileList: initialFileList } = props;
	const [fileList, setFileList] = useState<any[]>([]);
	const [open, setOpen] = useState(false);

	const { styles } = useStyle();
	useEffect(() => {
		setFileList(initialFileList || []);
	}, [initialFileList]);

	// 处理素材选择完成
	const handleMaterialSelect = (materials: BusinessAPI.MaterialVO[]) => {
		const imageList = materials.map((materialVO) => ({
			uid: materialVO?.materialId,
			name: materialVO?.name,
			// @ts-ignore
			status: 'success',
			thumbUrl: materialVO?.url,
			url: materialVO?.url,
		}));

		const newFileList = [...fileList, ...imageList];
		setFileList(newFileList);
		onChange(newFileList);
	};

	return (
		<>
			<Upload
				listType={'picture-card'}
				fileList={fileList}
				onRemove={(file) => {
					const index = fileList.indexOf(file);
					const newFileList = fileList.slice();
					newFileList.splice(index, 1);
					setFileList(newFileList);
					onChange(newFileList);
				}}
				showUploadList={true}
				multiple={false}
				accept={'image/*'}
				maxCount={maxCount || 1}
				openFileDialogOnClick={false}
			>
				{fileList.length >= (maxCount || 1) ? null : (
					<div className={styles.uploadImage} onClick={() => setOpen(true)}>
						<div className={styles.uploadImageIcon}>
							<UploadOutlined /> 单击上传
						</div>
					</div>
				)}
			</Upload>

			{/* 素材库选择弹窗 */}
			<MaterialLibraryModal
				open={open}
				onCancel={() => setOpen(false)}
				maxCount={maxCount - fileList.length}
				mode="checkbox"
				materialType="FILE_IMAGE"
				onFinish={(materials) => {
					handleMaterialSelect(materials);
					setOpen(false);
				}}
			/>
		</>
	);
};

export default UploadMaterial;
