import React from 'react';
import { message, Modal } from 'kts-xui';
import { Row, Col, Upload, Space } from 'kts-components-antd-x4';
import Icon, { InfoCircleOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { ReactComponent as DownloadIcon } from '../Icon/download.svg';
import { ReactComponent as UploadIcon } from '../Icon/upload.svg';
import '../index.less';
import { DigitalAssetVerification as agent } from '../../../..';
// import agent from '../../../Server';
import moment from 'moment';
interface IProps {
    fnForceUpdate: () => void;
    data: IData
}
interface IData {
    commonUploadCb?: (data) => Promise<any>;
    commonDownloadCb?: () => Promise<any>

}
/**
 * 这是一个通用的导入模块，处理函数都需要在外部实现，内部不进行具体业务实现
 */
class Component extends React.Component<IProps, any>{
    private list: any[] = [];
    constructor(props: any) {
        super(props);
        this.state = {
            downloadUrl: '',
            data: this.props.data,
            excel: true,
            errorModal: false,
            errorInfo: '',
            downloadFilePath: '',
            tip: '',
            successNo: 0,
            failureNo: 0
        };
    }
    handleCancel = () => {
        this.setState({
            errorModal: false
        });
    }
    handleOk = async () => {
        if (this.state.downloadFilePath.indexOf('http') >= 0 || this.state.downloadFilePath.indexOf('//') === 0) {
            window.open(this.state.downloadFilePath);
        } else {
            const response: any = await agent.server.post(`${agent.prefix_path}/web/verifiedTask/getFileDownloadUrl`, { fileNameList: [this.state.downloadFilePath] }).end(this);
            const res = response.res[0];
            const href = `${res}`;
            let a = window.document.createElement('a');
            a.setAttribute('href', href);
            a.setAttribute('target', '_blank');
            a.setAttribute('download', `下载文件_${moment(new Date()).format('YYYYMMDDHHmmss')}.xls`);
            a.click();
        }
    }
    onChange = (info: any) => {
        const status = info.file.status;
        let fileList = info.fileList;
        this.setState({ fileList });
        if (status === 'done') {
            const returnCode = info.file.response.status.returnCode;
            if (returnCode === '99999') {
                message.warning('系统异常');
            } else {
                if (info.file.response.ok) {
                    if (info.file.response.body.allSuccess) {
                        //message.success('上传成功！');
                    } else {
                        let downloadFilePath = info.file.response.body.downloadUrl;
                        const errorCount = info.file.response.body.failureNo;
                        const successCount = info.file.response.body.successNo;
                        let errorText = <span>录入成功{successCount}条,失败{errorCount}条!</span>;
                        this.setState({
                            excel: false,
                            errorModal: true,
                            errorInfo: errorText,
                            downloadFilePath: downloadFilePath,
                        });
                        if (!!errorCount === false) {
                            message.success('上传成功！');
                        }
                    }
                    this.props.fnForceUpdate!();
                } else {
                    message.error(info.file.response.status.description);
                }

            }
        } else if (status === 'error') {
            message.error(`${info.file.name} 文件上传失败.`);
        }
    }
    handleResponse = res => {
        if (!res.err) {
            let downloadFilePath = res.res.downloadUrl;
            const errorCount = res.res.failureNo;
            const successCount = res.res.successNo;
            let errorText = `录入成功${successCount}条,失败${errorCount}条!`;
            if (res.res.failureNo === res.res.failureNo + res.res.successNo) {
                this.setState({
                    tip: 'failure'
                })
            } else if (res.res.successNo === res.res.failureNo + res.res.successNo) {
                this.setState({
                    tip: 'success'
                })
            } else {
                this.setState({
                    tip: 'half'
                })
            }
            this.props.fnForceUpdate();
            this.setState({
                excel: false,
                errorModal: true,
                errorInfo: errorText,
                downloadFilePath: downloadFilePath,
                successNo: res.res.successNo,
                failureNo: res.res.failureNo
            });
        }
    }
    onDownload = async () => {
        this.props.data.commonDownloadCb && this.props.data.commonDownloadCb();
    }
    tipModal = () => {
        const { tip, successNo, failureNo } = this.state;
        let info;
        let title = '导入成功';
        let icon, download;
        if (tip === 'success') {
            icon = <CheckCircleOutlined style={{ color: '#0074ff', fontSize: 30 }} />;
            info = <span>模板数量<span style={{ color: '#0074ff' }}>{successNo + failureNo}条</span>，导入成功<span style={{ color: '#0074ff' }}>{successNo}条。</span></span>
        } else if (tip === 'failure') {
            download = <a onClick={this.handleOk}>下载失败结果</a>
            title = '导入失败';
            icon = <CloseCircleOutlined style={{ color: '#FF5F58', fontSize: 30  }} />;
            info = <span>模板数量<span style={{ color: '#0074ff' }}>{successNo + failureNo}条</span>，导入失败<span style={{ color: '#0074ff' }}>{failureNo}条。</span></span>
        } else {
            download = <a onClick={this.handleOk}>下载失败结果</a>
            title = '导入结果';
            icon = <InfoCircleOutlined style={{ color: '#FFD900', fontSize: 30 }} />;
            info = <span>模板数量<span style={{ color: '#0074ff' }}>{successNo + failureNo}条</span>，导入成功<span style={{ color: '#0074ff' }}>{successNo}条</span>，导入失败<span style={{ color: '#0074ff' }}>{failureNo}条</span>！您可以下载失败结果调整后重新导入。</span>
        }
        return (
            <Modal
                className='specail'
                title={' '}
                width={396}
                footer={null}
                maskClosable={false}
                visible={this.state.errorModal}
                onCancel={this.handleCancel}
            >
                <p style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18, textAlign: 'center', marginBottom: 15, fontWeight: 500, color: '#212223' }}>{icon} <span style={{ paddingLeft: 5 }}>{title}</span></p>
                {info}
                <div style={{ display: 'flex', justifyContent: 'space-between', padding: '35px 0 0' }}>
                    <div>
                        {download}
                    </div>
                    <div>
                        <Space size={20}>
                            <a onClick={this.handleCancel}>确认</a>
                            <a onClick={this.handleCancel}>取消</a>
                        </Space>
                    </div>
                </div>
            </Modal>
        )
    }
    render() {
        const propsData = this.state.data;
        const url = propsData.commonUploadCb;
        const props = {
            name: 'file',
            multiple: false,
            fileList: this.state.fileList,
            showUploadList: { showRemoveIcon: false },
            beforeUpload: async (file) => {
                return await url(file).then((res) => {
                    if (res) {
                        file.status = "done";
                    } else {
                        file.status = "error";
                    }
                    this.handleResponse(res);
                    this.list.unshift(file);
                    this.setState({
                        fileList: this.list
                    });
                    return false;
                });

            }
        };
        return (
            <div className='uploadFile'>
                <div style={{ display: 'flex', justifyContent: 'space-evenly' }}>
                    <div style={{ textAlign: 'center', flex: 1, width: '50%' }}>
                        <a onClick={this.onDownload} target="_blank" style={{ color: 'inherit' }}>
                            <Icon component={DownloadIcon} style={{ width: '100%', fontSize: 54 }} />
                            <h3>Excel 模板下载</h3>
                        </a>
                    </div>
                    <div style={{ textAlign: 'center', flex: 1, width: '50%' }}>
                        <a style={{ color: 'inherit' }}>
                            <Upload {...props}>
                                <Icon component={UploadIcon} style={{ width: '100%', fontSize: 54 }} />
                                <h3>Excel 上传</h3>
                            </Upload>

                        </a>
                    </div>
                </div>
                {this.tipModal()}
            </div>
        );
    }
}

export default Component;
