import KFModal from '@/components/KFModal';
import { ServiceRunStatus } from '@/enums';
import { useComputingResource } from '@/hooks/resource';
import { type ServiceVersionData } from '@/pages/ModelDeployment/types';
import { getServiceVersionCompareReq } from '@/services/modelDeployment';
import { isEmpty } from '@/utils';
import { to } from '@/utils/promise';
import { Typography, type ModalProps } from 'antd';
import classNames from 'classnames';
import { useEffect, useMemo, useState } from 'react';
import { statusInfo } from '../ModelDeployStatusCell';
import styles from './index.less';

type CompareData = {
  differences: Record<string, any>;
  version1: ServiceVersionData;
  version2: ServiceVersionData;
};

type ServiceVersionDataKey = keyof ServiceVersionData;

type FiledType = {
  key: ServiceVersionDataKey;
  text: string;
  format?: (data: any) => any;
};

interface VersionCompareModalProps extends Omit<ModalProps, 'onOk'> {
  version1: string;
  version2: string;
}

// 格式化环境变量
const formatEnvText = (env: Record<string, string>) => {
  if (!env || Object.keys(env).length === 0) {
    return '--';
  }
  return Object.entries(env)
    .map(([key, value]) => `${key} = ${value}`)
    .join(',');
};

function VersionCompareModal({ version1, version2, ...rest }: VersionCompareModalProps) {
  const [compareData, setCompareData] = useState<CompareData | undefined>(undefined);
  const getResourceDescription = useComputingResource()[2];

  const fields: FiledType[] = useMemo(
    () => [
      {
        key: 'service_name',
        text: '服务名称',
      },
      {
        key: 'run_state',
        text: '状态',
        format: (data: any) => {
          return data ? statusInfo[data as ServiceRunStatus].text : '--';
        },
      },
      {
        key: 'image',
        text: '镜像',
      },
      {
        key: 'code_config',
        text: '代码配置',
        format: (data: any) => {
          return data?.show_value;
        },
      },
      {
        key: 'model',
        text: '模型',
        format: (data: any) => {
          return data?.show_value;
        },
      },
      {
        key: 'resource',
        text: '资源规格',
        format: getResourceDescription,
      },
      {
        key: 'replicas',
        text: '副本数',
      },
      {
        key: 'mount_path',
        text: '挂载路径',
      },
      {
        key: 'url',
        text: '服务URL',
      },
      {
        key: 'env_variables',
        text: '环境变量',
        format: formatEnvText,
      },
      {
        key: 'description',
        text: '描述',
      },
    ],
    [getResourceDescription],
  );

  useEffect(() => {
    getServiceVersionCompare();
  }, []);

  // 获取对比数据
  const getServiceVersionCompare = async () => {
    const params = {
      id1: version1,
      id2: version2,
    };
    const [res] = await to(getServiceVersionCompareReq(params));
    if (res && res.data) {
      setCompareData(res.data);
    }
  };

  const {
    version1: v1 = {} as ServiceVersionData,
    version2: v2 = {} as ServiceVersionData,
    differences = {},
  } = compareData || {};

  const isDifferent = (key: ServiceVersionDataKey) => {
    const keys = Object.keys(differences);
    return keys.includes(key);
  };

  return (
    <KFModal
      {...rest}
      title="服务版本对比"
      width={825}
      footer={null}
      className={styles['version-compare']}
    >
      <div className={styles['version-compare__container']}>
        <div className={styles['version-compare__fields']}>
          <div className={styles['version-compare__fields__title']}>基础版本号</div>
          {fields.map(({ key, text }) => (
            <div
              className={classNames(styles['version-compare__fields__text'], {
                [styles['version-compare__fields__text--different']]: isDifferent(key),
              })}
              key={key}
            >
              {text}
            </div>
          ))}
        </div>
        <div className={styles['version-compare__left']}>
          <div className={styles['version-compare__left__title']}>{v1.version}</div>
          {fields.map(({ key, format }) => {
            const text = format ? format(v1[key]) : v1[key];
            return (
              <div
                key={key}
                className={classNames(styles['version-compare__left__text'], {
                  [styles['version-compare__left__text--different']]: isDifferent(key),
                })}
              >
                <Typography.Text ellipsis={{ tooltip: text }} style={{ color: 'inherit' }}>
                  {isEmpty(text) ? '--' : text}
                </Typography.Text>
              </div>
            );
          })}
        </div>
        <div className={styles['version-compare__right']}>
          <div className={styles['version-compare__right__title']}>{v2.version}</div>
          {fields.map(({ key, format }) => {
            const text = format ? format(v2[key]) : v2[key];
            return (
              <div
                key={key}
                className={classNames(styles['version-compare__right__text'], {
                  [styles['version-compare__right__text--different']]: isDifferent(key),
                })}
              >
                <Typography.Text ellipsis={{ tooltip: text }} style={{ color: 'inherit' }}>
                  {isEmpty(text) ? '--' : text}
                </Typography.Text>
              </div>
            );
          })}
        </div>
      </div>
    </KFModal>
  );
}

export default VersionCompareModal;
