import { getAccessToken } from '@/access';
import KFIcon from '@/components/KFIcon';
import KFModal from '@/components/KFModal';
import { ResourceType, resourceConfig } from '@/pages/Dataset/config';
import { to } from '@/utils/promise';
import { getFileListFromEvent, 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;
  initialName: string;
  onOk: () => void;
}

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

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

  // 上传请求
  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 otherParams = omit(formData, ['fileList']);
      const params = fileList.map((item) => {
        const data = item.response?.data?.[0] ?? {};
        return {
          ...otherParams,
          [config.idParamKey]: resourceId,
          file_name: data.fileName,
          file_size: data.fileSize,
          url: data.url,
        };
      });
      createDatasetVersion(params);
    }
  };

  const name = config.name;
  const accept = config.uploadAccept;
  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: initialName,
        }}
        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}版本`,
            },
          ]}
        >
          <Input placeholder={`请输入${name}版本`} maxLength={64} showCount allowClear />
        </Form.Item>
        <Form.Item
          label="版本描述"
          name="description"
          rules={[
            {
              required: true,
              message: '请输入版本描述',
            },
          ]}
        >
          <Input.TextArea
            placeholder="请输入版本描述"
            autoSize={{ minRows: 2, maxRows: 6 }}
            maxLength={256}
            showCount
            allowClear
          />
        </Form.Item>
        <Form.Item
          label={`${name}文件`}
          name="fileList"
          valuePropName="fileList"
          getValueFromEvent={getFileListFromEvent}
          rules={[
            {
              required: true,
              message: `请上传${name}文件`,
            },
          ]}
        >
          <Upload {...uploadProps} data={{ uuid: uuid }} accept={accept}>
            <Button
              className={styles['upload-button']}
              type="default"
              icon={<KFIcon type="icon-shangchuan" />}
            >
              上传文件
            </Button>
            {resourceType === ResourceType.Dataset && (
              <div className={styles['upload-tip']}>只允许上传.zip格式文件</div>
            )}
          </Upload>
        </Form.Item>
      </Form>
    </KFModal>
  );
}

export default AddVersionModal;
