


import { ImportOutlined } from '@ant-design/icons';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Upload, message, Modal, Divider, Menu, Dropdown } from 'antd';
import {envConfig} from '../../../config/defaultSettings';
// import Cookies from 'js-cookie';

// 服务器地址

const {host} = envConfig;
const Host = host;




class CAUpload extends Component {
    constructor(props) {
        super(props);
        // 模板下载事件
        this.jumpTo = this.jumpTo.bind(this);
        // 表格导出事件
        this.exportExcel = this.exportExcel.bind(this);
        // 表格上传事件
        this.uploadProps.onChange = this.uploadProps.onChange.bind(this);

        this.customRequestCallback = props.customRequestCallback ? props.customRequestCallback.bind(this) : () => { };

        this.timer = null;

        this.file = null;
        
        this.templeteUrl='';

        this.label='';
    }
    // 模板下载
    jumpTo() {
        const userData = localStorage.getItem('userData');
        const { token } = JSON.parse(userData);
        if(this.templeteUrl == '/costAccount/excel/getcurrentTemplate'){
            //找后端
            window.open(`${Host}${this.templeteUrl}`);
        }else{
            window.open(`${Host}${this.templeteUrl}?token=${token}`);
        }
    }
    // 上传参数
    uploadProps = {
        // // 发到后台的文件参数名
        // name: 'file',
        // // 接受的文件类型
        // accept: '.xls,.xlsx',
        // // 上传的地址
        // action: Host + this.props.url,
        // // 是否展示上传的文件
        // showUploadList:false,
        // // 上传的参数
        // data: {

        //     // uid: Cookies.get('uid')
        // },
        // // 设置上传的请求头部，IE10 以上有效
        // headers: {
        //     // authorization: 'authorization-text',
        //     'Content-Type':'multipart/form-data',
        //     'token':this.props.token,
        // },
        // 上传文件前的钩子函数
        showUploadList: false,
        beforeUpload() {
            message.loading('正在导入中...');
            return true;
        },
        customRequest: ({
            file, data, action, onSuccess
        }) => {
            console.log({ file, data, action, onSuccess });
            const formData = new FormData();
            formData.set('file', file);
            this.file = file;
            if (this.props.type != 'dialog') this.customRequestCallback(formData);

        },
        // 上传文件改变时的状态
        onChange(info) {
            // console.log({info});
            if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (info.file.status === 'done') {
                if (info.file.response.code !== 200) {
                    setTimeout(() => {
                        message.destroy();
                        message.error(info.file.response.message);
                    });
                } else {
                    this.props.importSuccessCallback && this.props.importSuccessCallback();
                    setTimeout(() => {
                        message.destroy();
                        message.success('导入成功');
                    });
                }
            } else if (info.file.status === 'error') {
                setTimeout(() => {
                    message.destroy();
                    message.error('导入失败');
                });
            }
        },
    }

    // 导出Excel表格
    async exportExcel() {
        const userData = localStorage.getItem('userData');
        const { token } = JSON.parse(userData);
        const url = Host + this.props.url + `/export?token=${token}`;
        window.open(url);
        //获取  全院其他收支设置列表
    }

    renderMenu(){
        return (
            <Menu onClick={this.handleMenuClick.bind(this)}>
                  {
                         this.props.templateHrefs&&Array.isArray(this.props.templateHrefs)&&this.props.templateHrefs.map((item,index)=>{
                            return (
                                <Menu.Item key={item.value}>{item.label}</Menu.Item>
                            )
                     })
                  }
            </Menu>
        ) 
    }


    handleMenuClick(e){
        // console.log('菜单点击',e);
        const {key} = e;
        this.label = ''
        this.templeteUrl = key;
        this.jumpTo();
    }

    handleButtonClick(e){
          
         const { type,templateHrefs } = this.props;

         if(type == 'normal'){
            this.templeteUrl = templateHrefs;
         }
         if(this.templeteUrl == ''){
            message.error('请选择下载模板！');
            return;
         }
         this.jumpTo();
    }

    openModal() {
        const uploadProps = this.uploadProps;
        Modal.confirm({
            title: <React.Fragment>
                导入数据
                <Divider plain></Divider>
            </React.Fragment>,
            icon: null,
            width: 600,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                return new Promise((resolve, reject) => {
                    this.timer = setTimeout(() => {
                        resolve(true);
                        this.customRequestCallback(this.file)
                    }, 1500)
                }).then(res => {
                    // console.log({res})
                })
                    .catch(err => console.log({ err }))

            },
            content: <React.Fragment >
                {this.props.content}
                <Divider plain></Divider>
                <Upload style={{ marginLeft: 10 }} key='importExcel' {...uploadProps} >
                    <Button icon={<ImportOutlined />} type="primary">选择上传文件</Button>
                </Upload>
            </React.Fragment>
        });
    }

    componentWillUnmount() {
        clearTimeout(this.timer);
    }

    render() {
        const uploadProps = this.uploadProps;
        const { type } = this.props;
        // console.log({...this.props});
        if (type == 'normal'||!type) {
            return [
                // <Button style={{marginLeft: 10}} key='exportExcel' onClick={this.exportExcel}>导出</Button>,
                <Upload style={{ marginLeft: 10 }} key='importExcel' {...uploadProps} >
                    <Button type="primary">导入</Button>
                </Upload>,
                <Button style={{ marginLeft: 10 }} key='templateDowload' onClick={this.handleButtonClick.bind(this)}>模板下载</Button>
            ]
        }
        if (type == 'dialog') {
            return [
                <Button type="primary" key='a' onClick={() => this.openModal()}>导入</Button>,
                // <Button style={{marginLeft: 10}} key='templateDowloadTwo' onClick={this.jumpTo}>模板下载</Button>,
                <Dropdown.Button  key='b' onClick={this.handleButtonClick.bind(this)} overlay={this.renderMenu()}>
                    模板下载
                </Dropdown.Button>

            ]
        }

        return <></>

    }
}

// 定义参数类型
CAUpload.propTypes = {
    // 模板下载地址
    templateHrefs: PropTypes.oneOfType([
        PropTypes.array,
        PropTypes.string,
    ]),    
    // 上传地址
    url: PropTypes.string.isRequired,
    // 导入成功后的回调
    importSuccessCallback: PropTypes.func,
   
    customRequestCallback: PropTypes.func,
    //上传功能类型 【‘normal’,'dialog'】
    type: PropTypes.string,
    //渲染节点
    content: PropTypes.node,
};





// const CAUpload = (props)=>{

//     return (
//         <Upload {...props}>
//             <Button type="primary" icon={<ImportOutlined />}>导入</Button>
//         </Upload>
//     )
// }

export default CAUpload;