import { ExperimentStatus } from '@/enums';
import { getQueryByExperimentLog } from '@/services/experiment/index.js';
import { to } from '@/utils/promise';
import dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';
import LogGroup from '../LogGroup';
import styles from './index.less';

export type ExperimentLog = {
  log_type: 'normal' | 'resource'; // 日志类型
  pod_name?: string; // 分布式名称
  log_content?: string; // 日志内容
  start_time?: string; // 日志开始时间
};

type LogListProps = {
  instanceName: string; // 实验实例 name
  instanceNamespace: string; // 实验实例 namespace
  pipelineNodeId: string; // 流水线节点 id
  workflowId?: string; // 实验实例工作流 id
  instanceNodeStartTime?: string; // 实验实例节点开始运行时间
  instanceNodeStatus?: ExperimentStatus;
};

function LogList({
  instanceName,
  instanceNamespace,
  pipelineNodeId,
  workflowId,
  instanceNodeStartTime,
  instanceNodeStatus,
}: LogListProps) {
  const [logList, setLogList] = useState<ExperimentLog[]>([]);
  const preStatusRef = useRef<ExperimentStatus | undefined>(undefined);
  const retryRef = useRef(3); // 等待 2 秒，重试 3 次

  // 当实例节点运行状态不是 Pending，而上一个运行状态不存在或者是 Pending 时，获取实验日志
  useEffect(() => {
    if (
      instanceNodeStatus &&
      instanceNodeStatus !== ExperimentStatus.Pending &&
      (!preStatusRef.current || preStatusRef.current === ExperimentStatus.Pending)
    ) {
      getExperimentLog();
    }
    preStatusRef.current = instanceNodeStatus;
  }, [instanceNodeStatus]);

  // 获取实验日志
  const getExperimentLog = async () => {
    const start_time = dayjs(instanceNodeStartTime).valueOf() * 1.0e6;
    const params = {
      task_id: pipelineNodeId,
      component_id: workflowId,
      name: instanceName,
      namespace: instanceNamespace,
      start_time: start_time,
    };
    const [res] = await to(getQueryByExperimentLog(params));
    if (res && res.data) {
      const { log_type, pods, log_detail } = res.data;
      if (log_type === 'normal') {
        const list = [
          {
            ...log_detail,
            log_type,
          },
        ];
        setLogList(list);
      } else if (log_type === 'resource') {
        const list = pods.map((v: string) => ({
          log_type,
          pod_name: v,
          log_content: '',
          start_time,
        }));
        setLogList(list);
      }
    } else {
      if (retryRef.current > 0) {
        retryRef.current -= 1;
        setTimeout(() => {
          getExperimentLog();
        }, 2 * 1000);
      }
    }
  };

  return (
    <div className={styles['log-list']} id="log-list">
      {logList.length > 0 ? (
        logList.map((v) => <LogGroup key={v.pod_name} {...v} status={instanceNodeStatus} />)
      ) : (
        <div className={styles['log-list__empty']}>暂无日志</div>
      )}
    </div>
  );
}

export default LogList;
