import React, { useEffect, useMemo, useState } from 'react';
import { connect } from 'react-redux';
import { userListState } from 'models/space.types';
import { format } from 'utils/utils';
import EasyvTable from 'components/EasyvTable';
interface Iprops {
  spaceAllUserList?: userListState[];
  userList?: userListState[];
  setRowKeys: (keys) => void;
  searchVal: string;
}

function SpaceModalTable({
  searchVal,
  spaceAllUserList: data,
  userList,
  setRowKeys,
}: Iprops): React.ReactElement {
  const columns: any[] = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      align: 'center',
    },
    {
      title: 'ID',
      dataIndex: 'id',
      align: 'center',
      key: 'id',
    },
    {
      title: '用户类型',
      align: 'center',
      dataIndex: 'type',
      key: 'type',
    },
    {
      title: '创建时间',
      key: 'relatedAt',
      align: 'center',
      dataIndex: 'relatedAt',
      render: (relatedAt) => <>{relatedAt ? format(new Date(relatedAt), '-') : ''}</>,
    },
  ];
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);

  useEffect(() => {
    userList && setSelectedRowKeys(userList.filter((d) => d.id !== 1).map((d) => d.id));
  }, [userList]);

  useEffect(() => {
    setRowKeys(selectedRowKeys);
  }, [selectedRowKeys]);

  const dataSource = useMemo(() => {
    return data
      ?.filter((d) => d.id !== 1)
      .filter((d: userListState) => {
        return d.id.toString().indexOf(searchVal) > -1 || d.username.indexOf(searchVal) > -1;
      })
      .map((d) => {
        d['key'] = d.id;
        d['type'] = d.type || '普通用户';
        return d;
      });
  }, [data, searchVal]);

  return (
    <EasyvTable
      columns={columns}
      dataSource={dataSource}
      openSelect={true}
      selectedRowKeys={selectedRowKeys}
      onRowSelectChange={(keys: number[]) => {
        setSelectedRowKeys(keys);
      }}
    />
  );
}

function mapStateToProps({ space }) {
  const { spaceAllUserList, userList } = space;
  return {
    spaceAllUserList,
    userList,
  };
}
export default connect(mapStateToProps, undefined)(SpaceModalTable);
