import React, { useState } from 'react';
import style from '../index.less';
import { connect } from 'react-redux';
import { format } from 'utils/utils';
import { updateSpace } from 'models/space';
import { ColumnsType } from '@easyv/antd/lib/table';
import EasyvTooltip from 'components/EasyvTooltip';
import EasyvModal, { useConfirmRef } from 'components/EasyvModal';
import EasyvTable from 'components/EasyvTable';

interface UserState {
  username?: string;
  visible?: boolean;
  id?: number;
  action?: any;
  type?: string;
}

function SpaceTable({
  defaultSpace,
  dataTable,
  updateSpace,
}: {
  defaultSpace: boolean;
  dataTable: any[];
  updateSpace: (removeUsers) => void;
}): React.ReactElement {
  const [delUser, setDelUser] = useState<UserState>({});
  const deleteRef = useConfirmRef();

  const columns: ColumnsType<UserState> = [
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: '用户类型',
      dataIndex: 'type',
      render: (userType) => <>{userType || '普通用户'}</>,
    },
    {
      title: '添加时间',
      dataIndex: 'relatedAt',
      render: (relatedAt) => <>{relatedAt ? format(new Date(relatedAt), '-') : ''}</>,
    },
  ];

  const [action]: ColumnsType<UserState> = [
    {
      title: '操作',
      align: 'center',
      dataIndex: 'action',
      render: (_text, record) => (
        <EasyvTooltip title="删除">
          <i
            className="icon iconfont icon-zd_shanchu"
            onClick={() => {
              setDelUser({
                ...record,
              });
              deleteRef.current?.show();
            }}
          />
        </EasyvTooltip>
      ),
    },
  ];

  !defaultSpace && columns.push(action);

  return (
    <div className={style.tableWrapper}>
      <EasyvTable pageSize={20} openSelect={false} dataSource={dataTable} columns={columns} />
      <EasyvModal.Confirm
        ref={deleteRef}
        content={
          <p>
            确认删除{delUser?.type || '用户'} <a>{delUser?.username}</a> 吗？
          </p>
        }
        onOk={() => {
          updateSpace({ removeUsers: [delUser?.id] });
          deleteRef.current?.close();
        }}
      />
    </div>
  );
}
export default connect(undefined, {
  updateSpace,
})(SpaceTable);
