import * as React from 'react';
import { Upload, Icon, message } from 'antd';
import { PageComponent } from '../../types/index';
import { randomImg } from './qiniuUploader';

type UploadFilesProps = {
    CDNToken: string,
    CDNUrl: string,
    CDNDir: string,
    fileType?: string, // 默认 .xlsx
    fileMaxSize?: number, // 默认 1024
    fileMinSize?: number, // 默认 0
    fileUnit?: string, // 默认 B
    onChange?: (url: string) => void,
    [propsName: string]: any
}
const timestamp = new Date().valueOf()
export class UploadFile extends React.PureComponent<PageComponent<UploadFilesProps>> {
    static INIT_STATE = { // 初始条件
        fileList: [],
        uploadedUrl: undefined
    }
    cdnAction = `https://up-z1.qiniup.com?${timestamp}`
    state = {
        fileList: [],
        uploadedUrl: undefined,
        uploadProgress: 0,
    };

    componentDidMount() {

    }
    fileSizeUnitFunsMap = {
        'B': (size) => size,
        'KB': (size) => size * 1024,
        'MB': (size) => size * 1024 * 1024,
        'GB': (size) => size * 1024 * 1024 * 1024,
        'TB': (size) => size * 1024 * 1024 * 1024 * 1024,
    }
    validateFileSize = (size) => {
        const { fileMaxSize = 1024, fileMinSize = 0, fileUnit = 'B' } = this.props;
        if (!this.fileSizeUnitFunsMap[fileUnit]) return message.error('请检查设置的文件大小单位')
        const allowedMaxSizeB = this.fileSizeUnitFunsMap[fileUnit](fileMaxSize);
        const allowedMinSizeB = this.fileSizeUnitFunsMap[fileUnit](fileMinSize);

        if (size > allowedMaxSizeB) {
            message.error('Error：文件验证失败，文件大小超出上限')
            return false;
        } else if (size < allowedMinSizeB) {
            message.error('Error：文件验证失败，文件大小小于下限')
            return false;
        }
        return true;
    }
    onHandleBeforeUpload = (info) => {
        return !!this.validateFileSize(info.size);
    }
    onHandleUploadChange = (info) => {
        const { onChange = () => null, CDNUrl } = this.props;

        if (info.file.status) {
            this.setState({ fileList: info.fileList })
        }

        if (info.file.status === 'done') {
            if (info.file.response) {
                const resUrl = CDNUrl + info.file.url
                onChange(resUrl);
                message.success('上传(缓存)操作成功');
            } else {
                message.error({
                    content: <pre>{info.file.response && info.file.response.msg || 'Error：上传操(缓存)作失败！'}</pre>
                });
            }
        } else if (info.file.status === 'error') {
            message.error('Error：上传(缓存)操作失败！')
        }
    }
    transformFile = (file) => {
        const { CDNDir } = this.props;
        const suffix = file.name.slice(file.name.lastIndexOf('.'));
        const filename = `${randomImg()}-${Date.now() + suffix}`;
        file.url = CDNDir + filename;
        return file
    }
    getExtraData = (file) => {
        const { CDNToken } = this.props;

        return {
            key: file.url,
            token: CDNToken,
        };
    }
    render() {
        const { fileList } = this.state;
        const { fileType = '.xlsx', fileMaxSize = 1024, fileMinSize = 0, fileUnit = 'KB' } = this.props;

        return (
            <div
                className='jad-upload-files-wrap'
            >
                <Icon type="cloud-upload" />
                <div className='upload-operate'>
                    <Upload
                        fileList={fileList}
                        action={this.cdnAction}
                        accept={fileType}
                        data={this.getExtraData}
                        transformFile={this.transformFile}
                        beforeUpload={this.onHandleBeforeUpload}
                        onChange={this.onHandleUploadChange}
                    >
                        {!(fileList && fileList.length) ? <div className='upload-prepare'>
                            <div>
                                {`支持格式 ${fileType}，${fileMaxSize ? ('文件大小' + fileMaxSize + fileUnit + '以内') : ''}${fileMinSize ? ('、' + fileMinSize + fileUnit + '以上') : ''}`}
                            </div>
                            <div className='link'>上传文件</div>
                        </div> : null}
                    </Upload>
                </div>

            </div>
        );
    }
}