// 封装原生table
import React from 'react';
import { Spin, Checkbox } from 'antd';
import { Util } from 'tools';
import './style/index.less';

class PublicNativeTablePagination extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      checkedAll: false,
      selectedRowKeys: [],
      selectedRows: [],
      columns: [],
      copyColumns: [],
      tableData: [],
      copyTableData: [],
      columnHeaderHeight: 45,
      columnHeaderWidth: 0
    };
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    let propsTableData = nextProps.param?.data || [];
    if (JSON.stringify(propsTableData) !== JSON.stringify(prevState.copyTableData)) {
      let copyTableData = Util.customDeepCopy(propsTableData);
      return {
        tableData: propsTableData,
        copyTableData
      }
    }
    let propsColumns = nextProps.param?.columns || [];
    if (JSON.stringify(propsColumns) !== JSON.stringify(prevState.copyColumns)) {
      let filterPropsColumns = Util.customDeepCopy(propsColumns); // 深拷贝数据
      return {
        columns: propsColumns,
        copyColumns: filterPropsColumns
      }
    }
    return null;
  }

  componentDidUpdate(nextProps, prevState) {
    let propsColumns = nextProps.param?.columns || [];
    if ((JSON.stringify(propsColumns) !== JSON.stringify(this.state.copyColumns))) {
      let { columns } = this.state;
      let columnHeaderWidth = 80;
      for (let i = 0; i < columns.length; i++) {
        if (!(parseInt(columns[i].width) > 0)) {
          columns[i].width = '100px';
          columnHeaderWidth += 100;
        } else {
          columnHeaderWidth += parseInt(columns[i].width);
        }
      }
      this.setState({ columns, columnHeaderWidth }, () => {
        this.getColumnsHeight();
      })
    }
    let propsTableData = nextProps.param?.data || [];
    if ((JSON.stringify(propsTableData) !== JSON.stringify(this.state.copyTableData))) {
      this.setCheckedAllStatus();
    }
  }

  getColumnsHeight = () => {
    let { columnHeaderWidth } = this.state;
    let _key = this.props.param?._key || '';
    let headDom = document.querySelector('.public-native-table-pagination-content' + _key + ' .ant-table-thead');
    let currentHeaderWidth = headDom?.clientWidth || headDom?.offsetWidth || 0;
    columnHeaderWidth = columnHeaderWidth > currentHeaderWidth ? columnHeaderWidth : currentHeaderWidth;
    let columnHeaderHeight = headDom?.clientHeight || headDom?.offsetHeight || 45;
    this.setState({ columnHeaderHeight: columnHeaderHeight + 12, columnHeaderWidth });
  }

  // 全选/反选
  handleCheckboxAll = () => {
    let { tableData } = this.state;
    let checkedAll = !this.state.checkedAll
    for (let i = 0; i < tableData.length; i++) {
      if (!checkedAll) {
        tableData[i].check = false
      } else {
        tableData[i].check = true
      }
    }
    this.setState({ tableData, checkedAll }, () => {
      this.handleFilterSelectData()
    });
  }

  // 单个选中操作
  handleTriggerCheckbox = (index) => {
    let { tableData } = this.state;
    tableData[index].check = !!!(tableData[index]?.check);
    this.setState({ tableData }, () => {
      this.setCheckedAllStatus();
      this.handleFilterSelectData();
    });
  }

  // 设置全选框的选中状态
  setCheckedAllStatus = () => {
    let { tableData } = this.state;
    let status = true;
    if (tableData && tableData.length > 0) {
      for (let i = 0; i < tableData.length; i++) {
        if (!tableData[i].check) {
          status = false;
          break;
        }
      }
    } else {
      status = false;
    }
    this.setState({ checkedAll: status })
  }

  // 过滤选中的数据
  handleFilterSelectData = () => {
    let { tableData } = this.state;
    let filterData = tableData && tableData.filter(item => !!(item.check));
    let selectedRowKeys = [];
    for (let i = 0; i < filterData.length; i++) {
      selectedRowKeys.push(filterData[i]?.key || i)
    }
    this.props?.rowSelectionPublic?.onChange(selectedRowKeys, filterData)
  }

  handleTableBodyScroll = (e) => {
    let { param } = this.props;
    let _key = param?._key || '';
    let bodyScrollLeft = document.getElementById('public-native-table-body' + _key)?.scrollLeft || 0;
    setTimeout(() => {
      let tableHeader = document.getElementById('public-native-table-header' + _key);
      tableHeader.scrollLeft = bodyScrollLeft;
    }, 0)
  }

  render() {
    let { columnHeaderHeight, columnHeaderWidth, columns } = this.state;
    let { param } = this.props;
    let tableData = param?.data || [];
    let _key = param?._key || '';
    let currentTableClassName = 'public-native-table-pagination-content' + _key; // 用于相同界面使用获取表头高度问题

    return (
      <Spin spinning={param.loading || false} tip="努力加载中……">
        <div className="public-native-table-pagination ant-table-wrapper table-body-height" style={{ height: param?.height || '100%', width: '100%' }}>
          <div className="ant-spin-container">
            <div className="ant-table ant-table-default ant-table-bordered ant-table-fixed-header ant-table-layout-fixed ant-table-scroll-position-left">
              <div className="ant-table-content">
                <div className="ant-table-scroll">
                  <div
                    id={'public-native-table-header' + _key}
                    className={[currentTableClassName, 'ant-table-header', 'ant-table-hide-scrollbar'].join(' ')}
                    style={{ marginBottom: '-17px', paddingBottom: '0px', minWidth: '17px', overflow: 'scroll' }}
                  >
                    <table className="ant-table-fixed" style={{ width: columnHeaderWidth || '100%' }}>
                      <thead className="ant-table-thead">
                        <tr>
                          <th style={{ width: '80px', textAlign: 'center' }}>
                            <Checkbox
                              checked={this.state.checkedAll}
                              onChange={this.handleCheckboxAll}
                              disabled={tableData && tableData.length > 0 ? false : true}
                            />
                          </th>
                          {columns && columns.map((item, index) => {
                            return (
                              <th
                                className="ant-table-align-center ant-table-row-cell-break-word"
                                key={index}
                                style={{ width: parseInt(item.width) > 0 ? item.width : '100px', textAlign: item.align ? item.align : 'center' }}
                              >
                                {item && 'title' in item && typeof (item.title) !== 'function' ? item.title : item.title(item, index)}
                              </th>
                            )
                          })}
                        </tr>
                      </thead>
                    </table>
                  </div>
                  {tableData && tableData.length > 0 ? (
                    <div
                      tabIndex="-1"
                      id={'public-native-table-body' + _key}
                      className="ant-table-body"
                      style={{ overflow: 'scroll', maxHeight: (param && param.height ? (parseInt(param.height) - columnHeaderHeight) : (300 - columnHeaderHeight)) }}
                      onScroll={this.handleTableBodyScroll}
                    >
                      <table
                        className="ant-table-fixed"
                        style={{ width: columnHeaderWidth || '100%' }}
                      >
                        <tbody className="ant-table-tbody">
                          {tableData && tableData.map((item, index) => {
                            return (
                              <tr className={["ant-table-row ant-table-row-level-0", item?.rowClassName === 'Y' ? (param?.rowClassName || '') : ''].join(' ')} key={index}>
                                <td className="ant-table-row-cell-break-word" style={{ width: '80px', textAlign: 'center' }} key={index}>
                                  <Checkbox checked={item?.check || false} disabled={item.disabled} onChange={() => this.handleTriggerCheckbox(index)} />
                                </td>
                                {columns && columns.map((itemChild, indexChild) => {
                                  return (
                                    <td className="ant-table-row-cell-break-word" key={indexChild}
                                      style={{
                                        width: parseInt(itemChild.width) > 0 ? itemChild.width : '100px',
                                        textAlign: itemChild.align ? itemChild.align : 'center',
                                        color: itemChild.dataIndex === 'aclFlag' && item[itemChild.dataIndex] === '是' ? 'red' : ''
                                      }}
                                    >{itemChild && 'render' in itemChild ? itemChild.render(item[itemChild.dataIndex], item, index) : item[itemChild.dataIndex]}</td>
                                  )
                                })}
                              </tr>
                            )
                          })}
                        </tbody>
                      </table>
                    </div>
                  ) : (
                    <div className="ant-table-placeholder pntp-placeholder">
                      <div className="ant-empty ant-empty-normal">
                        <div className="ant-empty-image">
                          <img src="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjQiIGhlaWdodD0iNDEiIHZpZXdCb3g9IjAgMCA2NCA0MSIgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CiAgPGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMCAxKSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIj4KICAgIDxlbGxpcHNlIGZpbGw9IiNGNUY1RjUiIGN4PSIzMiIgY3k9IjMzIiByeD0iMzIiIHJ5PSI3Ii8+CiAgICA8ZyBmaWxsLXJ1bGU9Im5vbnplcm8iIHN0cm9rZT0iI0Q5RDlEOSI+CiAgICAgIDxwYXRoIGQ9Ik01NSAxMi43Nkw0NC44NTQgMS4yNThDNDQuMzY3LjQ3NCA0My42NTYgMCA0Mi45MDcgMEgyMS4wOTNjLS43NDkgMC0xLjQ2LjQ3NC0xLjk0NyAxLjI1N0w5IDEyLjc2MVYyMmg0NnYtOS4yNHoiLz4KICAgICAgPHBhdGggZD0iTTQxLjYxMyAxNS45MzFjMC0xLjYwNS45OTQtMi45MyAyLjIyNy0yLjkzMUg1NXYxOC4xMzdDNTUgMzMuMjYgNTMuNjggMzUgNTIuMDUgMzVoLTQwLjFDMTAuMzIgMzUgOSAzMy4yNTkgOSAzMS4xMzdWMTNoMTEuMTZjMS4yMzMgMCAyLjIyNyAxLjMyMyAyLjIyNyAyLjkyOHYuMDIyYzAgMS42MDUgMS4wMDUgMi45MDEgMi4yMzcgMi45MDFoMTQuNzUyYzEuMjMyIDAgMi4yMzctMS4zMDggMi4yMzctMi45MTN2LS4wMDd6IiBmaWxsPSIjRkFGQUZBIi8+CiAgICA8L2c+CiAgPC9nPgo8L3N2Zz4K" alt="暂无数据" />
                        </div>
                        <p className="ant-empty-description">
                          暂无数据
                        </p>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      </Spin>
    )
  }
};

export default PublicNativeTablePagination;