import editExperimentIcon from '@/assets/img/edit-experiment.png';
import KFModal from '@/components/KFModal';
import { type ResourceData } from '@/pages/Dataset/config';
import {
  addModelsVersionDetail,
  exportModelReq,
  getModelList,
  getModelVersionsById,
} from '@/services/dataset';
import { to } from '@/utils/promise';
import { InfoCircleOutlined } from '@ant-design/icons';
import { Form, Input, ModalProps, Select } from 'antd';
import { useEffect, useState } from 'react';
import styles from './index.less';

type FormData = {
  models_id: string;
  version: string;
  description: string;
};

type ExportModelResponce = {
  fileName: string;
  fileSize: string;
  url: string;
};

type CreateModelVersionParams = FormData & {
  file_name: string;
  file_size: string;
  url: string;
  // name: string;
};

interface ExportModelModalProps extends Omit<ModalProps, 'onOk'> {
  path: string;
  onOk: () => void;
}

function ExportModelModal({ path, onOk, ...rest }: ExportModelModalProps) {
  const [form] = Form.useForm();
  const [models, setModels] = useState<ResourceData[]>([]);
  const [versions, setVersions] = useState<string[]>([]);
  const [uuid] = useState(Date.now());

  const layout = {
    labelCol: { span: 24 },
    wrapperCol: { span: 24 },
  };

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

  // 模型版本tooltip
  const getTooltip = () => {
    const id = form.getFieldValue('models_id');
    const name = models.find((item) => item.id === id)?.name ?? '';
    const tooltip =
      versions.length > 0 ? `${name}有以下版本：\n${versions.join('、')}\n注意不能重复` : undefined;
    return tooltip;
  };

  // 处理模型名称变化
  const handleModelChange = (id: number | undefined) => {
    if (id) {
      getModelVersions(id);
    } else {
      setVersions([]);
    }
  };

  // 获取模型列表
  const requestModelList = async () => {
    const params = {
      page: 0,
      size: 1000,
      available_range: 0, // 个人
    };
    const [res] = await to(getModelList(params));
    if (res && res.data) {
      setModels(res.data.content || []);
    }
  };

  // 获取模型版本列表
  const getModelVersions = async (id: number) => {
    const [res] = await to(getModelVersionsById(id));
    if (res && res.data) {
      setVersions(res.data);
    }
  };

  // 提交
  const hanldeFinish = (formData: FormData) => {
    exportToModel(formData);
  };

  // 导出到模型
  const exportToModel = async (formData: FormData) => {
    const params = {
      uuid: String(uuid),
      path,
    };
    const [res] = await to(exportModelReq(params));
    if (res && res.data) {
      const files = res.data as ExportModelResponce[];
      const params: CreateModelVersionParams[] = files.map((item) => ({
        ...formData,
        file_name: item.fileName,
        file_size: item.fileSize,
        url: item.url,
      }));

      createModelVersion(params);
    }
  };

  // 创建模型版本
  const createModelVersion = async (params: CreateModelVersionParams[]) => {
    const [res] = await to(addModelsVersionDetail(params));
    if (res) {
      onOk();
    }
  };

  return (
    <KFModal
      {...rest}
      title="导出到模型库"
      image={editExperimentIcon}
      okButtonProps={{
        htmlType: 'submit',
        form: 'form',
      }}
      width={825}
      className={styles['export-model-modal']}
    >
      <Form
        name="form"
        layout="horizontal"
        onFinish={hanldeFinish}
        autoComplete="off"
        form={form}
        {...layout}
        labelAlign="left"
        labelWrap
      >
        <Form.Item
          label="模型名称"
          name="models_id"
          rules={[{ required: true, message: '请选择模型' }]}
        >
          <Select
            placeholder="请选择模型"
            onChange={handleModelChange}
            options={models}
            fieldNames={{ label: 'name', value: 'id' }}
            allowClear
          ></Select>
        </Form.Item>
        <Form.Item
          label="模型版本"
          name="version"
          tooltip={
            getTooltip()
              ? {
                  overlayClassName: styles['export-model-modal__tooltip'],
                  title: getTooltip(),
                  icon: <InfoCircleOutlined />,
                }
              : undefined
          }
          rules={[
            { required: true, message: '请输入模型版本' },
            {
              validator: (_, value) => {
                if (value && versions.includes(value)) {
                  return Promise.reject('模型版本已存在');
                } else {
                  return Promise.resolve();
                }
              },
            },
          ]}
        >
          <Input placeholder="请输入模型版本" maxLength={64} showCount allowClear />
        </Form.Item>
        <Form.Item
          label="版本描述"
          name="description"
          rules={[{ required: true, message: '请输入版本描述' }]}
        >
          <Input.TextArea
            placeholder="请输入版本描述"
            maxLength={128}
            autoSize={{ minRows: 2, maxRows: 5 }}
            showCount
            allowClear
          />
        </Form.Item>
      </Form>
    </KFModal>
  );
}

export default ExportModelModal;
