import React, { useState, useEffect } from 'react';
import { Table, Pagination, Message, Divider, Button, Loading, Dialog } from '@alifd/next';
import request from 'axios';
import { editUrl, showUrl } from '@/utils/url';
import { deleteUser } from '@/apis';

const PAGE_SIZE = 10;

interface ITableListProps {
  api: string;
  addUrl: string;
}

const TableList = (props: ITableListProps) => {
  const [dataSource, setDataSource] = useState([]);
  const [pagination, setPagination] = useState({ total: 0, pageSize: PAGE_SIZE, current: 1 });
  const [loading, setLoading] = useState(true);
  const [ page, setPage ] = useState(1);

  useEffect(() => {
    const getUsers = async() => {
      setLoading(true);
      try {
        const result = await request.get(props.api, {
          params: { start: (page - 1) * PAGE_SIZE, limit: PAGE_SIZE },
        });
        if (result && result.data) {
          setDataSource(result.data.result || []);
          setPagination({ total: result.data.total, pageSize: PAGE_SIZE, current: page });
        }
      } catch (err) {
        Message.error(err.message || '网络错误');
      }
      setLoading(false);
    }


    getUsers();
  }, [ page ]);

  const onPaginationChange = (page) => {
    setPage(page);
  };

  const handleDelete = (user) => () => {
    Dialog.alert({
      title: '删除用户',
      content: `是否要删除用户：${user.name}?`,
      onOk: async () => {
        try {
          const result = await request.post(deleteUser, { _id: user._id });
          if (result.data && result.data.errorMessage) {
            throw new Error(result.data.errorMessage);
          }
          Message.success('成功删除用户');
          window.location.reload();
        } catch (err) {
          Message.error(err.message || '网络错误');
        }
      },
    });
  }

  return (
    <div className="halo-table-list">
      <Loading visible={loading} >
        <div className="halo-table-list-add">
          <Button type="primary" component="a" href={props.addUrl}>新增</Button>
        </div>
        <Table
          hasBorder={false}
          className="halo-table-list-table"
          dataSource={dataSource}
        >
          <Table.Column title="姓名" dataIndex="name" />
          <Table.Column title="昵称" dataIndex="nick" />
          <Table.Column title="角色" dataIndex="role" />
          <Table.Column title="更新时间" dataIndex="gmtModified" />
          <Table.Column title="创建时间" dataIndex="gmtCreate" />
          <Table.Column
            title="操作"
            cell={(value, idx, record) => (
              <div className="opt">
                <Button type="primary" text component="a" target="_blank" href={`${editUrl}?_id=${record._id}`}>编辑</Button>
                <Divider direction="ver" />
                <Button type="primary" text component="a" target="_blank" href={`${showUrl}?_id=${record._id}`}>查看</Button>
                <Divider direction="ver" />
                <Button type="primary" text onClick={handleDelete(record)}>删除</Button>
              </div>
            )}
          />
        </Table>
        <div className="halo-table-list-table-footer">
          <div className="halo-table-list-total">
            共<span>{pagination.total || 0}</span>个用户
          </div>
          <Pagination onChange={onPaginationChange} {...pagination} />
        </div>
      </Loading>
    </div>
  );
};

export default TableList;
