import { AutoMLTaskType, autoMLEnsembleClassOptions, autoMLTaskTypeOptions } from '@/enums';
import { AutoMLData } from '@/pages/AutoML/types';
import { experimentStatusInfo } from '@/pages/Experiment/status';
import { type NodeStatus } from '@/types';
import { parseJsonText } from '@/utils';
import { elapsedTime } from '@/utils/date';
import { Flex } from 'antd';
import classNames from 'classnames';
import { useMemo } from 'react';
import ConfigInfo, {
  formatBoolean,
  formatDate,
  formatEnum,
  type BasicInfoData,
} from '../ConfigInfo';
import styles from './index.less';

// 格式化数据集
const formatDataset = (dataset: { name: string; version: string }) => {
  if (!dataset || !dataset.name || !dataset.version) {
    return '--';
  }
  return `${dataset.name}:${dataset.version}`;
};

// 格式化优化方向
const formatOptimizeMode = (value: boolean) => {
  return value ? '越大越好' : '越小越好';
};

const formatMetricsWeight = (value: string) => {
  if (!value) {
    return '--';
  }
  const json = parseJsonText(value);
  if (!json) {
    return '--';
  }
  return Object.entries(json)
    .map(([key, value]) => `${key}:${value}`)
    .join('\n');
};

type AutoMLBasicProps = {
  info?: AutoMLData;
  className?: string;
  isInstance?: boolean;
  runStatus?: NodeStatus;
};

function AutoMLBasic({ info, className, runStatus, isInstance = false }: AutoMLBasicProps) {
  const basicDatas: BasicInfoData[] = useMemo(() => {
    if (!info) {
      return [];
    }

    return [
      {
        label: '实验名称',
        value: info.ml_name,
        ellipsis: true,
      },
      {
        label: '实验描述',
        value: info.ml_description,
        ellipsis: true,
      },
      {
        label: '创建人',
        value: info.create_by,
        ellipsis: true,
      },
      {
        label: '创建时间',
        value: info.create_time,
        ellipsis: true,
        format: formatDate,
      },
      {
        label: '更新时间',
        value: info.update_time,
        ellipsis: true,
        format: formatDate,
      },
    ];
  }, [info]);

  const configDatas: BasicInfoData[] = useMemo(() => {
    if (!info) {
      return [];
    }
    return [
      {
        label: '任务类型',
        value: info.task_type,
        ellipsis: true,
        format: formatEnum(autoMLTaskTypeOptions),
      },
      {
        label: '特征预处理算法',
        value: info.include_feature_preprocessor,
        ellipsis: true,
      },
      {
        label: '排除的特征预处理算法',
        value: info.exclude_feature_preprocessor,
        ellipsis: true,
      },
      {
        label: info.task_type === AutoMLTaskType.Regression ? '回归算法' : '分类算法',
        value:
          info.task_type === AutoMLTaskType.Regression
            ? info.include_regressor
            : info.include_classifier,
        ellipsis: true,
      },
      {
        label: info.task_type === AutoMLTaskType.Regression ? '排除的回归算法' : '排除的分类算法',
        value:
          info.task_type === AutoMLTaskType.Regression
            ? info.exclude_regressor
            : info.exclude_classifier,
        ellipsis: true,
      },
      {
        label: '集成方式',
        value: info.ensemble_class,
        ellipsis: true,
        format: formatEnum(autoMLEnsembleClassOptions),
      },
      {
        label: '集成模型数量',
        value: info.ensemble_size,
        ellipsis: true,
      },
      {
        label: '集成最佳模型数量',
        value: info.ensemble_nbest,
        ellipsis: true,
      },
      {
        label: '最大数量',
        value: info.max_models_on_disc,
        ellipsis: true,
      },
      {
        label: '内存限制（MB）',
        value: info.memory_limit,
        ellipsis: true,
      },
      {
        label: '单次时间限制（秒）',
        value: info.per_run_time_limit,
        ellipsis: true,
      },
      {
        label: '搜索时间限制（秒）',
        value: info.time_left_for_this_task,
        ellipsis: true,
      },
      {
        label: '重采样策略',
        value: info.resampling_strategy,
        ellipsis: true,
      },
      {
        label: '交叉验证折数',
        value: info.folds,
        ellipsis: true,
      },
      {
        label: '是否打乱',
        value: info.shuffle,
        ellipsis: true,
        format: formatBoolean,
      },
      {
        label: '训练集比率',
        value: info.train_size,
        ellipsis: true,
      },
      {
        label: '测试集比率',
        value: info.test_size,
        ellipsis: true,
      },
      {
        label: '计算指标',
        value: info.scoring_functions,
        ellipsis: true,
      },
      {
        label: '随机种子',
        value: info.seed,
        ellipsis: true,
      },

      {
        label: '数据集',
        value: info.dataset,
        ellipsis: true,
        format: formatDataset,
      },
      {
        label: '预测目标列',
        value: info.target_columns,
        ellipsis: true,
      },
    ];
  }, [info]);

  const metricsData = useMemo(() => {
    if (!info) {
      return [];
    }
    return [
      {
        label: '指标名称',
        value: info.metric_name,
        ellipsis: true,
      },
      {
        label: '优化方向',
        value: info.greater_is_better,
        ellipsis: true,
        format: formatOptimizeMode,
      },
      {
        label: '指标权重',
        value: info.metrics,
        ellipsis: true,
        format: formatMetricsWeight,
      },
    ];
  }, [info]);

  const instanceDatas = useMemo(() => {
    if (!runStatus) {
      return [];
    }

    return [
      {
        label: '启动时间',
        value: formatDate(runStatus.startedAt),
        ellipsis: true,
      },
      {
        label: '执行时长',
        value: elapsedTime(runStatus.startedAt, runStatus.finishedAt),
        ellipsis: true,
      },
      {
        label: '状态',
        value: (
          <Flex align="center">
            <img
              style={{ width: '17px', marginRight: '7px' }}
              src={experimentStatusInfo[runStatus.phase]?.icon}
              draggable={false}
              alt=""
            />
            <div
              style={{
                color: experimentStatusInfo[runStatus?.phase]?.color,
                fontSize: '15px',
                lineHeight: 1.6,
              }}
            >
              {experimentStatusInfo[runStatus?.phase]?.label}
            </div>
          </Flex>
        ),
        ellipsis: true,
      },
    ];
  }, [runStatus]);

  return (
    <div className={classNames(styles['auto-ml-basic'], className)}>
      {isInstance && runStatus ? (
        <ConfigInfo
          title="运行信息"
          data={instanceDatas}
          labelWidth={70}
          threeColumn
          style={{ marginBottom: '20px' }}
        />
      ) : (
        <ConfigInfo
          title="基本信息"
          data={basicDatas}
          labelWidth={70}
          threeColumn
          style={{ marginBottom: '20px' }}
        />
      )}
      <ConfigInfo
        title="配置信息"
        data={configDatas}
        labelWidth={150}
        threeColumn
        style={{ marginBottom: '20px' }}
      />
      <ConfigInfo title="优化指标" data={metricsData} labelWidth={70} threeColumn />
    </div>
  );
}

export default AutoMLBasic;
