import { Card, Col, Table, Tag } from 'antd';
import { useEffect, useState } from 'react';
import { listUser, type UserRecord } from '@/api/system/user';

/** 状态值与 Tag 颜色的映射 */
const statusColorMap: Record<string, string> = {
  启用: 'success',
  禁用: 'error',
};

const columns = [
  { title: '用户名', dataIndex: 'username', key: 'username' },
  { title: '姓名', dataIndex: 'name', key: 'name' },
  { title: '邮箱', dataIndex: 'email', key: 'email' },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    render: (status: string) => (
      <Tag color={statusColorMap[status] ?? 'default'}>{status}</Tag>
    ),
  },
];

interface UserTableProps {
  deptKey: string;
}

const UserTable = ({ deptKey }: UserTableProps) => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<UserRecord[]>([]);

  useEffect(() => {
    let cancelled = false;

    const load = async () => {
      setLoading(true);
      try {
        const res = await listUser(deptKey);
        // 用 cancelled 标志位防止组件卸载后的竞态更新
        if (!cancelled) setData(res.data ?? []);
      } finally {
        if (!cancelled) setLoading(false);
      }
    };

    load();
    return () => { cancelled = true; };
  }, [deptKey]);

  return (
    <Col xs={24} sm={24} md={17} lg={18} xl={19} style={{ display: 'flex' }}>
      <Card title="用户列表" style={{ width: '100%' }}>
        <Table
          columns={columns}
          dataSource={data}
          rowKey="username"
          loading={loading}
          pagination={{ pageSize: 10 }}
        />
      </Card>
    </Col>
  );
};

export default UserTable;
