import React, { useEffect, useState } from 'react';
import { Table } from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { coscoSupplier } from '../services';
import { useIntl } from 'umi';

// 联系人信息接口
interface Contact {
  id: string;
  name: string;
  department: string;
  position: string;
  mobile: string;
  phone: string;
  email: string;
  updateTime: string;
}

const ContactsInfoTab: React.FC = () => {
  const intl = useIntl();
  const [data, setData] = useState<Contact[]>([]);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [loading, setLoading] = useState(false);

  const fetchContacts = async (page: number = 1, pageSize: number = 10) => {
    setLoading(true);
    try {
      const res = await coscoSupplier(page);
      if (res.code === 200) {
        setData(res.contacts || []);
        setPagination({
          current: page,
          pageSize,
          total: res.totalContacts || (res.contacts?.length || 0),
        });
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchContacts();
  }, []);

  const handleTableChange = (pagination: TablePaginationConfig) => {
    fetchContacts(pagination.current!, pagination.pageSize!);
  };

  const columns: ColumnsType<Contact> = [
    {
      title: intl.formatMessage({ id: 'page.workbench.contacts.index' }),
      dataIndex: 'index',
      key: 'index',
      width: 60,
      align: 'center',
      render: (_: any, __: any, index: number) =>
        (pagination.current! - 1) * pagination.pageSize! + index + 1,
    },
    {
      title: intl.formatMessage({ id: 'page.workbench.contacts.name' }),
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: intl.formatMessage({ id: 'page.workbench.contacts.department' }),
      dataIndex: 'department',
      key: 'department',
    },
    {
      title: intl.formatMessage({ id: 'page.workbench.contacts.position' }),
      dataIndex: 'position',
      key: 'position',
    },
    {
      title: intl.formatMessage({ id: 'page.workbench.contacts.mobile' }),
      dataIndex: 'mobile',
      key: 'mobile',
    },
    {
      title: intl.formatMessage({ id: 'page.workbench.contacts.phone' }),
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: intl.formatMessage({ id: 'page.workbench.contacts.email' }),
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: intl.formatMessage({ id: 'page.workbench.contacts.updateTime' }),
      dataIndex: 'updateTime',
      key: 'updateTime',
    },
  ];

  return (
    <div style={{ padding: '0 30px 0 0' }}>
      <Table
        className="custom-table"
        columns={columns}
        dataSource={data}
        rowKey="id"
        loading={loading}
        pagination={pagination}
        onChange={handleTableChange}
        bordered
      />
    </div>
  );
};

export default ContactsInfoTab;