import React from 'react';
import * as XLSX from 'xlsx';
import { _Preview_Props } from '../LionFilePreview';
import { RendererProps } from '../../../../../factory';
import { Wrapper } from './style';
import message from 'antd/lib/message';
import Modal from 'antd/lib/Modal';

interface IState {
  cols: any;
  csv: any;
}

export default class XlsPreview extends React.PureComponent<_Preview_Props & RendererProps, IState> {
  state = {
    cols: null,
    csv: null
  }

  renderTable = (rows: any[]) => {

    return rows.map((row, idx) => {
      let tag = 0;
      let columns = row.split(',');
      columns.forEach((item: any) => {
        if (item !== '') {
          tag++
        }

      });

      if (tag === 0) {
        return null
      };

      return <tr>{
        columns.map((column: any) => {
          return <td>
            <span className="td-cell" style={{ width: '100px' }}>
              {column}
            </span>
          </td>
        })
      }</tr>
    })
  }

  renderCols = (columns: any) => {

    return columns.map((column: any, index: number) => {
      const width = column.width || 50;
      return (
        <col
          key={index}
          style={{ width: width, minWidth: width }}
        />
      );
    });
  }

  readWorkbook = (wookbook: any) => {
    let sheetNames = wookbook.SheetNames;
    let worksheet = wookbook.Sheets[sheetNames[0]];
    let csv = XLSX.utils.sheet_to_csv(worksheet);
    let rows = csv.split("\n");
    rows.pop();
    this.setState({
      cols: this.renderCols(rows),
      csv: this.renderTable(rows)
    })
  }

  getXlsxData = (url: string) => {
    const { env } = this.props;
    if (url.length === 0) {
      return;
    }

    env.fetcher({
      url,
      method: "get",
      data: {},
      responseType: "arraybuffer"
    }).then((res: any) => {

      const workbook = XLSX.read(new Uint8Array(res.data), {
        type: 'array'
      });

      this.readWorkbook(workbook)
    })
  }

  componentDidMount() {
    const { current } = this.props;
    let url = current?.url ? current.url : (current?.addr ? current?.addr : '');
    try {
      this.getXlsxData(url)
    } catch (err) {
      message.error('数据导入有误')
    }
  }


  render() {
    const { current } = this.props;
    return <>{
      current && current?.name && (current?.addr || current?.url) ?
        <Modal
          wrapClassName="file-preview"
          title={current?.name}
          visible={this.props.visible}
          footer={null}
          onCancel={this.props.setVisible}
          closable
        >
          <div className='view'
            style={{
              display: 'flex',
              justifyContent: 'center',
              /* padding: 50px 0; */
              overflow: 'auto',
              /* width: 200px; */
              margin: 'auto',
              height: '400px',
              width: "100%"
            }}
          >
            <div className='pageContainer'
              style={{
                width: '100vw',
                maxWidth: '100%',
                height: "inherit"
              }}>
              <Wrapper>
                <div className="table-container" style={{ width: "100%" }}>
                  <div style={{ maxHeight: "350px", overflow: "auto scroll" }}>
                    <table>
                      <colgroup>
                        {
                          this.state.cols ? this.state.cols : null
                        }
                      </colgroup>
                      <tbody>
                        {
                          this.state.csv ? this.state.csv : null
                        }
                      </tbody>
                    </table>
                  </div>
                </div>
              </Wrapper>
            </div>
          </div>
        </Modal> : null}
    </>
  }
}
