/**
 * 导入
 */
import React from 'react';
import { Card, Table, Button, message, Tabs, Modal, Progress, Spin } from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import store from 'store';
import CommonPagination from 'components/pagination/index';
import * as XLSX from 'xlsx';
import { handleExcel } from 'tools/handleExcel.js';
import { PAGE_NUM_MORE_STATUS } from 'tools/statusConstants';
import moment from 'moment';
import './style/index.less';

const { TabPane } = Tabs;

class ImportDataPage extends React.Component {
    constructor(props) {
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        var date = new Date()
        super(props)
        this.state = {
            dataSource: [],
            previewSource: [],
            failMessage: [],
            maxPreviewRow: 50,  //excel预览的条数
            recordSaveLoading: false,
            spinLoading: false,
            percentCount: 0,
            batchSize: 1000,
            startDate: moment(date).format(dayFormat),
            stopDate: moment(date).format(dayFormat),
            userData: userData,
            leftData: [],
            total: 0,
            page: 1,
            pageSize: 10,
            size: 'small',
            curPageDetail: PAGE_NUM_MORE_STATUS[0].code,
            type: 'String',
            rightColumns: [],
            activeKey: '1'
        };
        this.timer = null;
        this.rightColumns = [{
            key: 1,
            title: 'A',
            dataIndex: 'A',
            align: 'center',
        }, {
            key: 2,
            title: 'B',
            dataIndex: 'proBductIP',
            align: 'center',
        }, {
            key: 3,
            title: 'C',
            dataIndex: 'C',
            align: 'center',
        }, {
            key: 5,
            title: 'D',
            dataIndex: 'D',
            align: 'center',
        }, {
            key: 6,
            title: 'E',
            dataIndex: 'E',
            align: 'center',
        },];
    }

    componentDidMount() {
        this.initData()
        this.loadLeftData()
    }
    componentWillUnmount() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
    }

    initData() {
        this.leftColumns = [{
            title: '代码',
            dataIndex: 'code',
            width: 80,
            align: 'center'
        }, {
            title: '描述',
            dataIndex: 'descripts',
            width: 200,
            align: 'center'
        }, {
            title: '方法名',
            dataIndex: 'methodName',
            width: 200,
            align: 'center'
        }, {
            title: '类名',
            dataIndex: 'className',
            width: 200,
            align: 'center'
        }, {
            title: '备注',
            dataIndex: 'note',
            width: 120,
            align: 'center'
        }];
        this.fullColumns = [{
            title: 'excel行数',
            dataIndex: 'rowNumber',
            width: 80,
            align: 'center'
        }, {
            title: '错误日志',
            dataIndex: 'errorMessage',
            width: 280,
            align: 'center'
        }];
        this.errColumns = [{
            title: 'excel行数',
            dataIndex: 'rowNumber',
            width: 80,
            align: 'center'
        }, {
            title: '错误日志',
            dataIndex: 'errorMessage',
            width: 280,
            align: 'center'
        }];
    }

    handleDel(data) {
        var params = {
            params: [
                {
                    userID: this.state.userData.userID,
                    hospID: this.state.userData.hospID,
                    groupID: this.state.userData.groupID,
                    id: [data.id]
                }
            ]
        }
        $http.post('urlDeault', this, {
            code: "01040202",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.loadLeftData(1);
                    message.success('删除成功！')
                }
            }
        });
    }

    handleDelRightData(data) {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                id: [data.id]
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040205",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.loadRightData(1);
                    message.success('删除成功！')
                }
            }
        });
    }

    editData(data) {
        this.setState({
            isShowSourceTypeModal: true,
            recordData: data
        })
    }

    loadLeftData() {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040203",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        leftData: res.result.data
                    })
                }
            }
        });
    }

    loadRightColumns() {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                importRulesID: this.state.leftRowID
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040206",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    var columns = res.result.data;
                    if (!Util.isEmpty(columns)) {
                        for (var i = 0; i < columns.length; i++) {
                            this.state.rightColumns.push({
                                title: columns[i].code,
                                dataIndex: columns[i].code,
                                required: columns[i].required,
                                type: columns[i].type,
                                errStatus: 'errStatus',
                                width: 150,
                                textAlign: 'center',
                                render: (text, data, index) => {
                                    return <span style={{ color: text == 'flag' ? 'red' : '' }}>{text == 'flag' ? '必填数据不能为空' : text}</span>
                                }
                            })
                        }
                    }
                    this.setState({
                        dataSource: res.result.rowData
                    })
                }
            }
        });
    }

    loadRightData(page, pageSize, e) {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                importRulesID: this.state.leftRowID
            }],
            pagination: [{
                pageSize: this.state.size == 'small' ? this.state.pageSize : PAGE_NUM_MORE_STATUS[0].code,
                currentPage: page
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040206",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        dataSource: res.result.data,
                        total: res.result.totalCount,
                        page: page,
                        search: 'search'
                    })
                }
            }
        });
    }

    //点击行，渲染当前行样式
    onClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    leftRowID: record.id,
                    leftRecord: record,
                    rightColumns: [],
                    importDataErr: [],
                    previewSource: [],
                    total: 0,
                    failMessage: [],
                }, () => {
                    this.loadRightColumns()
                });
            },
        };
    }

    onClickRightRow = (record) => {
        var date = new Date()
        return {
            onClick: () => {
                if (this.state.rightRowID == record.id) {
                    this.setState({
                        rightRowID: '',
                        code: undefined,
                        descripts: undefined,
                        enDescripts: undefined,
                        note: undefined,
                        required: false,
                        type: 'String',
                        startDate: moment(date).format(dayFormat),
                        stopDate: ''
                    });
                } else {
                    this.setState({
                        rightRowID: record.id,
                        code: record.code,
                        descripts: record.descripts,
                        enDescripts: record.enDescripts,
                        note: record.note,
                        required: record.required == 'Y' ? true : false,
                        type: record.type,
                        startDate: record.startDate ? moment(record.startDate).format(dayFormat) : moment(date).format(dayFormat),
                        stopDate: record.stopDate ? moment(record.stopDate).format(dayFormat) : ''
                    });
                }
            },
        };
    }

    //点击行，渲染当前行样式
    setRowRightClassName = (record) => {
        return record.id === this.state.rightRowID ? 'clickRowStyle' : '';
    }

    //分页切换
    onChange(e) {
        this.setState({ page: e }, () => {
            this.loadRightData(e);
        });
    }

    //分页切换
    changePageSize(current, pageSize) {
        this.setState({ pageSize: pageSize, page: current }, () => {
            this.loadRightData(current, pageSize);
        });
    }


    //点击行，渲染当前行样式
    setRowClassName = (record) => {
        return record.id === this.state.leftRowID ? 'clickRowStyle' : '';
    }

    hideModal(name) {
        this.setState({
            [name]: false,
            recordData: {}
        })
    }

    //添加数据类型弹框
    showSourceType() {
        this.setState({
            isShowSourceTypeModal: true
        })
    }

    updateSourceType(data) {
        var params = {
            params: [{
                ...data,
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040201",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('操作成功！')
                    this.hideModal('isShowSourceTypeModal')
                    this.loadLeftData(1)
                }
            }
        });
    }

    //清空输入框
    cleanInput() {
        var date = new Date()
        this.props.form.resetFields();
        this.setState({
            code: undefined,
            descripts: undefined,
            enDescripts: undefined,
            required: false,
            type: 'String',
            startDate: moment(date).format(dayFormat),
            stopDate: '',
            rightRowID: ''
        })
    }

    changeDate(name, e) {
        this.setState({
            [name]: e ? moment(e).format(dayFormat) : ''
        })
    }

    onChangeSwitch(name, checked) {
        this.setState({
            [name]: checked ? 'Y' : 'N'
        })
    }

    handleSaveList() {
        let { validateFields } = this.props.form;
        validateFields({ force: true }, (err, params) => {
            if (err) {
                return;
            }
            var data = {
                params: [{
                    ...params,
                    importRulesID: this.state.leftRowID,
                    required: params.required == true ? 'Y' : 'N',
                    userID: this.state.userData.userID,
                    hospID: this.state.userData.hospID,
                    groupID: this.state.userData.groupID,
                    id: this.state.rightRowID,
                    startDate: params.startDate ? moment(params.startDate).format(dayFormat) : '',
                    stopDate: params.stopDate ? moment(params.stopDate).format(dayFormat) : '',
                }]
            }

            $http.post('urlDeault', this, {
                code: "01040204",
                data: data,
                success: function (res) {
                    if (res.errorCode == '0') {
                        this.cleanInput()
                        message.success('保存成功')
                        this.loadRightData(1)
                    }
                }
            });
        });
    }

    handleExport() {
        this.setState({
            exportLoading: true,
        }, () => {
            this.loadExportMsg(1)
        })
    }

    loadExportMsg(page, pageSize, e) {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                importRulesID: this.state.leftRowID
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040206",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        exportData: res.result.data,
                        exportLoading: false,
                    }, () => {
                        handleExcel.exportExcel(this.state.rightColumns, this.state.dataSource, '列表维护表格')
                        message.success('导出成功！')
                    })
                }
            }
        });
    }

    SelectFile = () => {
        this.fileInput.click()
    }

    // ReadExcelFile = (file) => {
    //     const { files } = file.target;
    //     // 通过FileReader对象读取文件
    //     const fileReader = new FileReader();
    //     this.setState({
    //         spinLoading: true,
    //         percentCount: 1
    //     })
    //     fileReader.onload = event => {
    //         try {
    //             const { result } = event.target;
    //             // 以二进制流方式读取得到整份excel表格对象
    //             const workbook = XLSX.read(result, { type: 'binary' });
    //             let data = []; // 存储获取到的数据
    //             // 遍历每张工作表进行读取（这里默认只读取第一张表
    //             this.setState({ percentCount: 50 }, () => {
    //                 this.forceUpdate();
    //             });
    //             for (const sheet in workbook.Sheets) {
    //                 if (workbook.Sheets.hasOwnProperty(sheet)) {
    //                     // 利用 sheet_to_json 方法将 excel 转成 json 数据
    //                     data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]), { defval: "" });
    //                     break; // 如果只取第一张表，就取消注释这行
    //                 }
    //             }
    //             this.setState({ percentCount: 90 }, () => {
    //                 this.forceUpdate();
    //             });
    //             if (data.length > 0) {
    //                 var importData = []
    //                 var errData = []
    //                 var previewData = []
    //                 // data = data.slice(0)
    //                 var requiredField = this.state.rightColumns
    //                 for (var i = 0; i < data.length; i++) {
    //                     var itemData = data[i]
    //                     if (typeof itemData["__rowNum__"] === "undefined") continue
    //                     itemData.excelRowNum = itemData["__rowNum__"] + 1
    //                     importData.push(itemData)
    //                     for (var j = 0; j < requiredField.length; j++) {
    //                         var itemField = requiredField[j]
    //                         if (typeof itemData[itemField.dataIndex] === "undefined") {
    //                             // itemData[itemField.dataIndex]='(数据不能为空)'
    //                             errData.push(itemData)
    //                         } else {
    //                             if (itemData[itemField.dataIndex] === "") {
    //                                 // itemData[itemField.dataIndex]='数据不能为空'
    //                                 errData.push(itemData)
    //                             }
    //                         }
    //                     }
    //                 }
    //                 this.setState((s) => { return { percentCount: 100 } });
    //                 // 限制预览数量
    //                 if (importData.length > this.state.maxPreviewRow) {
    //                     previewData = importData.slice(0, this.state.maxPreviewRow)
    //                 } else {
    //                     previewData = importData
    //                 }

    //                 console.log('data', data)
    //                 console.log('importData', importData)
    //                 console.log('previewData', previewData)
    //                 console.log('errData', errData)
    //                 this.setState({
    //                     spinLoading: false,
    //                     data: data,
    //                     dataSource: importData,
    //                     previewSource: previewData,
    //                     total: data.length,
    //                     importDataErr: errData,
    //                     totalErr: errData.length,
    //                 })
    //                 this.fileInput.value = ""
    //             }
    //         } catch (e) {
    //             // 这里可以抛出文件类型错误不正确的相关提示
    //             console.log(e);
    //             return;
    //         }
    //     };
    //     // 以二进制方式打开文件
    //     fileReader.readAsBinaryString(files[0]);
    // }

    ReadExcelFile = async (file) => {
        try {
            const { files } = file.target;
            // 通过FileReader对象读取文件
            const fileReader = new FileReader();
            // let _this = this;
            this.setState({ spinLoading: true });
            // this.timer = setInterval(() => {
            //     _this.handleTurnOnTimer();
            // }, 300);
            let workbook;
            // 利用Promise改造回调函数结构
            await new Promise((resolve, reject) => {
                fileReader.onload = event => {
                    try {
                        const { result } = event.target;
                        workbook = XLSX.read(result, { type: 'binary' });
                        resolve();
                    } catch (e) {
                        reject(e);
                    }
                };
                // 以二进制方式打开文件
                fileReader.readAsBinaryString(files[0]);
            });
            this.processWorkbook(workbook);
        } catch (error) {
            console.error(error);
        }
    }

    handleTurnOnTimer = () => {
        try {
            let { percentCount } = this.state;
            if (percentCount < 90) {
                this.setState({ percentCount: percentCount + 1 }, () => {
                    // this.forceUpdate();
                    console.log('触发了', this.state.percentCount)
                });
            } else {
                clearInterval(this.timer);
                this.timer = null;
            }
        } catch (error) {
            console.log(error);
        }
    }

    // 将workbook处理逻辑单独抽离成一个函数 提高可读性 并便于维护
    processWorkbook = (workbook) => {
        let data = [];
        for (const sheet in workbook.Sheets)
            if (workbook.Sheets.hasOwnProperty(sheet))
                data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]), { defval: '' });
        this.setState({ percentCount: 95 });
        var importData = [], errData = [], previewData = [];
        var requiredField = this.state.rightColumns;
        // 使用forEach替换for循环，并使用filter找出空值或未定义字段。
        // importData = data && data.filter(item => {
        //     item.excelRowNum = item['__rowNum__'] + 1;
        //     return requiredField.every(field => {
        //         if (typeof item[field.dataIndex] === 'undefined') {
        //             return false;
        //         } else if (item[field.dataIndex] === '') {
        //             errData.push(item);
        //             return true;
        //         } else {
        //             return true;
        //         }
        //     });
        // });
        for (var i = 0; i < data.length; i++) {
            var itemData = data[i]
            if (typeof itemData['__rowNum__'] === 'undefined') continue
            itemData.excelRowNum = itemData['__rowNum__'] + 1
            importData.push(itemData)
            for (var j = 0; j < requiredField.length; j++) {
                var itemField = requiredField[j]
                if (typeof itemData[itemField.dataIndex] === 'undefined') {
                    errData.push(itemData)
                } else {
                    if (itemData[itemField.dataIndex] === '') {
                        errData.push(itemData)
                    }
                }
            }
        }
        //限制预览数量
        previewData = importData.slice(0, Math.min(importData.length, this.state.maxPreviewRow));
        this.setState({
            spinLoading: false,
            data: data,
            dataSource: importData,
            previewSource: previewData,
            total: data.length,
            importDataErr: errData,
            totalErr: errData.length,
            percentCount: 100
        }, () => {
            setTimeout(() => {
                this.setState({ percentCount: 0 });
            }, 300)
        });
    }

    // importDataList() {
    //     var { dataSource, batchSize } = this.state;
    //     var errColumns = this.state.rightColumns;
    //     var errData = dataSource.slice(1);

    //     this.setState({
    //         recordSaveLoading: true,
    //         percentCount: 0
    //     });

    //     if (!Util.isEmpty(errColumns) && !Util.isEmpty(errData)) {
    //         for (var i = 0; i < errColumns.length; i++) {
    //             for (var j = 0; j < errData.length; j++) {
    //                 if (errData[j].hasOwnProperty(errColumns[i].dataIndex) && errData[j][errColumns[i].dataIndex] == 'flag') {
    //                     errData[j][errColumns[i].dataIndex] = undefined;
    //                 }
    //             }
    //         }
    //     }

    //     // 分批次导入
    //     let batchData = [];
    //     for (var i = 0; i < errData.length; i += batchSize) {
    //         if ((i + batchSize) >= errData.length) {
    //             batchData.push(errData.slice(i));
    //         } else {
    //             batchData.push(errData.slice(i, i + batchSize));
    //         }
    //     }
    //     let promiseList = batchData.map((item, index) => this.uploadImportData(item));
    //     Promise.all(promiseList).then(res => {
    //         let ret = { result: { successNum: 0, failNum: 0, repeatNum: 0, repeatList: [], failMessage: [] } }
    //         res.forEach(data => {
    //             ret.result.successNum += data.result.successNum;
    //             ret.result.failNum += data.result.failNum;
    //             ret.result.repeatNum += data.result.repeatNum;
    //             ret.result.repeatList = ret.result.repeatList.concat(data.result.repeatList);
    //             ret.result.failMessage = ret.result.failMessage.concat(data.result.failMessage);
    //         });

    //         // 显示最终结果
    //         this.setState({
    //             percentCount: 100,
    //             recordSaveLoading: false
    //         })
    //         this.showImportResultModal(ret);
    //     }).catch(err => {
    //         this.setState({
    //             recordSaveLoading: false
    //         })
    //         console.log(err);
    //     });
    // }

    // 单批次导入
    // uploadImportData = (batchData) => {
    //     return new Promise((resolve, reject) => {
    //         var params = {
    //             params: [{
    //                 userID: this.state.userData.userID,
    //                 hospID: this.state.userData.hospID,
    //                 className: !Util.isEmpty(this.state.leftRecord) ? this.state.leftRecord.className : '',
    //                 methodName: !Util.isEmpty(this.state.leftRecord) ? this.state.leftRecord.methodName : '',
    //                 data: batchData
    //             }]
    //         }
    //         $http.post('urlDeault', this, {
    //             code: "01040207",
    //             data: params,
    //             success: (res) => {
    //                 if (res.errorCode == '0') {
    //                     this.setState((s) => {
    //                         let percent = s.percentCount + (100 / (s.dataSource.length / s.batchSize));
    //                         return { percentCount: Math.round(percent, 2) }
    //                     }, () => {
    //                         this.forceUpdate();
    //                     });
    //                     resolve(res)
    //                     return;
    //                 }
    //                 reject(res);
    //             },
    //             fail: (err) => {
    //                 reject(err);
    //             }
    //         });
    //     });
    // }

    // 数组分段
    handleChunk = (array, size) => {
        var result = [];
        for (var i = 0; i < array.length; i += size) {
            result.push(array.slice(i, i + size));
        }
        return result;
    }

    importDataList() {
        var { dataSource, batchSize } = this.state;
        var errColumns = this.state.rightColumns;
        var errData = dataSource.slice(1);
        this.setState({
            recordSaveLoading: true,
            percentCount: 0
        });
        // 分批次处理错误列和行
        const chunks = this.handleChunk(errData, batchSize);
        chunks.forEach(chunk => {
            chunk.forEach(row => {
                errColumns.forEach(col => {
                    if (row[col.dataIndex] === 'flag') row[col.dataIndex] = undefined;
                });
            });
        });
        let promiseList = chunks.map((item) => this.uploadImportData(item));
        Promise.all(promiseList).then(res => {
            let ret = res.reduce((total, current) => {
                total.result.successNum += current.result.successNum;
                total.result.failNum += current.result.failNum;
                total.result.repeatNum += current.result.repeatNum;
                total.result.repeatList = total.result.repeatList.concat(current?.result?.repeatList || []);
                total.result.failMessage = total.result.failMessage.concat(current.result?.failMessage || []);
                return total;
            }, { result: { successNum: 0, failNum: 0, repeatNum: 0, repeatList: [], failMessage: [] } });
            // 显示最终结果
            this.setState({
                percentCount: 100,
                recordSaveLoading: false
            })
            this.showImportResultModal(ret);
        }).catch(err => {
            this.setState({
                recordSaveLoading: false
            })
        })
    }

    uploadImportData = (batchData) => {
        return new Promise((resolve, reject) => {
            const params = {
                params: [{
                    userID: this.state.userData.userID,
                    hospID: this.state.userData.hospID,
                    className: !Util.isEmpty(this.state.leftRecord) ? this.state.leftRecord.className : '',
                    methodName: !Util.isEmpty(this.state.leftRecord) ? this.state.leftRecord.methodName : '',
                    data: batchData
                }]
            }
            $http.post('urlDeault', this, {
                code: '01040207',
                data: params,
                success: (res) => {
                    if (res.errorCode == '0') {
                        resolve(res)
                    } else {
                        reject(res)
                    }
                },
                fail: (err) => { reject(err) }
            })
        })
    }

    // 显示导入结果
    showImportResultModal = (res) => {
        let that = this;
        // 为提升性能，预览错误信息的条数不能超过设定的最大预览数量
        let previewFailMessage = res.result.failMessage
        if (res.result.failMessage.length > this.state.maxPreviewRow) {
            previewFailMessage = res.result.failMessage.slice(0, this.state.maxPreviewRow)
        }
        Modal.success({
            title: '本次导入结果：',
            content: <div>
                <h4>导入成功数：<span style={{ color: '#1999db', fontSize: '16px' }}>{res.result?.successNum || ''}</span></h4>
                <h4>导入失败数：<span style={{ color: 'red', fontSize: '16px' }}>{res.result?.failNum || ''}</span>&nbsp;&nbsp;
                    失败信息，请查看错误日志；</h4>
                <h4>导入重复数：<span style={{ color: 'orange', fontSize: '16px' }}>{res.result?.repeatNum || ''}</span>&nbsp;&nbsp;
                    <span>重复Excel对应行数：{!Util.isEmpty(res.result.repeatList) ? res.result.repeatList.join(',') : 0}</span>
                </h4>
            </div>,
            onOk: () => {
                if (!Util.isEmpty(res.result.failMessage)) {
                    that.setState({
                        activeKey: '3',
                        fullMessage: res.result.failMessage,
                        failMessage: previewFailMessage
                    })
                }
            },
        });
    }

    changeActiveKey(e) {
        var errColumns = this.state.rightColumns;
        var errData = this.state.dataSource.slice(1);
        if (!Util.isEmpty(errColumns) && !Util.isEmpty(errData)) {
            for (var i = 0; i < errColumns.length; i++) {
                for (var j = 0; j < errData.length; j++) {
                    if (errColumns[i].required == 'Y' && errData[j].hasOwnProperty(errColumns[i].dataIndex) == false && Util.isEmpty(errData[j][errColumns[i].dataIndex])) {
                        errData[j][errColumns[i].dataIndex] = 'flag';
                    }
                }
            }
        }
        this.setState({
            activeKey: e
        })
    }

    render() {
        let { spinLoading, recordSaveLoading, rightColumns } = this.state

        var col = [{
            title: 'excel行数',
            dataIndex: 'excelRowNum',
            width: 100
        }]
        var importStatus = false;
        var errColumns = this.state.rightColumns;
        var errData = this.state.dataSource.slice(1);
        if (!Util.isEmpty(errColumns) && !Util.isEmpty(errData)) {
            for (var i = 0; i < errColumns.length; i++) {
                for (var j = 0; j < errData.length; j++) {
                    if (errColumns[i].required == 'Y' && errData[j].hasOwnProperty(errColumns[i].dataIndex) == false && Util.isEmpty(errData[j][errColumns[i].dataIndex])) {
                        errData[j][errColumns[i].dataIndex] = 'flag';
                        importStatus = true
                    }
                }
            }
        }

        return (<div style={{ background: '#F1F1F1' }} className="import-data-body">

            <Card style={{ height: '100%', width: '30%', float: 'left' }} title={'数据类型'} className='left-table-scroll-body'>
                <Table columns={this.leftColumns}
                    dataSource={this.state.leftData}
                    bordered
                    onRow={this.onClickRow}
                    scroll={{ x: 600, y: store.getState().tableHeight.y + 134 }}
                    rowClassName={this.setRowClassName}
                    rowKey={(data) => {
                        return data.id
                    }}
                    pagination={false}>
                </Table>
            </Card>
            <Card style={{ height: '100%', width: '69.7%', float: 'right' }} title="列表维护"
                extra={<div><Button onClick={this.handleExport.bind(this)} disabled={!Util.isEmpty(this.state.rightColumns) ? false : true}
                    loading={this.state.exportLoading}>导出</Button>
                    <span style={{ marginLeft: 5 }}>
                        <Button type="primary" onClick={this.SelectFile} disabled={!Util.isEmpty(this.state.rightColumns) ? false : true}>选择文件</Button>
                        <input type='file' accept='.xlsx, .xls' style={{ display: 'none' }} onChange={this.ReadExcelFile} ref={el => this.fileInput = el} />
                    </span>
                    <Button style={{ marginLeft: 5 }} onClick={this.importDataList.bind(this)}
                        disabled={(Util.isEmpty(this.state.rightColumns) || importStatus || Util.isEmpty(this.state.dataSource.slice(1))) ? true : false}>导入</Button>
                </div>}>
                <Spin
                    spinning={spinLoading || recordSaveLoading}
                    // indicator={null}
                    tip={(
                        <div style={{ textAlign: 'center' }}>
                            {/* <Progress style={{ width: '240px' }} percent={percentCount} /> */}
                            <div>
                                {spinLoading ? '正在读取Excel数据……' : (recordSaveLoading ? '数据导入中，请耐心等待…' : '')}
                            </div>
                        </div>
                    )}>
                    <Tabs onChange={this.changeActiveKey.bind(this)} type='card' activeKey={this.state.activeKey}>
                        <TabPane tab='导入数据' key='1'>
                            <Table
                                columns={rightColumns && rightColumns.length > 0 ? rightColumns : this.rightColumns}
                                className='right-table-scroll-body'
                                dataSource={this.state.previewSource}
                                bordered
                                onRow={this.onClickRightRow}
                                // rowClassName={this.setRowRightClassName}
                                scroll={{ x: 600, y: store.getState().tableHeight.y + 62 }}
                                rowKey={(data) => {
                                    return data.id
                                }}
                                pagination={false}>
                            </Table>

                            <CommonPagination size={this.state.size} current={this.state.page} total={this.state.total}
                                search={this.state.search}
                                onShowSizeChange={this.changePageSize.bind(this)} complete={true} dataSource={this.state.previewSource}
                                onChange={this.onChange.bind(this)} />
                        </TabPane>
                        {/* <TabPane tab='数据校验' key='2'>
                        <Table columns={col.concat(errColumns)} className='right-table-scroll-body'
                            dataSource={errData}
                            bordered
                            // rowClassName={this.setRowRightClassName}
                            scroll={{ x: 1600, y: '71vh' }}
                            rowKey={(data) => {
                                return data.id
                            }}
                            pagination={false}> </Table>
                    </TabPane> */}
                        <TabPane tab='错误日志' key='3' disabled={Util.isEmpty(this.state.failMessage) ? true : false}>
                            <Table
                                columns={this.fullColumns}
                                className='right-table-scroll-body'
                                dataSource={this.state.failMessage}
                                bordered
                                // rowClassName={this.setRowRightClassName}
                                scroll={{ y: store.getState().tableHeight.y + 62 }}
                                rowKey={(data) => {
                                    return data.id
                                }}
                                pagination={false}>
                            </Table>
                        </TabPane>
                    </Tabs>
                </Spin>
            </Card>
        </div>)
    }
};

export default ImportDataPage;