import React, { useEffect, useRef, useState } from 'react';
import { message, Upload } from 'antd';
import moment from 'moment';
import s from './index.less';
import { antiAssign, getRandom } from '../../../../utils/utils';
import { checkoutFileType } from './utils';
import Preview from './preview';
import addIcon from '../../../../assets/addIcon.png';

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

const UploadCom = (props) => {
    const { onChange, CDN_HOST, getFormat, setFormat, data, domain, maxLength } = props;
    const selfProps = antiAssign(props, ['onChange', 'CDN_HOST', 'data']);
    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 resData = file.response || {};
        const url = `${domain ? `https://${domain}` : CDN_HOST}/${resData.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 previewModel = useRef<any>();
    // 自定义七牛文件唯一key
    const getKey = (file: any) => {
        if (!file) return;
        const suffix = file.name.match(/\.\w+$/)[0];
        const rand6 = getRandom();
        const time = moment().format('YYYYMMDDHHmmss');
        return time + rand6 + suffix;
    };
    const [extraData, setExtraData] = useState({});
    // 七牛上传额外数据，token和key
    const getToken = async () => {
        let extData = data || {};
        if (typeof data === 'function') {
            const res = await data();
            if (res && res.success) {
                extData = res.data;
            }
        }
        setExtraData(extData);
    };
    const getData = (file: any) => {
        return {
            ...extraData,
            key: getKey(file),
        };
    };

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

    const changeFileList = ({ file, fileList }) => {
        let newList = fileList;
        if (maxLength) {
            newList = fileList.slice(-maxLength);
        }
        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) => {
            return item.uid !== file.uid;
        });
        onSaveFileList(newFileList);
    };

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