import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { LocationParam, utils } from 'amos-tool';
import { SplitPane } from 'amos-designer';
import { tools, request } from '@gm/graphmod-utils';
import TableHeader from './tableHeader';
import TableFilter from './filterPane';
import BizTableDetail from './detailPane';
import TableList from './TableList';
import InitReuestRemoteApi from './InitReuestRemoteApi';
import './style.scss';

/**
 * 标准表格页面
 *
 * @class TablePage
 * @extends {Component}
 */
class TablePage extends Component {

  static propTypes = {
    initShowFilter: PropTypes.bool,
    pageSize: PropTypes.number,
    columns: PropTypes.array,
    defaultFilters: PropTypes.object,
    recordsKey: PropTypes.string,
    totalKey: PropTypes.string,
    exportProps: PropTypes.object,
    importProps: PropTypes.object,
    rowKey: PropTypes.string,
    detailSetting: PropTypes.object,
    tableAction: PropTypes.func,
    otherValue: PropTypes.any,
    totalChange: PropTypes.func,
    title: PropTypes.any,
    headerContent: PropTypes.any,
    showSeg: PropTypes.bool,
    rowSelection: PropTypes.bool,
    pagination: PropTypes.bool,
    dataPayload: PropTypes.func,
    filterSetting: PropTypes.array,
    renderFilters: PropTypes.func
  };

  static defaultProps = {
    recordsKey: 'records',
    totalKey: 'total',
    pageSize: 20
  };

  constructor(props) {
    super(props);
    this.state = {
      showFilter: !!props.initShowFilter,
      filters: {},
      current: 1,
      pageSize: props.pageSize,
      sortedInfo: {},
      dataSource: [],
      selectedRowKeys: [],
      showDetail: false,
      details: {},
      rowData: {},
      reloadKey: 1
    };
  }

  componentDidMount() {
    this.init();
  }

  init = () => {
    this.setState({ ...this.initFilterValue() }, this.requestTableData);
  }

  initFilterValue = () => {
    const { columns, defaultFilters } = this.props;
    const colConfig = (columns || []).find(e => e.sort && e.sortOrder);
    let sortedInfo = {};
    if (colConfig) {
      sortedInfo = {
        order: colConfig.sortOrder,
        field: colConfig.dataIndex,
        columnKey: colConfig.dataIndex
      };
    }
    return { sortedInfo, filters: defaultFilters };
  }


  requestTableData = () => {
    this.setState({ reloadKey: Date.now() });
  }

  requestAfterData = (data) => {
    const { recordsKey = 'records', totalKey = 'total', totalChange, dataPayload } = this.props;
    const { current, pageSize } = this.state;
    const { total, content } = dataPayload ? dataPayload(data) : {
      content: data[recordsKey],
      total: data[totalKey]
    };
    totalChange && totalChange(Number(total));
    if (content && content.length > 0) {
      if (total < ((current - 1) * pageSize + content.length)) {
        this.setState({
          dataSource: content,
          total
        });
      } else {
        this.setState({
          dataSource: content,
          total
        });
      }
    } else {
      if (current > 1 && (!content || content.length === 0)) {
        this.handlePageChange(1, pageSize);
      } else {
        this.setState({
          dataSource: content || [],
          total
        });
      }
    }
    this.handleSelectChange([]);
  }

  handleShowFilter = () => {
    this.setState({ showFilter: !this.state.showFilter, showDetail: this.state.showDetail ? false : this.state.showDetail });
  }

  handleExport = () => {
    const { exportProps } = this.props;
    const { title, exportApi } = exportProps || {};
    const { token, appKey, product } = request.compleHeaders() || {};
    if (exportApi) {
      const { filters, sortedInfo, selectedRowKeys, pageSize, current } = this.state;
      const a = window.document.createElement('a');
      const sortObj = sortedInfo && sortedInfo.field && sortedInfo.order ? { sort: `${sortedInfo.field},${sortedInfo.order}` } : {};
      const data = { current, pageSize, ...sortObj, ...filters, ids: selectedRowKeys };
      a.href = LocationParam.completeParam(tools.objEncodeURI({ ...data, token, appKey, product }), (exportApi || '').trim());
      console.log('------------->', a.href);
      a.download = `${title}.xls`;
      a.target = '_blank';
      a.click();
      window.URL.revokeObjectURL(a.href);
    }
  }

  handleTemplateDownload = (config) => {
    const { importProps } = this.props;
    const { templateApi, templateName } = importProps || {};
    if (utils.isString(templateApi)) {
      const { token, appKey, product } = request.compleHeaders() || {};
      const a = window.document.createElement('a');
      if (templateApi) {
        a.href = LocationParam.completeParam(tools.objEncodeURI({ token, appKey, product }), (templateApi || '').trim());
        a.download = `${templateName}.xls`;
        a.target = '_blank';
        a.click();
        window.URL.revokeObjectURL(a.href);
      }
    } else {
      templateApi && templateApi();
    }
  }

  handleSearch = () => {
    this.requestTableData();
  }

  handleReset = () => {
    this.setState({ filters: {} }, this.requestTableData);
  }

  handleFilterChange = (filters) => {
    this.setState({ filters });
  }

  handlePageChange = (current, pageSize) => {
    this.setState((state) => {
      if (pageSize !== state.pageSize) {
        state.pageSize = pageSize;
        state.current = 1;
        state.dataSource = [];
      } else {
        if (state.current !== current) {
          state.dataSource = [];
        }
        state.pageSize = pageSize;
        state.current = current;
      }
      return state;
    }, this.requestTableData);
  }

  handleSorter = (sortedInfo) => {
    this.setState({ sortedInfo }, this.requestTableData);
  }

  handleSelectChange = (selectedRowKeys) => {
    const { rowSelection } = this.props;
    this.setState({ selectedRowKeys });
    rowSelection && rowSelection.onSelectedRowKeys && rowSelection.onSelectedRowKeys(selectedRowKeys);
  }

  handleShowDetail = () => {
    this.setState({ showDetail: !this.state.showDetail, showFilter: this.state.showFilter ? false : this.state.showFilter });
  }

  onRowClick = (record) => {
    const { detailSetting } = this.props;
    if (detailSetting) {
      this.setState({
        rowData: record,
        showDetail: true,
        showFilter: false
      });
    }
  }

  setRowClassName = (record) => {
    const { rowKey } = this.props;
    return record[rowKey] === this.state.rowData[rowKey] ? 'select-row' : '';
  }

  render() {
    const { showSeg, headerContent, exportProps, importProps, detailSetting, tableAction, otherValue, title,
      rowKey, rowSelection, filterSetting, pagination, renderFilters, columns } = this.props;
    const { filters, showFilter,
      dataSource, total, selectedRowKeys, pageSize, current, sortedInfo, showDetail, rowData } = this.state;


    if (showSeg && columns && columns[0] && columns[0].dataIndex !== 'gm_tablepage_seg') {
      columns.unshift({
        title: '序号', width: 60, dataIndex: 'gm_tablepage_seg', key: 'gm_tablepage_seg',
        render: (value, row, index) => {
          console.log(this.state.pageSize, this.state.current);
          return <span>{((this.state.current - 1) * this.state.pageSize) + index + 1}</span>;
        }
      });
    }
    const sortObj = sortedInfo && sortedInfo.field && sortedInfo.order ? { sort: `${sortedInfo.field},${sortedInfo.order}` } : {};
    const hasFilters = (filterSetting && filterSetting.length > 0) || renderFilters;
    return (
      <div className="gm-tablepage-container">
        <InitReuestRemoteApi
          tableAction={tableAction}
          reloadKey={this.state.reloadKey}
          onBefore={() => this.setState({ selectedRowKeys: [] })}
          onSuccess={this.requestAfterData}
          otherValue={otherValue}
          innerParamsValue={{ current, pageSize, sortObj, filters }}
        />
        <TableHeader
          title={title}
          onShowFilter={this.handleShowFilter}
          showFilter={hasFilters}
          headerContent={headerContent}
          exportProps={exportProps}
          importProps={importProps}
          onRefresh={this.requestTableData}
          onTemplateDownload={this.handleTemplateDownload}
          onExport={this.handleExport}
          selectedRowKeys={selectedRowKeys}
        />
        <div className="gm-tablepage-content">
          <SplitPane
            mainPaneIndex={0}
            mainPaneMinSize={296}
            secondaryDefaultSize={230}
            secondaryMinSize={0}
          >
            <TableList
              ref={node => this.table = node}
              dataSource={dataSource}
              rowKey={rowKey}
              columns={columns}
              sortedInfo={sortedInfo}
              total={total}
              pageSize={pageSize}
              current={current}
              onSorter={this.handleSorter}
              onPageChange={this.handlePageChange}
              rowSelection={rowSelection}
              selectedRowKeys={selectedRowKeys}
              onSelectChange={this.handleSelectChange}
              pagination={pagination}
              onRowClick={this.onRowClick}
              rowClassName={this.setRowClassName}
            />
            {
              showDetail && detailSetting ?
                <BizTableDetail
                  show={showDetail}
                  data={rowData}
                  detailSetting={detailSetting}
                  onShowDetail={this.handleShowDetail}
                /> : showFilter && hasFilters &&
                <TableFilter
                  show={showFilter}
                  filters={filters || {}}
                  onFilterChange={this.handleFilterChange}
                  onSearch={this.handleSearch}
                  onReset={this.handleReset}
                  onShowFilter={this.handleShowFilter}
                  filterSetting={filterSetting}
                  renderFilters={renderFilters}
                />
            }
          </SplitPane>
        </div>
      </div>
    );
  }
}

export default TablePage;
