import { getAccessToken } from '@/access';
import KFIcon from '@/components/KFIcon';
import KFModal from '@/components/KFModal';
import { CategoryData, DataSource, ResourceType, resourceConfig } from '@/pages/Dataset/config';
import { addDataset } from '@/services/dataset/index.js';
import { to } from '@/utils/promise';
import {
  getFileListFromEvent,
  limitUploadFileType,
  removeUploadedFile,
  validateUploadFiles,
} from '@/utils/ui';
import {
  Button,
  Form,
  Input,
  Radio,
  Select,
  Upload,
  UploadFile,
  message,
  type ModalProps,
  type UploadProps,
} from 'antd';
import { omit } from 'lodash';
import { useState } from 'react';
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 uploadProps: UploadProps = {
    action: resourceConfig[ResourceType.Dataset].uploadAction,
    headers: {
      Authorization: getAccessToken() || '',
    },
    defaultFileList: [],
    accept: '.zip,.tgz',
    beforeUpload: limitUploadFileType('zip,tgz'),
    onRemove: removeUploadedFile,
  };

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

  // 提交
  const onFinish = (formData: any) => {
    const fileList: UploadFile[] = formData['fileList'] ?? [];
    if (validateUploadFiles(fileList)) {
      const params = {
        ...omit(formData, ['fileList']),
        dataset_source: DataSource.Create,
        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}
        initialValues={{ is_public: false }}
        autoComplete="off"
      >
        <Form.Item
          label="数据集名称"
          name="name"
          required
          rules={[
            {
              required: true,
              message: '请输入数据集名称',
            },
          ]}
        >
          <Input placeholder="请输入数据名称" showCount allowClear maxLength={40} />
        </Form.Item>
        <Form.Item
          label="数据集版本"
          name="version"
          rules={[
            {
              required: true,
              message: '请输入数据集版本',
            },
            {
              pattern: /^[a-zA-Z0-9._-]+$/,
              message: '版本只支持字母、数字、点(.)、下划线(_)、中横线(-)',
            },
            {
              validator: (_rule, value) => {
                if (value === 'master') {
                  return Promise.reject(`版本不能为 master`);
                }
                return Promise.resolve();
              },
            },
          ]}
        >
          <Input placeholder="请输入数据集版本" showCount allowClear maxLength={64} />
        </Form.Item>
        <Form.Item label="数据集分类" name="data_type">
          <Select
            allowClear
            placeholder="请选择数据集分类"
            options={typeList}
            fieldNames={{ label: 'name', value: 'name' }}
            optionFilterProp="name"
            showSearch
          />
        </Form.Item>
        <Form.Item label="研究方向/应用领域" name="data_tag">
          <Select
            allowClear
            placeholder="请选择研究方向/应用领域"
            options={tagList}
            fieldNames={{ label: 'name', value: 'name' }}
            optionFilterProp="name"
            showSearch
          />
        </Form.Item>
        <Form.Item
          label="数据集描述"
          name="description"
          rules={[
            {
              required: true,
              message: '请输入数据集描述',
            },
          ]}
        >
          <Input.TextArea
            placeholder="请输入数据集描述"
            showCount
            maxLength={200}
            autoSize={{ minRows: 2, maxRows: 6 }}
            allowClear
          />
        </Form.Item>
        <Form.Item
          label="版本描述"
          name="version_desc"
          rules={[
            {
              required: true,
              message: '请输入版本描述',
            },
          ]}
        >
          <Input.TextArea
            placeholder="请输入版本描述"
            autoSize={{ minRows: 2, maxRows: 6 }}
            maxLength={200}
            showCount
            allowClear
          />
        </Form.Item>
        <Form.Item
          label="可见性"
          name="is_public"
          rules={[{ required: true, message: '请选择可见性' }]}
        >
          <Radio.Group>
            <Radio value={false}>私有</Radio>
            <Radio value={true}>公开</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label="数据集文件"
          name="fileList"
          valuePropName="fileList"
          getValueFromEvent={getFileListFromEvent}
          rules={[
            {
              required: true,
              message: '请上传数据集文件',
            },
          ]}
        >
          <Upload {...uploadProps} data={{ uuid: uuid }}>
            <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;
