import React from 'react';
import { Form, Input, message, Modal } from 'kts-xui';
import { Row, Col, Upload } from 'kts-components-antd-x4';
import debounce from 'lodash/debounce';
import { PlusOutlined } from '@ant-design/icons';
import { CloudUploadOutlined, CloudDownloadOutlined } from "@ant-design/icons";
import '../index.less';
import { DigitalAssetVerification as agent } from '../../../../..';
import moment from 'moment';
const FormItem = Form.Item;
interface IProps {
    fnForceUpdate: () => void;
    data: IData
}
interface IData {
    /**
     *  上传地址
     */
    url: string | ((data) => Promise<any>);
    downloadurl: string;

}

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: '',
            groupNumber: null,
            // showFive: this.props.data.show || false,
            // callback: this.props.data.excelcallback,
            // uploadConfig: DigitalAssetVerification.remoteConfig,
        };
        this.fetchGroup = debounce(this.fetchGroup, 800);
    }
    handleCancel = () => {
        this.setState({
            errorModal: false
        });
    }
    handleOk = () => {

        if (this.state.downloadFilePath.indexOf('http') >= 0 || this.state.downloadFilePath.indexOf('//') === 0) {
            window.open(this.state.downloadFilePath);
        } else {
            // window.open(this.state.uploadConfig.domain + this.state.downloadFilePath);
            window.open(this.state.downloadFilePath);
        }
    }
    onAddGroup = () => {

    }
    fetchGroup = (rule, value, callback) => {

    }
    downloadfile = async () => {

    }
    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;
                        // if (downloadFilePath && downloadFilePath.indexOf('http') < 0) {
                        //     downloadFilePath = `/zone/invoice/biz-logging/downloadFile?filepath=${downloadFilePath}`;
                        // }
                        const errorCount = info.file.response.body.failureNo;
                        const successCount = info.file.response.body.successNo;
                        let errorText = `录入成功${successCount} 条,失败${errorCount} 条!`;
                        this.setState({
                            excel: false,
                            errorModal: !!errorCount,
                            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} 条!`;
            this.props.fnForceUpdate();
            this.setState({
                excel: false,
                errorModal: !!errorCount,
                errorInfo: errorText,
                downloadFilePath: downloadFilePath
            });
            if (!!errorCount === false) {
                message.success('上传成功！');

            }
        }
    }
    onDownload = (url) => {
        const href = `${url}`;
        let a = window.document.createElement('a');
        a.setAttribute('href', href);
        a.setAttribute('target', '_blank');
        a.download = `模板_${moment(new Date()).format("YYYYMMDDHHmmss")}.xls`;
        a.click();
    }
    render() {
        let formItemLayout = {
            labelCol: { span: 7 },
            wrapperCol: { span: 17 },
        };
        // let { domain } = this.state.uploadConfig;
        const propsData = this.state.data;
        const url = propsData.url;
        let downloadTemplate = '';
        if (propsData.downloadurl.indexOf('http') >= 0 || propsData.downloadurl.indexOf('//') === 0) {
            //绝对地址
            downloadTemplate = propsData.downloadurl;
            //我怎么感觉这个if判断没意义呢？    
        } else {
            //相对地址
            // downloadTemplate = domain + propsData.downloadurl;
            downloadTemplate = propsData.downloadurl;

        }
        const props = {
            name: 'file',
            multiple: false,
            // onChange: this.onChange,
            fileList: this.state.fileList,
            showUploadList: { showRemoveIcon: false },
            beforeUpload: async (file) => {
                if (typeof url === 'string') {

                    const res = await agent.server
                        .post(url)
                        .reqFs(agent.server.reqFs.filter(v => v !== agent.serviceTools.addContentType))
                        .field('fileName', file.name)
                        // .set({ 'Content-Type': 'multipart/form-data' })  //When you use .field() or .attach() you can't use .send() and you must not set Content-Type (the correct type will be set for you).
                        .attach('file', file, file.name).end(this);
                    if (res) {
                        file.status = "done";
                    } else {
                        file.status = "error";
                    }
                    this.handleResponse(res);
                    this.list.unshift(file);
                    this.setState({
                        fileList: this.list
                    });
                    return false;
                } else {
                    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(downloadTemplate)} target="_blank" style={{ color: 'inherit' }}><CloudDownloadOutlined style={{ width: '100%', fontSize: 54 }} />
                            <h3>Excel 模板下载</h3>
                        </a>
                    </div>
                    <div style={{ textAlign: 'center', flex: 1, width: '50%' }}>
                        <a style={{ color: 'inherit' }}>
                            <Upload {...props}>
                                <CloudUploadOutlined style={{ width: '100%', fontSize: 54, }} />
                                <h3>Excel 上传</h3>
                            </Upload>
                            
                        </a>
                    </div>
                </div>
                {
                    this.state.showFive &&
                    <Form>
                        <Row style={{ marginTop: 20 }}>
                            <Col span={21} >
                                <FormItem
                                    name="groupNumber"
                                    {...formItemLayout}
                                    label="指定到发票组"
                                    rules={
                                        [
                                            {
                                                validator: this.fetchGroup
                                            }
                                        ]
                                    }
                                >
                                    <Input onChange={(e) => this.setState({ groupNumber: e.target.value })} />
                                </FormItem>
                            </Col>
                            <Col span={2} offset={1}>
                                <span style={{ lineHeight: '107px' }} className="hand" onClick={this.onAddGroup}><PlusOutlined /></span>
                            </Col>
                        </Row>
                        <span className='tip'>如需指定发票组，请在上传文件前指定发票组</span>
                    </Form>
                }
                <Modal
                    title={'提示'}
                    okText={'下载'}
                    visible={this.state.errorModal}
                    onCancel={this.handleCancel}
                    onOk={this.handleOk}
                >
                    {this.state.errorInfo} 点击下载按钮下载录入失败记录。
                </Modal>
            </div>
        );
    }
}

export default Component;
