import { useEffect } from 'react';
import { useDispatch, useSelector } from 'dva';
import { Table, AdminAmount as Amount, StatusBox } from 'iglooform';
import { ITableProps } from 'iglooform/es/table';
import { useIntl } from 'react-intl';
import moment from 'moment';
import { dateFormatter } from '@/utils/tools';
import { history } from 'umi';
import { request, upload } from '@/utils/request';
import status, { statusTypes } from '@/utils/status';
import styles from './index.less';

export default () => {
  const dispatch = useDispatch();
  const { formatMessage } = useIntl();
  const { list, total, page, pageSize, loading } = useSelector<
    GlobalState,
    StateWithLoading<<%= pageType %>>
  >((state) => ({
    ...state.<%= pageName %>,
    loading: state.loading.effects['<%= pageName %>/getData'],
  }));

  useEffect(() => {
    dispatch({
      type: '<%= pageName %>/getData',
    });
  }, []);

  const enterDetail = (record: <%= pageType %>) => {
    dispatch({
      type: '<%= pageName %>/getDetail',
      payload: {
        id: record?.<%= keyDataIndex %>,
      },
    });
    history.push('/<%= pageName %>/detail');
  };

  const handlePagination = (page: number, pageSize?: number) => {
    dispatch({
      type: '<%= pageName %>/setData',
      payload: {
        page,
        pageSize,
      },
    });
    
    dispatch({
      type: '<%= pageName %>/getData',
    });
  };

  const handleSort: ITableProps['onChange'] = (_, __, sorter, extra) => {
    if(extra.action === 'sort') {
      dispatch({
        type: '<%= pageName %>/setData',
        payload: {
          sorter,
        },
      });
      
      dispatch({
        type: '<%= pageName %>/getData',
      });
    }
  }

  const columns: ITableProps['columns'] = [];

  const filterConfig: ITableProps['filterConfig'] = {
    filterTitle: formatMessage({
      id: 'Filter <%= pageType %> List',
      defaultMessage: 'Filter <%= pageType %> List',
    }),
    placeholder: formatMessage({
      id: 'Search by <%= pageType %>Id, TransactionId...',
      defaultMessage: 'Search by <%= pageType %>Id, TransactionId...',
    }),
    onFilter: (filter: any) => {
      dispatch({
        type: '<%= pageName %>/setData',
        payload: {
          filter,
        },
      });
      // some
      dispatch({
        type: '<%= pageName %>/getData',
      });
    }
  };

  return (
    <div className={styles.container}>
      <Table
        filterConfig={filterConfig}
        columns={columns}
        dataSource={list}
        rowKey="id"
        loading={loading}
        actionButtons={[
          {
            text: formatMessage({
              id: 'Enter Detail',
              defaultMessage: 'Enter Detail',
            }),
            onClick: enterDetail,
          },
        ]}
        onClickRow={enterDetail}
        total={total}
        page={page}
        pageSize={pageSize}
        onPagination={handlePagination}
        onChange={handleSort}
      />
    </div>
  );
};
