import React, { useEffect, useState } from 'react';
import { Button, Table, TableColumnProps } from '@arco-design/web-react';
import { getTreeComponents } from '@/api/componentTestCase';
import { runStatusConstant, runStatusDic, runTypeConstant, runTypeDic } from '@/const/isdp/componentDeploy';
import dayjs from 'dayjs';

const InstanceList = ({ identifier, refreshKey }: { identifier: string; refreshKey: number }) => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);

  // 获取实例列表数据
  const fetchInstanceData = async (identifier: string) => {
    if (!identifier) {
      setData([]);
      return;
    }

    setLoading(true);
    try {
      const res: any = await getTreeComponents({ identifier } as any);

      if (res.code === 200) {
        // 直接使用 children 数据
        const instanceData = res.data?.[0]?.children || [];
        setData(instanceData);
      }
    } catch (error) {
      console.error('获取实例列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchInstanceData(identifier);
  }, [identifier, refreshKey]);

  // 定义表格列
  const columns: TableColumnProps[] = [
    {
      title: '实例标识',
      dataIndex: 'identifier'
    },
    {
      title: '实例名',
      dataIndex: 'name'
    },
    {
      title: '运行类型',
      dataIndex: 'runType',
      align: 'center',
      render: (runType) => {
        const item = runTypeDic.find(d => d.value === runTypeConstant[runType]);
        return item ? item.label : '-';
      }
    },
    {
      title: '实例状态',
      dataIndex: 'runStatus',
      align: 'center',
      render: (runStatus) => {
        const item = runStatusDic.find(d => d.value === runStatus.toLowerCase());
        return item ? item.label : '-';
      }
    },
    {
      title: '实例测试时间',
      dataIndex: 'lastTestTime',
      align: 'center',
      render: (lastTestTime) => {
        return lastTestTime ? dayjs(lastTestTime).format('YYYY-MM-DD HH:mm:ss') : '-';
      }
    },
    {
      title: '操作',
      dataIndex: 'operations',
      align: 'center',
      render: (col, record, index) => {
        return (
          record.runStatus === 'RUN' && (
            <Button
              type="text"
            >前往测试</Button>
          )
        );
      }
    }
  ];

  return (
    <Table
      columns={columns}
      data={data}
      loading={loading}
      pagination={false}
      rowKey="id"
    />
  );
};

export default InstanceList;