import { getAccessToken } from '@/access';
import KFIcon from '@/components/KFIcon';
import KFModal from '@/components/KFModal';
import { DataSource, ResourceType, resourceConfig } from '@/pages/Dataset/config';
import { to } from '@/utils/promise';
import { getFileListFromEvent, removeUploadedFile, validateUploadFiles } from '@/utils/ui';
import {
  Button,
  Form,
  Input,
  Upload,
  UploadFile,
  message,
  type ModalProps,
  type UploadProps,
} from 'antd';
import { omit } from 'lodash';
import { useState } from 'react';
import styles from '../AddDatasetModal/index.less';

interface AddVersionModalProps extends Omit<ModalProps, 'onOk'> {
  resourceType: ResourceType;
  resourceId: number;
  resoureName: string;
  owner: string;
  identifier: string;
  is_public: boolean;
  onOk: () => void;
}

function AddVersionModal({
  resourceType,
  resourceId,
  resoureName,
  owner,
  identifier,
  is_public,
  onOk,
  ...rest
}: AddVersionModalProps) {
  const [uuid] = useState(Date.now());
  const config = resourceConfig[resourceType];

  // 上传组件参数
  const uploadProps: UploadProps = {
    action: config.uploadAction,
    headers: {
      Authorization: getAccessToken() || '',
    },
    defaultFileList: [],
    beforeUpload: config.beforeUpload,
    accept: config.uploadAccept,
    onRemove: removeUploadedFile,
  };

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

  // 提交
  const onFinish = (formData: any) => {
    const fileList: UploadFile[] = formData['fileList'] ?? [];
    if (validateUploadFiles(fileList)) {
      const version_vos = fileList.map((item) => {
        const data = item.response?.data?.[0] ?? {};
        return {
          file_name: data.fileName,
          file_size: data.fileSize,
          url: data.url,
        };
      });
      const params = {
        id: resourceId,
        identifier,
        is_public,
        owner,
        [config.filePropKey]: version_vos,
        ...omit(formData, 'fileList'),
        [config.sourceParamKey]: DataSource.Create,
      };
      createDatasetVersion(params);
    }
  };

  const name = config.name;

  return (
    <KFModal
      {...rest}
      title="创建新版本"
      image={require('@/assets/img/create-experiment.png')}
      width={825}
      okButtonProps={{
        htmlType: 'submit',
        form: 'form',
      }}
    >
      <Form
        name="form"
        layout="vertical"
        initialValues={{
          name: resoureName,
        }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label={`${name}名称`}
          name="name"
          rules={[
            {
              required: true,
              message: `请输入${name}名称`,
            },
          ]}
        >
          <Input disabled placeholder={`请输入${name}名称`} />
        </Form.Item>
        <Form.Item
          label={`${name}版本`}
          name="version"
          rules={[
            {
              required: true,
              message: `请输入${name}版本`,
            },
            {
              pattern: /^[a-zA-Z0-9._-]+$/,
              message: '版本只支持字母、数字、点(.)、下划线(_)、中横线(-)',
            },
            {
              validator: (_rule, value) => {
                if (value === 'master') {
                  return Promise.reject(`版本不能为 master`);
                }
                return Promise.resolve();
              },
            },
          ]}
        >
          <Input placeholder={`请输入${name}版本`} maxLength={64} showCount 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}文件`}
          name="fileList"
          valuePropName="fileList"
          getValueFromEvent={getFileListFromEvent}
          rules={[
            {
              required: true,
              message: `请上传${name}文件`,
            },
          ]}
        >
          <Upload {...uploadProps} data={{ uuid: uuid }}>
            <Button
              className={styles['upload-button']}
              type="default"
              icon={<KFIcon type="icon-shangchuan" />}
            >
              上传文件
            </Button>
            {resourceType === ResourceType.Dataset && (
              <div className={styles['upload-tip']}>只允许上传 .zip 和 .tgz 格式文件</div>
            )}
          </Upload>
        </Form.Item>
      </Form>
    </KFModal>
  );
}

export default AddVersionModal;
