import editExperimentIcon from '@/assets/img/edit-experiment.png';
import KFModal from '@/components/KFModal';
import {
  DataSource,
  ResourceType,
  ResourceVersionData,
  resourceConfig,
  type ResourceData,
} from '@/pages/Dataset/config';
import { to } from '@/utils/promise';
import { InfoCircleOutlined } from '@ant-design/icons';
import { Form, Input, ModalProps, Select } from 'antd';
import { pick } from 'lodash';
import { useEffect, useState } from 'react';
import styles from './index.less';

type FormData = {
  id: number;
  version: string;
  version_desc: string;
};

interface ExportModelModalProps extends Omit<ModalProps, 'onOk'> {
  resourceType: ResourceType;
  pipelineId: number; // 流水线 id
  experimentId: number; // 实验 id
  experimentName: string; // 实验 name
  experimentInsId: number; // 实验实例 id
  pipelineNodeId: string; // 流水线节点 id
  path: string; // 文件路径
  onOk: () => void;
}

function ExportModelModal({
  resourceType,
  pipelineId,
  experimentId,
  experimentName,
  experimentInsId,
  pipelineNodeId,
  path,
  onOk,
  ...rest
}: ExportModelModalProps) {
  const [form] = Form.useForm();
  const [resources, setResources] = useState<ResourceData[]>([]);
  const [versions, setVersions] = useState<ResourceVersionData[]>([]);
  const config = resourceConfig[resourceType];

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

  useEffect(() => {
    // 获取数据集、模型列表
    const requestResourceList = async () => {
      const params = {
        page: 0,
        size: 1000,
        is_public: false, // 个人
      };
      const [res] = await to(config.getList(params));
      if (res && res.data) {
        setResources(res.data.content || []);
      }
    };

    requestResourceList();
  }, [config]);

  // 获取选中的数据集、模型
  const getSelectedResource = (id: number | undefined) => {
    if (id) {
      return resources.find((item) => item.id === id);
    }
    return undefined;
  };

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

  // 处理数据集、模型选择变化
  const handleResourceChange = (id: number | undefined) => {
    if (id) {
      getRecourceVersions(id);
    } else {
      setVersions([]);
    }
  };

  // 获取数据集、模型版本列表
  const getRecourceVersions = async (id: number) => {
    const resource = getSelectedResource(id);
    if (!resource) {
      return;
    }
    const [res] = await to(config.getVersions(pick(resource, ['identifier', 'owner'])));
    if (res && res.data) {
      setVersions(res.data);
    }
  };

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

  // 导出到数据集、模型
  const exportToResource = async (formData: FormData) => {
    const id = form.getFieldValue('id');
    const resource = getSelectedResource(id);
    const params = {
      ...formData,
      identifier: resource?.identifier,
      name: resource?.name,
      [config.sourceParamKey]: DataSource.HandExport,
      train_task: {
        workflow_id: pipelineId,
        experiment_id: experimentId,
        name: experimentName,
        ins_id: experimentInsId,
        task_id: pipelineNodeId,
      },
      [config.filePropKey]: [
        {
          url: path,
        },
      ],
    };
    const [res] = await to(config.addVersion(params));
    if (res) {
      onOk();
    }
  };

  return (
    <KFModal
      {...rest}
      title={`导出到${config.name}`}
      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={`${config.name}名称`}
          name="id"
          rules={[{ required: true, message: `请选择${config.name}` }]}
        >
          <Select
            placeholder={`请选择${config.name}`}
            onChange={handleResourceChange}
            options={resources}
            fieldNames={{ label: 'name', value: 'id' }}
            allowClear
          ></Select>
        </Form.Item>
        <Form.Item
          label={`${config.name}版本`}
          name="version"
          tooltip={
            getTooltip()
              ? {
                  overlayClassName: styles['export-model-modal__tooltip'],
                  title: getTooltip(),
                  icon: <InfoCircleOutlined />,
                }
              : undefined
          }
          rules={[
            { required: true, message: `请输入${config.name}版本` },
            {
              validator: (_, value) => {
                if (value && versions.map((item) => item.name).includes(value)) {
                  return Promise.reject(`${config.name}版本已存在`);
                } else {
                  return Promise.resolve();
                }
              },
            },
          ]}
        >
          <Input placeholder={`请输入${config.name}版本`} maxLength={64} showCount allowClear />
        </Form.Item>
        <Form.Item
          label="版本描述"
          name="version_desc"
          rules={[{ required: true, message: '请输入版本描述' }]}
        >
          <Input.TextArea
            placeholder="请输入版本描述"
            maxLength={128}
            autoSize={{ minRows: 2, maxRows: 5 }}
            showCount
            allowClear
          />
        </Form.Item>
      </Form>
    </KFModal>
  );
}

export default ExportModelModal;
