import ConfigInfo, { type BasicInfoData } from '@/components/ConfigInfo';
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 { formatBoolean, formatDataset, formatDate, formatEnum } from '@/utils/format';
import { Flex } from 'antd';
import classNames from 'classnames';
import { useMemo } from 'react';
import styles from './index.less';

// 格式化优化方向
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,
      },
      {
        label: '实验描述',
        value: info.ml_description,
      },
      {
        label: '创建人',
        value: info.create_by,
      },
      {
        label: '创建时间',
        value: info.create_time,
        format: formatDate,
      },
      {
        label: '更新时间',
        value: info.update_time,
        format: formatDate,
      },
    ];
  }, [info]);

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

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

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

    return [
      {
        label: '启动时间',
        value: formatDate(runStatus.startedAt),
      },
      {
        label: '执行时长',
        value: elapsedTime(runStatus.startedAt, runStatus.finishedAt),
      },
      {
        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>
        ),
      },
    ];
  }, [runStatus]);

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

export default AutoMLBasic;
