// 数据维护 - 新增配置
import React, { Component } from 'react';
import {
    Table, Button, Select, message, Pagination, Modal, Tabs, Input
} from 'antd';
import { $http } from '../../containers/config/https';
import '../../assets/css/App.css';
import * as XLSX from 'xlsx';
const TabPane = Tabs.TabPane;
class CBDataImport extends Component {
    constructor(props) {
        super(props);
        this.state = {
            fieldsColumn: [],
            dataColumn: [],
            dataColumnErr: [],
            dataColumnLog: [],
            excelData: [],
            visible: false,
            editField: [],
            importData: [],
            pageSize: 10,
            currentPage: 1,
            importDataErr: [],
            pageSizeErr: 10,
            currentPageErr: 1,
            requiredField: [],
            data: [],
            editField: [],
            importDataLog: [],
            pageSizeLog: 10,
            currentPageLog: 1,
            importRows: 1000
        };
        this.dataColumnLog = [
            {
                title: "Excel行号",
                dataIndex: "excelRowNum",
                width: 100,
                align: "center"
            }, {
                title: "属性",
                dataIndex: "errorField",
                width: 100,
                align: "center"
            }, {
                title: "错误代码",
                dataIndex: "errorCode",
                width: 100,
                align: "center"
            }, {
                title: "错误原因",
                dataIndex: "errorMessage",
                width: 100,
                align: "center"
            }
        ]
    }

    ShowMessage = () => {
        const hide = message.loading('正在载入数据..', 0);
        return hide
    }

    ReadExcelFile = (file) => {
        const { files } = file.target;
        // 通过FileReader对象读取文件
        const fileReader = new FileReader();

        fileReader.onload = event => {
            try {
                const { result } = event.target;
                // 以二进制流方式读取得到整份excel表格对象
                const workbook = XLSX.read(result, { type: 'binary' });
                let data = []; // 存储获取到的数据
                // 遍历每张工作表进行读取（这里默认只读取第一张表）
                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; // 如果只取第一张表，就取消注释这行
                    }
                }
                if (data.length > 0) {

                    var importData = []
                    var errData = []
                    data = data.slice(1)
                    var requiredField = this.state.requiredField
                    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.Code] === "undefined") {
                                //itemData[itemField.Code]="(数据不能为空)"
                                errData.push(itemData)
                            } else {
                                if (itemData[itemField.Code] === "") {
                                    //itemData[itemField.Code]="(数据不能为空)"
                                    errData.push(itemData)
                                }
                            }
                        }
                    }

                    this.setState({
                        data: data,
                        importData: importData,
                        total: data.length,
                        importDataErr: errData,
                        totalErr: errData.length,
                    })
                    this.fileInput.value = ""

                }
            } catch (e) {
                // 这里可以抛出文件类型错误不正确的相关提示
                console.log(e);
                return;
            }
        };
        // 以二进制方式打开文件
        fileReader.readAsBinaryString(files[0]);
    }

    componentDidMount() {
        var className = this.props.className
        this.getEditField(className)
    }

    componentWillReceiveProps(nextProps) {
        let className = ""
        if (nextProps.className !== undefined) {
            className = nextProps.className
            if (className === this.props.className) {
                return
            }
        } else {
            className = ""
        }
        if (className !== "") {
            this.getEditField(className)
            this.setState({
                importData: [],
                importDataErr: [],
                total: 0,
                totalErr: 0
            })
        }
    }
    
    getEditField = (className) => {
        let data = {
            params: [{
                ClassName: className,
                groupId: "",
                hospitalId: ""
            }]
        }
        $http.post("urlS", this, {
            code: "4004",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    var fieldArr = []
                    fieldArr = res.result.Data
                    var requiredField = []
                    var dataColumn = []
                    var dataColumnErr = []
                    dataColumnErr.push({
                        title: "Excel行号",
                        dataIndex: "excelRowNum",
                        className: className,
                        width: 100,
                        align: "center"
                    })
                    var requiredFlag = 0
                    for (var i = 0; i < fieldArr.length; i++) {
                        var itemData = fieldArr[i]
                        var ReadOnlyFlag = itemData.ReadOnlyFlag
                        if (ReadOnlyFlag === "Y") continue
                        var className = ""
                        requiredFlag = 0
                        for (var j = 0; j < itemData.rules.length; j++) {
                            var ruleItem = itemData.rules[j]
                            if ((ruleItem.required) && (ruleItem.required === "true")) {
                                requiredField.push(itemData)
                                requiredFlag = 1
                            }
                        }
                        var itemColumn =
                        {
                            title: itemData.Code,
                            dataIndex: itemData.Code,
                            width: 100,
                            align: "center"
                        }
                        dataColumn.push(itemColumn)
                        if (requiredFlag === 1) {
                            var itemColumnErr = {
                                title: itemData.Code,
                                dataIndex: itemData.Code,
                                width: 100,
                                align: "center",
                                render: (text, record, index) => {
                                    if (typeof text === "undefined") {
                                        return (<span style={{ color: 'red' }}>(数据不能为空)</span>)
                                    } else {
                                        if (text === "") {
                                            return (<span style={{ color: 'red' }}>(数据不能为空)</span>)
                                        }
                                    }
                                    return text
                                }

                            }
                        } else {
                            var itemColumnErr = {
                                title: itemData.Code,
                                dataIndex: itemData.Code,

                                width: 100,
                                align: "center"
                            }
                        }

                        dataColumnErr.push(itemColumnErr)
                    }
                    this.setState({
                        requiredField: requiredField,
                        dataColumn: dataColumn,
                        dataColumnErr: dataColumnErr
                    })
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            }
        })
    }

    handleCancel = () => {
        this.setState({
            visible: false
        })
    }

    handleOk = () => {
        this.setState({
            visible: false
        })
    }

    DrawerShow = () => {
        this.setState({
            visible: true
        })
    }

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

    onChangePage = (page) => {
        this.setState({
            currentPage: page,
        });
    }

    onChangePageErr = (page) => {
        this.setState({
            currentPageErr: page,
        });
    }

    onChangePageLog = (page) => {
        this.setState({
            currentPageLog: page,
        });
    }

    ImportData = () => {
        var importRows = this.state.importRows
        if (importRows != "") {
            this.ImportDataNew(0)
            return
        }

        var importData = this.state.importData
        if (importData.length <= 0) {
            message.error("没有要导入的数据");
            return
        }
        var importDataErr = this.state.importDataErr
        if (importDataErr.length > 0) {
            message.error("存在错误的数据,不能导入!");
            return
        }
        var className = this.props.className
        let data = {
            params: [{
                className: className,
                data: this.state.importData
            }]
        }
        const hide = message.loading('正在导入数据..', 0);
        $http.post("urlS", this, {
            code: "4030",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    var success = res.success
                    var error = res.error
                    this.setState({
                        importDataLog: res.errData,
                        totalLog: res.errData.length
                    })
                    setTimeout(hide, 100);
                    if (error === 0) {
                        message.info("导入成功" + success + "条数据");
                    } else {
                        message.info("导入成功" + success + "条数据,失败" + error + "条数据,详细错误信息请查看错误日志");
                    }

                } else {
                    setTimeout(hide, 100);
                    message.error('失败：' + res.errorMessage);
                }
            }
        })
    }

    ImportDataNew = (index) => {
        var importData = this.state.importData
        var importRows = this.state.importRows
        importRows = parseInt(importRows)
        if (importRows <= 0) return
        var className = this.props.className
        var itemArr = this.state.importData.slice(index * importRows, (index + 1) * importRows)
        console.log(itemArr.length)
        if (typeof itemArr === "undefined") return
        if (itemArr.length === 0) {
            message.success("数据导入完成")
            return
        }
        let data = {
            params: [{
                className: className,
                data: itemArr
            }]
        }
        message.success('正在导入第' + (index * importRows + 1) + "到" + ((index + 1) * importRows) + "条数据");
        $http.post("urlS", this, {
            code: "4030",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    // message.success('正在导入第'+(start+1)+"到"+(end+1)+"条数据");   
                    var importDataLog = this.state.importDataLog
                    if (typeof res.errData !== "undefined") {
                        importDataLog = importDataLog.concat(res.errData)
                        this.setState({
                            importDataLog: importDataLog,
                            totalLog: importDataLog.length
                        })
                    }
                    this.ImportDataNew(index + 1)
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            }
        })

    }

    ImportDataNew1 = () => {
        var importData = this.state.importData
        var className = this.props.className
        var i = 0
        var importRows = this.state.importRows
        importRows = parseInt(importRows)
        if (importRows <= 0) return
        while (i < importData.length) {
            var itemArr = []
            var start = i
            var end = i + importRows - 1
            if (end >= importData.length) {
                end = importData.length - 1
            }
            i = i + importRows
            itemArr = this.state.importData.slice(start, end + importRows - 1)
            let data = {
                params: [{
                    className: className,
                    data: itemArr
                }]
            }
            message.success('正在导入第' + (start + 1) + "到" + (end + 1) + "条数据");
            $http.post("urlS", this, {
                code: "4030",
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        // message.success('正在导入第'+(start+1)+"到"+(end+1)+"条数据");   
                        var importDataLog = this.state.importDataLog
                        if (typeof res.errData !== "undefined") {
                            importDataLog = importDataLog.concat(res.errData)

                            this.setState({
                                importDataLog: importDataLog,
                                totalLog: importDataLog.length
                            })
                        }
                    } else {
                        message.error('失败：' + res.errorMessage);
                    }
                }
            })
        }
    }

    RowsChange = (e) => {
        var importRows = e.target.value
        this.setState({
            importRows: importRows
        })
    }

    render() {
        return (
            <Modal
                title={"数据维护"}
                width={1000}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                visible={this.state.visible}
                style={{ top: 20 }}
                height={600}
            >
                <div>
                    <Button type="primary" onClick={this.SelectFile}>选择文件</Button>
                    <input type='file' accept='.xlsx, .xls' style={{ display: 'none' }} onChange={this.ReadExcelFile} onClick={this.handleClick} ref={el => this.fileInput = el} />
                    <Button type="primary" onClick={this.ImportData}>导入</Button>
                    单次导入条数:<Input style={{ width: '100px' }} value={this.state.importRows} onChange={this.RowsChange} />
                </div>
                <div>

                    <Tabs type="card">
                        <TabPane tab="全部数据" key="1">

                            <Table
                                dataSource={this.state.importData.slice((this.state.currentPage - 1) * this.state.pageSize, (this.state.currentPage - 1) * this.state.pageSize + this.state.pageSize)}
                                columns={this.state.dataColumn}
                                rowClassName={this.setRowClassName}
                                pagination={false}
                                bordered
                                onRow={this.onClickRow}
                                rowKey="ID"
                                style={{ height: 550 }}
                                scroll={{ x: this.state.TableWidth, y: 450 }}
                            //rowSelection={{onChange:this.tableOnChange,type:"radio"}}
                            />
                            <Pagination
                                size="small"
                                showQuickJumper
                                showSizeChanger
                                defaultCurrent={1}
                                current={this.state.currentPage}
                                total={this.state.total}
                                onChange={this.onChangePage}
                                defaultPageSize={10}
                                onShowSizeChange={this.onShowSizeChange}
                                style={{ textAlign: "right", marginTop: '0px' }}
                                showTotal={(e) => { return "共 " + e + " 条" }}
                            />
                        </TabPane>
                        <TabPane tab="有问题数据" key="2">

                            <Table
                                dataSource={this.state.importDataErr.slice((this.state.currentPageErr - 1) * this.state.pageSizeErr, (this.state.currentPageErr - 1) * this.state.pageSizeErr + this.state.pageSizeErr)}
                                columns={this.state.dataColumnErr}
                                rowClassName={this.setRowClassName}
                                pagination={false}
                                bordered
                                onRow={this.onClickRow}
                                rowKey="ID"
                                style={{ height: 550 }}
                                scroll={{ x: this.state.TableWidth, y: 450 }}
                            />
                            <Pagination
                                size="small"
                                showQuickJumper
                                showSizeChanger
                                defaultCurrent={1}
                                current={this.state.currentPageErr}
                                total={this.state.totalErr}
                                onChange={this.onChangePageErr}
                                defaultPageSize={10}
                                onShowSizeChange={this.onShowSizeChangeErr}
                                style={{ textAlign: "right", marginTop: '0px' }}
                                showTotal={(e) => { return "共 " + e + " 条" }}
                            />
                        </TabPane>
                        <TabPane tab="错误日志" key="3">

                            <Table
                                dataSource={this.state.importDataLog.slice((this.state.currentPageLog - 1) * this.state.pageSizeLog, (this.state.currentPageLog - 1) * this.state.pageSizeLog + this.state.pageSizeLog)}
                                columns={this.dataColumnLog}
                                rowClassName={this.setRowClassName}
                                pagination={false}
                                bordered
                                onRow={this.onClickRow}
                                rowKey="ID"
                                style={{ height: 550 }}
                                scroll={{ x: this.state.TableWidth, y: 450 }}
                            />
                            <Pagination
                                size="small"
                                showQuickJumper
                                showSizeChanger
                                defaultCurrent={1}
                                current={this.state.currentPageLog}
                                total={this.state.totalLog}
                                onChange={this.onChangePageLog}
                                defaultPageSize={10}
                                onShowSizeChange={this.onShowSizeChangeLog}
                                style={{ textAlign: "right", marginTop: '0px' }}
                                showTotal={(e) => { return "共 " + e + " 条" }}
                            />
                        </TabPane>
                    </Tabs>
                </div>
            </Modal>
        );
    }
}

export default CBDataImport;