import { useEffect, useState } from "react";
import { request } from '@umijs/max';
import { baseUrl } from '@/constants/index'
import { message, Space, Image } from 'antd';
import { ProFormUploadButton } from '@ant-design/pro-components';
import { Imageprefix } from '@/constants';


type UploadModelProps = {
    form_name: string;
    uploadTxt: string;
    image_type: number | 1;
    image_length: number | 1;
    onUploadComplete: (filename: string) => void;
    multiple: boolean | false,
    imageUrl?: String | undefined;

};
const UploadModel: React.FC<UploadModelProps> = (props) => {
    const { onUploadComplete, uploadTxt, image_type, form_name, image_length, multiple, imageUrl } = props;
    const handleUploadComplete = (filename: string) => {
        if (filename) {
            onUploadComplete(filename);
        }
    };

    const [image_url, setImageUrl] = useState<string>(imageUrl)

    useEffect(() => {
        setImageUrl(imageUrl)
    }, [imageUrl])




    return (
        <>
            <Space>
                <ProFormUploadButton
                    label={uploadTxt}
                    name={form_name}
                    icon={null}
                    title={uploadTxt}
                    fieldProps={{
                        maxCount: image_length,
                        multiple: multiple,
                        fileList: [],
                        listType: 'picture-card',
                        showUploadList: false,
                        customRequest: (e) => {
                            let formdata = new FormData();
                            formdata.append('image', e.file);
                            console.log(formdata)
                            request(baseUrl + '/common/image/upload?imgtype=' + image_type, {
                                method: 'post',
                                data: formdata,
                                Headers: {
                                    Authorization: sessionStorage.getItem('token'),
                                    'X-Requested-With': null
                                }
                            }).then(res => {
                                setImageUrl(res.data.filename)
                                handleUploadComplete(res.data.filename)
                            }).catch(err => {
                                console.log(err)
                                message.error('上传失败')
                            })
                        }
                    }}
                >
                </ProFormUploadButton>

                {
                    image_url && <Image src={`${Imageprefix}${image_url}`} width={102} height={102} style={{ borderRadius: 8 }} />
                }


            </Space>
        </>
    )
}

export default UploadModel;