import { getAccessToken } from '@/access';
import KFIcon from '@/components/KFIcon';
import KFModal from '@/components/KFModal';
import { CategoryData, DataSource, ResourceType, resourceConfig } from '@/pages/Dataset/config';
import { addModel } from '@/services/dataset/index.js';
import { to } from '@/utils/promise';
import { getFileListFromEvent, 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 '../AddDatasetModal/index.less';

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

function AddModelModal({ typeList, tagList, onOk, ...rest }: AddModelModalProps) {
  const [uuid] = useState(Date.now());

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

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

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

  return (
    <KFModal
      {...rest}
      title="新建模型"
      image={require('@/assets/img/create-experiment.png')}
      width={825}
      okButtonProps={{
        htmlType: 'submit',
        form: 'form',
      }}
    >
      <Form
        name="form"
        layout="vertical"
        onFinish={onFinish}
        autoComplete="off"
        initialValues={{ is_public: false }}
      >
        <Form.Item
          label="模型名称"
          name="name"
          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="model_type">
          <Select
            allowClear
            placeholder="请选择模型框架"
            options={typeList}
            fieldNames={{ label: 'name', value: 'name' }}
            optionFilterProp="name"
            showSearch
          />
        </Form.Item>
        <Form.Item label="模型能力" name="model_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="请输入模型描述"
            maxLength={200}
            autoSize={{ minRows: 2, maxRows: 6 }}
            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="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>
          </Upload>
        </Form.Item>
      </Form>
    </KFModal>
  );
}

export default AddModelModal;
