import React, { useEffect, useState } from 'react';
import dayjs from 'dayjs';
import { Tabs, Table, TableColumnProps, Input } from '@arco-design/web-react';
import { IconCheckCircleFill, IconLoading, IconCloseCircleFill } from '@arco-design/web-react/icon';
import { formatSeconds } from '@/utils/common';

const TabPane = Tabs.TabPane;

const columns: TableColumnProps[] = [
  {
    title: '节点',
    dataIndex: 'name',
    width: 120
  },
  {
    title: '时间',
    width: 160,
    render: (_: any, record) => (
      <>
        <span>开始 {dayjs(record.startTime).format('MM-DD HH:mm:ss')}</span>
        <br></br>
        {record.endTime > 0 && <span>结束 {dayjs(record.endTime).format('MM-DD HH:mm:ss')}</span>}
      </>
    )
  },
  {
    title: '耗时',
    dataIndex: 'duration',
    width: 80,
    render: (_: any, record) => (
      record.duration > 1000 ?
        <span>{formatSeconds((record.duration / 1000).toString())}</span> :
        <span>{record.duration}ms</span>
    )
  },
  {
    title: '状态',
    dataIndex: 'state',
    width: 60,
    align: 'center',
    render: (_: any, record) => (
      <>
        {record.state === 1 && <IconCheckCircleFill fontSize={24} style={{ color: 'rgb(var(--green-6))' }} />}
        {record.state === 0 && <IconLoading fontSize={24} style={{ color: 'rgb(var(--arcoblue-4))' }} />}
        {record.state === -1 && <IconCloseCircleFill fontSize={24} style={{ color: 'rgb(var(--red-6))' }} />}
      </>
    )
  },
  {
    title: '输入参数',
    dataIndex: 'input',
    width: 200,
    render: (_: any, record) => (
      <div style={{ wordBreak: 'break-all', whiteSpace: 'pre-wrap' }}>{JSON.stringify(record.input)}</div>
    )
  },
  {
    title: '输出参数',
    dataIndex: 'output',
    width: 200,
    render: (_: any, record) => (
      <div style={{ wordBreak: 'break-all', whiteSpace: 'pre-wrap' }}>{JSON.stringify(record.output)}</div>
    )
  }
];

const RunTimeData = ({ logData }) => {
  const [currentTab, setCurrentTab] = useState('0');
  const [tabList, setTabList] = useState([]);
  const [keyMap, setKeyMap] = useState({});
  const [data, setData] = useState([]);

  const onTabChange = (key) => {
    setCurrentTab(key);
    setData(keyMap[key]);
  };

  useEffect(() => {
    const tempMap = {};
    const list = logData.map((item, index) => {
      tempMap[index] = item.nodes;
      return {
        key: index,
        title: item.parent
      };
    });
    setKeyMap(tempMap);
    setTabList(list);
  }, [logData]);

  useEffect(() => {
    if (tabList.length > 0) {
      setData(keyMap[0]);
      onTabChange(0); // 默认选中第一个
    }
  }, [tabList]);

  return (
    <div style={{ paddingRight: 30 }}>
      <Tabs type="card" onChange={onTabChange} activeTab={currentTab}>
        {tabList.map((item) => (<TabPane key={item.key} title={item.title}></TabPane>))}
      </Tabs>
      <Table columns={columns} data={data} tableLayoutFixed scroll={{ x: 'max-content' }} />
    </div>
  );
};

export default RunTimeData;