/**
 * 表结构导出，按照Excel模板导出 
 * */
import React, { Component } from 'react';
import {
    Table, Button, Input, Select, message, Col
} from 'antd';
import { handleExcel } from 'tools/handleExcel.js';
import { $http } from '../../containers/config/https';
import * as XLSX from 'xlsx';

const Option = Select.Option;
let userData;
class ExportTableToExcel extends Component {
    constructor(props) {
        userData = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {}
        super(props);
        this.state = {
            column: [],
            tableData: [],
            basicClassData: [],
            basicClassDataOth: [],
            tableDesc: "",
            tableWidth: 0,
            sheetName: 'mysheet',
        }
    }

    componentWillUnmount() {
        this.setState = (state, callback) => {
            return
        }
    }
    componentDidMount() {
        this.getColumn();
        this.getTable();
    }

    getTable = () => {
        let { page, pageSize } = this.state;
        let data = { params: [] }
        $http.post("urlS", this, {
            code: "4033",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({ basicClassData: res.result })
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        })
    }

    getColumn = () => {
        let data = {
            params: [{
                compontName: "ExportExcel",
                type: "C",
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    this.setState({
                        column: res.result.C,
                        tableWidth: res.totalWidth,
                    })
                }
            }
        })
    }
    getTableFiledData = (className, option) => {

        let data = {
            params: [{ ClassName: className }]
        }
        $http.post("urlS", this, {
            code: "01040091",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    var data = res.result
                    this.setState({
                        tableData: data,
                        tableDesc: option.props.descripts,
                        sheetName: option.props.table,
                    })
                } else {
                    message.error('失败：' + res.errorMessage);
                }
            },
            error: function (error) {
                message.error('失败：' + error);
            }
        })
    }
    onExportClick = () => {
        if (this.state.tableData.length == 0) {
            message.warn("没有要导出的数据!")
            return;
        }
        this.exportExcel(this.state.column, this.state.tableData, this.state.tableDesc, this.state.sheetName)
    }
    // 导出 Excel
    exportExcel = (headers, data, name = '导出表格数据', sheetName, arr, format = 'xlsx') => {
        let fileName = name + '.' + format;
        let headerData = []
        let headerDataLen = headers && headers.length > 0 ? headers.length : 0
        for (var i = 0; i < headerDataLen; i++) {
            let obj = {};
            obj.wpx = parseInt(headers[i].width.replace("px", "") / 2);
            headerData.push(obj)
        }
        // 单元格的大小
        let wpxArr = arr ? arr : headerData;
        const _headers = headers
            .map((item, i) => Object.assign({}, { dataIndex: item.dataIndex, title: item.title, position: i > 25 ? ('A' + String.fromCharCode(65 + i - 26) + 1) : String.fromCharCode(65 + i) + 1 }))
            .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { dataIndex: next.dataIndex, v: next.title } }), {});
        const _data = data
            .map((item, i) => headers.map((dataIndex, j) => Object.assign({}, { content: item[dataIndex.dataIndex], position: j > 25 ? ('A' + String.fromCharCode(65 + j - 26) + (i + 2)) : String.fromCharCode(65 + j) + (i + 2) })))
            // 对刚才的结果进行降维处理（二维数组变成一维数组）
            .reduce((prev, next) => prev.concat(next))
            // 转换成 worksheet 需要的结构
            .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.content } }), {});
        // 合并 headers 和 data
        const output = Object.assign({}, _headers, _data);
        // 获取所有单元格的位置
        const outputPos = Object.keys(output);
        // 计算出范围 ,["A1",..., "H2"]
        const ref = `${outputPos[0]}:${outputPos[outputPos.length - 1]}`;
        // 构建 workbook 对象
        const wb = {
            SheetNames: [sheetName],
            Sheets: {
                [sheetName]: Object.assign(
                    {},
                    output,
                    {
                        '!ref': ref,
                        '!cols': wpxArr,
                    },
                ),
            },
        };

        XLSX.writeFile(wb, fileName, (err) => {
            if (err) {
                message.error(err)
            }
        });
    }
    onChange = (e) => {
        this.setState({
            tableDesc: e.target.value
        })
    }
    render() {
        let tableItem = [];
        this.state.basicClassData.map((d) =>
            tableItem.push(<Option key={d.Code} descripts={d.Desc} table={d.Table}>{d.Desc + "-" + d.Code}</Option>)
        )
        return (
            <div style={{ height: '100%', width: '100%' }}>
                <div style={{ height: '50px', lineHeight: '50px' }}>
                    <Col span={7}>
                        表名：<Select
                            showSearch
                            optionFilterProp="children"
                            placeholder='请选择表'
                            style={{ width: '90%' }}
                            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                            onChange={this.getTableFiledData}
                        >
                            {tableItem}
                        </Select>
                    </Col>
                    <Col span={4}>
                        文件名:<Input style={{ width: '80%' }} value={this.state.tableDesc} onChange={this.onChange} />
                    </Col>
                    <Col span={3}>
                        <Button type="primary" onClick={this.onExportClick}>
                            导出
                         </Button>
                    </Col>
                </div>
                <div style={{ height: 'calc(100% - 50px)' }}>
                    <Table
                        style={{ height: 'calc(100% - 100px)', width: this.state.tableWidth }}
                        scroll={{ y: 'calc(100% - 100)' }}
                        bordered
                        columns={this.state.column}
                        dataSource={this.state.tableData}
                        pagination={false}
                        rowKey={(data) => {
                            return data.div
                        }}
                    >
                    </Table>
                </div>
            </div>
        )
    }

}
export default ExportTableToExcel;
