/*
 * @Author: 赵伟
 * @Date: 2024-04-16 13:58:08
 * @Description: 创建实验
 */
import PageTitle from '@/components/PageTitle';
import { AutoMLTaskType } from '@/enums';
import {
  addActiveLearnReq,
  getActiveLearnInfoReq,
  updateActiveLearnReq,
} from '@/services/activeLearn';
import { safeInvoke } from '@/utils/functional';
import { to } from '@/utils/promise';
import { useLocation, useNavigate, useParams } from '@umijs/max';
import { App, Button, Form } from 'antd';
import { useEffect } from 'react';
import BasicConfig from '../components/CreateForm/BasicConfig';
import ExecuteConfig from '../components/CreateForm/ExecuteConfig';
import { ActiveLearnData, FormData } from '../types';
import styles from './index.less';

function CreateActiveLearn() {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const { message } = App.useApp();
  const params = useParams();
  const id = safeInvoke(Number)(params.id);
  const { pathname } = useLocation();
  const isCopy = pathname.includes('copy');

  useEffect(() => {
    // 获取服务详情
    const getActiveLearnInfo = async (id: number) => {
      const [res] = await to(getActiveLearnInfoReq({ id }));
      if (res && res.data) {
        const info: ActiveLearnData = res.data;
        const { name: name_str, ...rest } = info;
        const name = isCopy ? `${name_str}-copy` : name_str;
        const formData = {
          ...rest,
          name,
        };

        form.setFieldsValue(formData);
      }
    };
    // 编辑，复制
    if (id && !Number.isNaN(id)) {
      getActiveLearnInfo(id);
    }
  }, [id, isCopy, form]);

  // 创建、更新、复制实验
  const createExperiment = async (formData: FormData) => {
    // 根据后台要求，修改表单数据
    const object = {
      ...formData,
    };

    const params =
      id && !isCopy
        ? {
            id: id,
            ...object,
          }
        : object;

    const request = id && !isCopy ? updateActiveLearnReq : addActiveLearnReq;
    const [res] = await to(request(params));
    if (res) {
      message.success('操作成功');
      navigate(-1);
    }
  };

  // 提交
  const handleSubmit = (values: FormData) => {
    createExperiment(values);
  };

  // 取消
  const cancel = () => {
    navigate(-1);
  };

  let buttonText = '新建';
  let title = '新建实验';
  if (id) {
    if (isCopy) {
      title = '复制实验';
      buttonText = '确定';
    } else {
      title = '编辑实验';
      buttonText = '更新';
    }
  }

  return (
    <div className={styles['create-hyperparameter']}>
      <PageTitle title={title}></PageTitle>
      <div className={styles['create-hyperparameter__content']}>
        <div>
          <Form
            name="create-active-learn"
            labelCol={{ flex: '160px' }}
            labelAlign="left"
            form={form}
            onFinish={handleSubmit}
            size="large"
            autoComplete="off"
            scrollToFirstError
            initialValues={{
              task_type: AutoMLTaskType.Classification,
              shuffle: false,
            }}
          >
            <BasicConfig />
            <ExecuteConfig />

            <Form.Item wrapperCol={{ offset: 0, span: 16 }} style={{ marginTop: '40px' }}>
              <Button type="primary" htmlType="submit">
                {buttonText}
              </Button>
              <Button
                type="default"
                htmlType="button"
                onClick={cancel}
                style={{ marginLeft: '20px' }}
              >
                取消
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  );
}

export default CreateActiveLearn;
