import React, { useMemo, memo, useState } from 'react';
import { Switch, Row, Col, Select, Upload, message } from 'antd';
import { deepCopy, UserConfig } from 'dooringx-lib';
import { FormMap } from '../formTypes';
import { CreateOptionsRes } from 'dooringx-lib/dist/core/components/formTypes';
import { IBlockType } from 'dooringx-lib/dist/core/store/storetype';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';

interface MSwitchProps {
	data: CreateOptionsRes<FormMap, 'upload'>;
	current: IBlockType;
	config: UserConfig;
}

const MUpload = (props: MSwitchProps) => {
	const [loading, setLoading] = useState(false);
	const [imageUrl, setImageUrl] = useState<string>();
	const option = useMemo(() => {
		return props.data?.option || {};
	}, [props.data]);
	const store = props.config.getStore();
	const beforeUpload = (file: any) => {
		const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
		if (!isJpgOrPng) {
			message.error('You can only upload JPG/PNG file!');
		}
		const isLt2M = file.size / 1024 / 1024 < 2;
		if (!isLt2M) {
			message.error('Image must smaller than 2MB!');
		}
		return isJpgOrPng && isLt2M;
	};
	const getBase64 = (img: any, callback: (url: string) => void) => {
		const reader = new FileReader();
		reader.addEventListener('load', () => callback(reader.result as string));
		reader.readAsDataURL(img);
	};

	const handleChange: any = (info: any) => {
		if (info.file.status === 'uploading') {
			setLoading(true);
			return;
		}
		if (info.file.status === 'done') {
			// Get this url from response in real world.
			getBase64(info.file.originFileObj as any, (url) => {
				setLoading(false);
				setImageUrl(url);
				const receive = (option as any).receive;
				const clonedata = deepCopy(store.getData());
				const newblock = clonedata.block.map((v: IBlockType) => {
					if (v.id === props.current.id) {
						v.props[receive] = url;
					}
					return v;
				});
				store.setData({ ...clonedata, block: [...newblock] });
			});
		}
	};

	const uploadButton = (
		<div>
			{loading ? <LoadingOutlined /> : <PlusOutlined />}
			<div style={{ marginTop: 8 }}>上传</div>
		</div>
	);
	return (
		<Row style={{ padding: '10px' }}>
			<Col span={8} style={{ lineHeight: '30px' }}>
				{(option as any)?.label || '文字'}：
			</Col>
			<Col span={16} style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
				<Upload
					listType="picture-card"
					action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
					beforeUpload={beforeUpload}
					showUploadList={false}
					onChange={handleChange}
				>
					{imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
				</Upload>
			</Col>
		</Row>
	);
};

export default memo(MUpload);
