import React, { Component, Fragment } from 'react';
import { Input, ConfigProvider } from '@easyv/react-gui';
import styles from '../style.less';
import ExportConstantModal from './ExportConstantModal';
import Thumb from 'components/Thumb';
import defaultImg from 'images/default.png';
import { request } from 'utils/fetch';
import { api } from 'constants/config';
import {getAssetsUrl} from 'utils/utils';
import PanelHeaderContainer from 'components/PanelHeaderContainer';
import EasyvButton from 'components/EasyvButton';
import EasyvTable from 'components/EasyvTable';
import EasyvTooltip from 'components/EasyvTooltip';
import classNames from 'classnames';
import { connect } from 'react-redux';

const { Search } = Input;

interface IProps {
  deadline: Date | string;
}

interface IState {
  loading: boolean;
  data: any[];
  search: string;
  selectedRowKeys: string[];
  filters: any;
  sorter: {
    order?: 'descend' | 'ascend';
  };
}

class CustomConstantPanel extends Component<IProps, IState> {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      data: [],
      search: '',
      selectedRowKeys: [],
      filters: {},
      sorter: {}
    };
  }

  componentDidMount() {
    document.title = '自定义组件';
    request(api.allTenantConstantList).then((res) => {
      this.setState({
        data: res,
        loading: false
      });
    });
  }

  handleImageError = (e) => {
    const img = e.target;
    img.src = defaultImg;
  };

  handleSearch = (e) => {
    const value = e.target.value && e.target.value.trim();
    this.setState(() => ({
      search: value
    }));
  };

  onRowSelectChange = (selectedRowKeys) => {
    this.setState({
      selectedRowKeys
    });
  };

  onExportComplete = () => {
    this.setState({
      selectedRowKeys: []
    });
  };

  onTableChange = (_pagination, filters, sorter) => {
    this.setState({
      filters,
      sorter
    });
  };

  filterConstant = () => {
    const { data = [] } = this.state;
    const sortedConstants = data.concat().sort((a: any, b: any) => +new Date(b.updatedAt) - +new Date(a.updatedAt));
    const {
      sorter: { order },
      search
    } = this.state;
    const result = sortedConstants.filter(
      (d) =>
        (d.name && d.name.toLowerCase().includes(search.toLowerCase())) ||
        (d.developerName && d.developerName.toLowerCase().includes(search.toLowerCase())) ||
        (d.tenantName && d.tenantName.toLowerCase().includes(search.toLowerCase()))
    );

    if (order) {
      result.sort((a, b) =>
        order === 'descend' ? +new Date(b.updatedAt) - +new Date(a.updatedAt) : +new Date(a.updatedAt) - +new Date(b.updatedAt)
      );
    }

    return result;
  };

  render() {
    const { selectedRowKeys, search, loading } = this.state;
    const selectedLength = selectedRowKeys.length;
    const resultConstants = this.filterConstant();
    const columns = [
      {
        title: '组件名称',
        dataIndex: 'name',
        width: '10%',
        render: (text, record: any) => <span title={record.moduleName}>{text}</span>
      },
      {
        title: '缩略图',
        dataIndex: 'thumb',
        width: '10%',
        render: (text) => <Thumb src={text ? getAssetsUrl(`${text}`) : undefined} style={{ width: 68, height: 44 }} />
      },
      {
        title: '组件版本号',
        dataIndex: 'version',
        width: '10%',
        render: (text) => <span>v{text}</span>
      },
      {
        title: '更新时间',
        dataIndex: 'updatedAt',
        width: '20%',
        sorter: true,
        showSorterTooltip: false
      },
      {
        title: '租户',
        dataIndex: 'tenantName',
        width: '10%'
      },
      {
        title: '开发者',
        dataIndex: 'developerName',
        width: '10%',
        sorter: true,
        showSorterTooltip: false
      },
      {
        title: '操作',
        dataIndex: 'options',
        render: (_text, record: any) => (
          <span>
            <ExportConstantModal list={[record.id]}>
              <EasyvTooltip title="导出">
                <i className={classNames('icon iconfont icon-daochu ' + styles.iconHover)} />
              </EasyvTooltip>
            </ExportConstantModal>
          </span>
        )
      }
    ];

    return (
      <Fragment>
        <PanelHeaderContainer>
          <div>
            <ConfigProvider>
              <Search className={styles.searchInput} onChange={this.handleSearch} placeholder="搜索组件名称" value={search} />
            </ConfigProvider>
          </div>
          <div>
            <ExportConstantModal list={selectedRowKeys} onComplete={this.onExportComplete}>
              <EasyvButton disabled={!selectedLength}>批量导出</EasyvButton>
            </ExportConstantModal>
          </div>
        </PanelHeaderContainer>
        <EasyvTable
          loading={loading}
          selectedRowKeys={selectedRowKeys}
          onRowSelectChange={this.onRowSelectChange}
          dataSource={resultConstants}
          rowKey={(d: any) => d.id}
          scroll={this.props.deadline ? { y: 'calc(100vh - 298px)' } : { y: 'calc(100vh - 250px)' }}
          onChange={this.onTableChange}
          columns={columns}
        />
      </Fragment>
    );
  }
}

function mapStateToProps({ transfer }) {
  const { deadline } = transfer;

  return {
    deadline
  };
}

export default connect(mapStateToProps)(CustomConstantPanel);
