import InfoGroup from '@/components/InfoGroup';
import KFIcon from '@/components/KFIcon';
import { type HyperParameterFile } from '@/pages/HyperParameter/types';
import { downLoadZip } from '@/utils/downloadfile';
import { Tree, type TreeDataNode } from 'antd';
import classNames from 'classnames';
import styles from './index.less';

const { DirectoryTree } = Tree;

export type TrialFileTreeProps = {
  title: string;
  file?: HyperParameterFile;
  classname?: string;
  defaultExpandAll?: boolean;
};

function TrialFileTree({ file, title, defaultExpandAll = true, classname }: TrialFileTreeProps) {
  const filesToTreeData = (
    files: HyperParameterFile[],
    parent?: HyperParameterFile,
  ): TreeDataNode[] =>
    files.map((file) => {
      const key = parent ? `${parent.name}/${file.name}` : file.name;
      return {
        ...file,
        key,
        title: file.name,
        children: file.children ? filesToTreeData(file.children, file) : undefined,
      };
    });

  const treeData: TreeDataNode[] = filesToTreeData(file ? [file] : []);
  return (
    <InfoGroup title={title} className={classNames(styles['trail-file-tree'], classname)}>
      <DirectoryTree
        // @ts-ignore
        treeData={treeData}
        defaultExpandAll={defaultExpandAll}
        titleRender={(record: TreeDataNode & HyperParameterFile) => {
          const label = record.title + (record.isFile ? `（${record.size}）` : '');
          return (
            <>
              <span style={{ fontSize: 14 }}>{label}</span>
              <KFIcon
                type="icon-xiazai"
                className="trail-file-tree__icon"
                onClick={(e) => {
                  e.stopPropagation();
                  downLoadZip(
                    record.isFile
                      ? `/api/mmp/minioStorage/downloadFile`
                      : `/api/mmp/minioStorage/download`,
                    { path: record.url },
                  );
                }}
              />
            </>
          );
        }}
      />
    </InfoGroup>
  );
}

export default TrialFileTree;
