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, onGoToTest, searchValue }: {
  identifier: string;
  refreshKey: number;
  onGoToTest: (instance: any) => void;
  searchValue?: string;
}) => {
  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 filteredData = React.useMemo(() => {
    if (!searchValue || searchValue.trim() === '') {
      return data;
    }

    const searchTerm = searchValue.toLowerCase().trim();
    return data.filter((item: any) => {
      const identifier = (item.identifier || '').toLowerCase();
      const name = (item.name || '').toLowerCase();
      return identifier.includes(searchTerm) || name.includes(searchTerm);
    });
  }, [data, searchValue]);

  // 定义表格列
  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"
              onClick={() => onGoToTest(record)}
            >前往测试</Button>
          )
        );
      }
    }
  ];

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

export default InstanceList;