import { createNewFileBid, removeFileByOid } from '@/services/download_';
import { downloadPath, uploadAttachmentPath } from '@/utils/DownloadUtils';
import { getSessionRoleData, getUserToken } from '@/utils/session';
import { PlusOutlined } from '@ant-design/icons';
import { message, Modal, Spin, Upload } from 'antd';
import type { RcFile, UploadProps } from 'antd/es/upload';
import type { UploadFile } from 'antd/es/upload/interface';
import React, { useEffect, useState } from 'react';

const getBase64 = (file: RcFile): Promise<string> =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result as string);
        reader.onerror = error => reject(error);
    });

interface ExpertPhotoUpload {
    maxSize?: number | undefined; //文件大小KB 默认1024KB
    value?: string | null; //文档中心fileId
    onChange?: (fileId: string | null) => void; //回调
    uploadProps?: UploadProps;
}
/**
 * 图片上传 仅用fileId objectId随机生成
 * @param props 
 * @returns 
 */
const ExpertPhotoUpload: React.FC<ExpertPhotoUpload> = (props) => {
    const { maxSize, value, onChange, uploadProps } = { maxSize: 1024, ...props, }
    //预览弹窗
    const [previewVisible, setPreviewVisible] = useState(false);
    //预览图片的base64
    const [previewImage, setPreviewImage] = useState('');
    //objectId
    const [uploadObjectId, setUploadObjectId] = useState<string>();
    //文件列表
    const [fileList, setFileList] = useState<any[]>([]);

    const handleCancel = () => setPreviewVisible(false);

    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as RcFile);
        }

        setPreviewImage(file.url || (file.preview as string));
        setPreviewVisible(true);
    };

    const handleChange: UploadProps['onChange'] = ({ file, fileList: newFileList }) => {
        if (file.status === 'uploading') {
            setFileList(newFileList);
        } else if (file.status === 'removed') {
            //删除文件
            removeFileByOid(file.uid).then(res => {
                if (res.success) {
                    onChange && onChange(null);
                    message.success("删除成功");
                }
            })
        } else if (file.status === 'done') {
            onChange && onChange(file?.response.data[0].sysStorageVO.fileId);
            message.success("上传成功");
        } else if (file.status === 'error') {
            message.error("上传失败，请重新上传");
        }
    };
    //上传前校验
    const beforeUpload = (file: RcFile) => {
        const fileType = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg';
        const fileSize = file.size / 1024;//精确到KB
        console.log("fileSize", fileSize)
        const fileListLength = fileList.length;
        if (!fileType) {
            message.error(`上传失败，${file.name}类型不正确，请选择png、jpg、jpeg类型的图片`);
            return Upload.LIST_IGNORE;
        }
        if (fileSize >= maxSize) {
            message.error(`上传失败，${file.name}大小为${fileSize.toFixed(2)}KB，超过允许的大小${maxSize}KB`);
            return Upload.LIST_IGNORE;
        }
        if (fileListLength >= 1) {
            message.error(`上传失败，${file.name}数量为${fileListLength}个，超过允许的数量 1 个`);
            return Upload.LIST_IGNORE;
        }
        return true;
    }

    const uploadButton = (
        <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>上传</div>
        </div>
    );
    //获取雪花id，上传用
    const getObjectId = () => {
        createNewFileBid().then(res => {
            setUploadObjectId(res.id);
        })
    }
    //回显文件列表
    const getFileList = (fileId: string | null | undefined) => {
        if (fileId) {
            return [{
                uid: fileId,
                name: 'image.png',
                status: 'done',
                url: downloadPath + "?fileId=" + fileId,
            }]
        }
        return [];
    }

    useEffect(() => {
        !uploadProps?.disabled && getObjectId();
    }, [])

    useEffect(() => {
        setFileList(() => getFileList(value));
    }, [value])

    return (
        <>
            <Upload
                action={uploadAttachmentPath}
                data={{
                    appCode: 'ebtp-cloud-frontend',
                    objectId: uploadObjectId,
                }}
                headers={{
                    Authorization: getUserToken(),
                    currentRoleCode: getSessionRoleData()?.roleCode,
                }}
                name="multipartFiles"
                listType="picture-card"
                fileList={fileList}
                onPreview={handlePreview}
                onChange={handleChange}
                beforeUpload={beforeUpload}
                accept=".jpg,.png,.jpeg"
                {...uploadProps}
            >
                {uploadProps?.disabled || fileList.length >= 1 ? null : uploadButton}
            </Upload>
            <Modal visible={previewVisible} title="查看" footer={null} onCancel={handleCancel} centered>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>
        </>
    );
};

export default ExpertPhotoUpload;