import React, { useEffect, useRef, useState } from 'react';
import { message, Upload } from 'antd';
import moment from 'moment';
import { getToken } from '@/apollo-table/services/globalSearchApi';
import IconFont from '@/apollo-table/component/base/extra/iconFont';
import s from './index.less';
import { antiAssign, getRandom } from '@/apollo-table/utils/utils';
import { checkoutFileType } from './utils';
import Preview from './preview';

message.config({
    maxCount: 1,
});

const UploadCom = (props) => {
    const { onChange, CDN_HOST, getFormat, setFormat } = props;
    const selfProps = antiAssign(props, ['onChange', 'CDN_HOST']);
    const getFormatFileList = (fileList = []) => {
        if (!fileList) {
            return [];
        }
        if (typeof getFormat === 'function') {
            return getFormat(fileList);
        }
        return fileList.map((item: any) => {
            return {
                name: item.name,
                value: item.value,
                size: item.size,
                uid: item.value,
                ...checkoutFileType(item.value),
            };
        });
    };
    const setFormatFile = (file) => {
        if (!file) {
            return {};
        }
        if (typeof setFormat === 'function') {
            return setFormat(fileList);
        }
        const data = file.response || {};
        const url = `${domain ? 'https://' + domain : CDN_HOST}/${data.key}`;
        return {
            uid: file.uid,
            name: file.name,
            value: url,
            size: file.size,
            ...checkoutFileType(url),
        };
    };
    const [fileList, setFileList] = useState(getFormatFileList(props.value));
    useEffect(() => {
        setFileList(getFormatFileList(props.value));
    }, [props.value]);
    const [token, setToken] = useState(null);
    const [domain, setDomain] = useState(null);
    const previewModel = useRef<any>();
    //自定义七牛文件唯一key
    const getKey = (file) => {
        if (!file) return;
        let suffix = file.name.match(/\.\w+$/)[0];
        let rand6 = getRandom();
        let time = moment().format('YYYYMMDDHHmmss');
        return time + rand6 + suffix;
    };
    //七牛上传额外数据，token和key
    const getData = (file) => {
        return {
            token,
            key: getKey(file),
        };
    };
    //获取七牛上传token
    const getUploadToken = async () => {
        const response = await getToken();
        if (response && response.success && response.data) {
            setToken(response.data.token);
            setDomain(response.data.domain);
        }
    };

    const onSaveFileList = (fileList = []) => {
        if (typeof onChange === 'function') {
            onChange(fileList);
        }
    };

    const beforeUpload = async () => {
        await getUploadToken();
        return true;
    };
    const changeFileList = ({ file, fileList }) => {
        let newList = fileList;
        if (file.status === 'done' && file.response) {
            const itemObj = setFormatFile(file);
            newList = fileList.map((item) => {
                return item.uid === itemObj.uid ? itemObj : item;
            });
            onSaveFileList(newList);
        }
        setFileList(newList);
    };
    const previewFile = (file) => {
        return new Promise((res, rej) => {
            const obj = checkoutFileType(file.name);
            const typeArr = file.name.match(/\.[a-zA-Z]+$/);
            const type = typeArr && typeArr[0] ? typeArr[0].replace('.', '') : '';
            if (!['png', 'gif', 'bmp', 'jpg', 'jpeg'].includes(type)) {
                res(obj.thumbUrl);
            }
        });
    };
    const onPreview = (file) => {
        if (previewModel.current && previewModel.current.onPreview) {
            previewModel.current.onPreview(file.value, file.name);
        }
    };
    const onRemove = (file) => {
        const newFileList = fileList.filter((item) => item.uid !== file.uid);
        onSaveFileList(newFileList);
    };

    return (
        <div className={s.container}>
            <Upload
                className={s.upload}
                listType="picture"
                action="https://upload-z1.qiniup.com/" //七牛上传地址
                data={getData}
                beforeUpload={beforeUpload}
                multiple
                fileList={fileList}
                {...selfProps}
                onChange={changeFileList}
                onRemove={onRemove}
                previewFile={previewFile}
                onPreview={onPreview}
                showUploadList={{
                    showPreviewIcon: true,
                    showRemoveIcon: true,
                    showDownloadIcon: true,
                }}
            >
                <IconFont type="iconxinzeng" />
            </Upload>
            <Preview ref={previewModel} />
        </div>
    );
};
export default UploadCom;
