import { getAccessToken } from '@/access';
import { DictValueEnumObj } from '@/components/DictTag';
import KFIcon from '@/components/KFIcon';
import KFModal from '@/components/KFModal';
import { addDatesetAndVesion } from '@/services/dataset/index.js';
import { getDictSelectOption } from '@/services/system/dict';
import { to } from '@/utils/promise';
import { getFileListFromEvent, validateUploadFiles } from '@/utils/ui';
import {
  Button,
  Form,
  Input,
  Radio,
  Select,
  Upload,
  UploadFile,
  message,
  type ModalProps,
  type UploadProps,
} from 'antd';
import { omit } from 'lodash';
import { useEffect, useState } from 'react';
import { CategoryData } from '../../config';
import styles from './index.less';

interface AddDatasetModalProps extends Omit<ModalProps, 'onOk'> {
  typeList: CategoryData[];
  tagList: CategoryData[];
  onOk: () => void;
}

function AddDatasetModal({ typeList, tagList, onOk, ...rest }: AddDatasetModalProps) {
  const [uuid] = useState(Date.now());
  const [clusterOptions, setClusterOptions] = useState<DictValueEnumObj[]>([]);

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

  // 上传组件参数
  const uploadProps: UploadProps = {
    action: '/api/mmp/dataset/upload',
    headers: {
      Authorization: getAccessToken() || '',
    },
    defaultFileList: [],
  };

  // 获取集群版本数据
  const getClusterOptions = async () => {
    const [res] = await to(getDictSelectOption('available_cluster'));
    if (res) {
      setClusterOptions(res);
    }
  };

  // 上传请求
  const createDataset = async (params: any) => {
    const [res] = await to(addDatesetAndVesion(params));
    if (res) {
      message.success('创建成功');
      onOk?.();
    }
  };

  // 提交
  const onFinish = (formData: any) => {
    const fileList: UploadFile[] = formData['fileList'] ?? [];
    if (validateUploadFiles(fileList)) {
      const params = {
        ...omit(formData, ['fileList']),
        dataset_version_vos: fileList.map((item) => {
          const data = item.response?.data?.[0] ?? {};
          return {
            file_name: data.fileName,
            file_size: data.fileSize,
            url: data.url,
          };
        }),
      };
      createDataset(params);
    }
  };

  return (
    <KFModal
      {...rest}
      title="新建数据集"
      image={require('@/assets/img/create-experiment.png')}
      width={825}
      okButtonProps={{
        htmlType: 'submit',
        form: 'form',
      }}
      destroyOnClose
    >
      <Form name="form" layout="vertical" onFinish={onFinish} autoComplete="off">
        <Form.Item
          label="数据集名称"
          name="name"
          required
          rules={[
            {
              required: true,
              message: '请输入数据集名称',
            },
          ]}
        >
          <Input placeholder="请输入数据名称" showCount allowClear maxLength={64} />
        </Form.Item>
        <Form.Item
          label="数据集版本"
          name="version"
          rules={[
            {
              required: true,
              message: '请输入数据集版本',
            },
          ]}
        >
          <Input placeholder="请输入数据集版本" showCount allowClear maxLength={64} />
        </Form.Item>
        <Form.Item label="数据集分类" name="data_type">
          <Select
            allowClear
            placeholder="请选择数据集分类"
            options={typeList}
            fieldNames={{ label: 'name', value: 'id' }}
            optionFilterProp="name"
            showSearch
          />
        </Form.Item>
        <Form.Item label="研究方向/应用领域" name="data_tag">
          <Select
            allowClear
            placeholder="请选择研究方向/应用领域"
            options={tagList}
            fieldNames={{ label: 'name', value: 'id' }}
            optionFilterProp="name"
            showSearch
          />
        </Form.Item>
        <Form.Item label="集群版本" name="available_cluster">
          <Select allowClear placeholder="请选择集群版本" options={clusterOptions} />
        </Form.Item>
        <Form.Item
          label="数据集简介"
          name="description"
          rules={[
            {
              required: true,
              message: '请输入数据集简介',
            },
          ]}
        >
          <Input.TextArea
            placeholder="请输入数据集简介"
            showCount
            maxLength={256}
            autoSize={{ minRows: 2, maxRows: 6 }}
            allowClear
          />
        </Form.Item>
        <Form.Item label="选择流水线" name="range">
          <Radio.Group>
            <Radio value="0">仅自己可见</Radio>
            <Radio value="1">工作空间可见</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label="数据集文件"
          name="fileList"
          valuePropName="fileList"
          getValueFromEvent={getFileListFromEvent}
          rules={[
            {
              required: true,
              message: '请上传数据集文件',
            },
          ]}
        >
          <Upload {...uploadProps} data={{ uuid: uuid }} accept=".zip,.tgz">
            <Button
              className={styles['upload-button']}
              type="default"
              icon={<KFIcon type="icon-shangchuan" />}
            >
              上传文件
            </Button>
            <div className={styles['upload-tip']}>只允许上传.zip,.tgz格式文件</div>
          </Upload>
        </Form.Item>
      </Form>
    </KFModal>
  );
}

export default AddDatasetModal;
