/*
* 导入
* */

import React, { Component } from 'react';
import {
    Input, Form, Select, Modal, Button, Progress, Tabs, message, Tooltip, Icon, Table,
    Card, Row, Col, DatePicker, Popconfirm, Radio
} from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import { PAGE_NUM_MORE_STATUS } from 'tools/statusConstants';
import { handleExcel } from 'tools/handleExcel.js';
import CommonPagination from 'components/pagination/index';
import * as XLSX from 'xlsx';
import '../style/index.less';
import moment from 'moment';

const Option = Select.Option;
const { TabPane } = Tabs;
const FormItem = Form.Item;
const { TextArea } = Input;

class ShowImportModal extends Component {

    constructor(props) {
        super(props);
        var date = new Date();
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            userData: userData,
            total: 0,
            page: 1,
            pageSize: 10,
            size: 'small',
            ids: [],
            totalCount: 0,
            dataSource: [],
            activeKey: '1',
            rightColumns: []
        }
    }
    componentWillReceiveProps(nextProp) {
        if (nextProp.isShow === true) {
            this.loadLeftData()
        } else if (this.props.isShow === false) {
            this.cleanInput();
        }
    }

    componentDidMount() {
        this.initData()
    }

    initData() {
        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'
                }
            ]
    }

    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') {
                    var leftData = res.result.data
                    var code = '', className = '', methodName = ''
                    if (!Util.isEmpty(leftData)) {
                        for (var i = 0; i < leftData.length; i++) {
                            if (leftData[i].code == '016') {
                                code = leftData[i].id
                                className = leftData[i].className
                                methodName = leftData[i].methodName
                            }
                        }
                    }
                    this.setState({
                        importID: code,
                        className: className,
                        methodName: methodName,
                    }, () => {
                        this.loadRightColumns()
                    })
                }
            }
        });
    }

    loadRightColumns() {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                groupID: this.state.userData.groupID,
                importRulesID: this.state.importID
            }]
        }
        $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.importID
            }],
            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'
                    })
                }
            }
        });
    }

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

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


    closeModal(name) {
        let { onHide } = this.props;
        onHide && onHide();
        this.cleanInput();
    }

    //清空输入框
    cleanInput() {
        this.setState({
            recordData: {},
            rightColumns: [],
            importDataErr: [],
            dataSource: []
        })
    }

    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.importID
            }]
        }
        $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();

        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){
                    for (var i = 0; i < data.length; i++) {
                        Object.keys(data[i]).forEach((keys) => {
                            if (keys == 'birthday' && (typeof data[i][keys] == 'number')) {
    
                                let date = new Date(1900, 0, data[i][keys] - 1).toLocaleDateString();
    
                                data[i][keys] = moment(date).format(dayFormat);
    
                            }
                        })
                    }
                }
                if (data.length > 0) {

                    var importData = []
                    var errData = []
                    // 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({
                        data: data,
                        dataSource: importData,
                        total: data.length,
                        importDataErr: errData,
                        totalErr: errData.length,
                    })
                    this.fileInput.value = ""

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

    importDataList() {
        var { dataSource } = this.state;
        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 (errData[j].hasOwnProperty(errColumns[i].dataIndex) && errData[j][errColumns[i].dataIndex] == 'flag') {
                        errData[j][errColumns[i].dataIndex] = undefined;
                    }
                }
            }
        }
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                className: this.state.className,
                methodName: this.state.methodName,
                data: errData
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040207",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    var that = this;
                    // if (!Util.isEmpty(res.result.failMessage)) {
                    //     message.error('导入失败')
                    //     this.setState({
                    //         activeKey: '3',
                    //         fullMessage: res.result.failMessage
                    //     })
                    // } else {
                    //     message.success('导入成功')
                    //     this.setState({
                    //         dataSource: []
                    //     })
                    // }
                    Modal.success({
                        title: '本次导入结果：',
                        content: <span>
                            <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>
                        </span>,

                        onOk() {
                            if (!Util.isEmpty(res.result.failMessage)) {
                                that.setState({
                                    activeKey: '3',
                                    fullMessage: res.result.failMessage
                                })
                            }
                        },
                    });
                }
            }
        });
    }

    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() {
        var col = [{
            title: 'excel行数',
            dataIndex: 'excelRowNum',
            width: 100
        }]
        var newColumns = []
        var importStatus = false;
        var errColumns = this.state.rightColumns;
        var errData = this.state.dataSource && 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>
            <Modal className='show-import-modal'
                title={'数据导入'}
                maskClosable={false}
                visible={this.props.isShow}
                onCancel={this.closeModal.bind(this)}
                footer={null}>
                <Card 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>}>
                    <Tabs onChange={this.changeActiveKey.bind(this)} type='card' activeKey={this.state.activeKey}>
                        <TabPane tab='导入数据' key='1'>
                            <Table columns={this.state.rightColumns} className='right-table-scroll-body'
                                dataSource={this.state.dataSource}
                                bordered
                                onRow={this.onClickRightRow}
                                scroll={{ x: 600, y: '48vh' }}
                                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.dataSource}
                                onChange={this.onChange.bind(this)} />
                        </TabPane>

                        <TabPane tab='错误日志' key='3' disabled={Util.isEmpty(this.state.fullMessage) ? true : false}>
                            <Table columns={this.fullColumns} className='right-table-scroll-body'
                                dataSource={this.state.fullMessage}
                                bordered
                                scroll={{ y: '48vh' }}
                                rowKey={(data) => {
                                    return data.id
                                }}
                                pagination={false}>
                            </Table>
                        </TabPane>
                    </Tabs>
                </Card>
            </Modal></div>
    }
}

export default Form.create()(ShowImportModal);