import { ExperimentStatus } from '@/enums';
import { getQueryByExperimentLog } from '@/services/experiment/index.js';
import { to } from '@/utils/promise';
import classNames from 'classnames';
import dayjs from 'dayjs';
import React, { useCallback, 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 = {
  /** 实验实例 name */
  instanceName: string;
  /** 实验实例 namespace */
  instanceNamespace: string;
  /** 流水线节点 id */
  pipelineNodeId: string;
  /** 实验实例工作流 id */
  workflowId?: string;
  /** 实验实例节点开始运行时间 */
  instanceNodeStartTime?: string;
  /** 实验实例节点运行状态 */
  instanceNodeStatus?: ExperimentStatus;
  /** 自定义类名 */
  className?: string;
  /** 自定义样式 */
  style?: React.CSSProperties;
};

function LogList({
  instanceName,
  instanceNamespace,
  pipelineNodeId,
  workflowId,
  instanceNodeStartTime,
  instanceNodeStatus,
  className,
  style,
}: LogListProps) {
  const [logGroups, setLogGroups] = useState<ExperimentLog[]>([]);
  const retryRef = useRef(3); // 等待 2 秒，重试 3 次

  // 获取实验 Pods 组
  const getExperimentLog = useCallback(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,
          },
        ];
        setLogGroups(list);
      } else if (log_type === 'resource') {
        const list = pods.map((v: string) => ({
          log_type,
          pod_name: v,
          log_content: '',
          start_time,
        }));
        setLogGroups(list);
      }
    } else {
      if (retryRef.current > 0) {
        retryRef.current -= 1;
        setTimeout(() => {
          getExperimentLog();
        }, 2 * 1000);
      }
    }
  }, [pipelineNodeId, workflowId, instanceName, instanceNamespace, instanceNodeStartTime]);

  // 当实例节点运行状态不是 Pending，获取实验日志组
  useEffect(() => {
    if (
      instanceNodeStatus &&
      instanceNodeStatus !== ExperimentStatus.Pending &&
      logGroups.length === 0
    ) {
      getExperimentLog();
    }
  }, [getExperimentLog, logGroups, instanceNodeStatus]);

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

export default LogList;
