/*
 * @Author: 赵伟
 * @Date: 2024-04-16 13:58:08
 * @Description: 创建实验
 */
import PageTitle from '@/components/PageTitle';
import { addRayReq, getRayInfoReq, updateRayReq } from '@/services/hyperParameter';
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 { getReqParamName } from '../components/CreateForm/utils';
import { FormData, HyperParameterData } from '../types';
import styles from './index.less';

function CreateHyperParameter() {
  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 getHyperParameterInfo = async (id: number) => {
      const [res] = await to(getRayInfoReq({ id }));
      if (res && res.data) {
        const info: HyperParameterData = res.data;
        const { name: name_str, parameters, points_to_evaluate, ...rest } = info;
        const name = isCopy ? `${name_str}-copy` : name_str;
        if (parameters && Array.isArray(parameters)) {
          parameters.forEach((item) => {
            const paramName = getReqParamName(item.type);
            item.range = item[paramName];
            item[paramName] = undefined;
          });
        }

        const formData = {
          ...rest,
          name,
          parameters,
          points_to_evaluate: points_to_evaluate ?? [],
        };

        form.setFieldsValue(formData);
      }
    };

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

  // 创建、更新、复制实验
  const createExperiment = async (formData: FormData) => {
    // 按后台接口要求，修改参数表单数据结构，将 "value" 参数改为 "bounds"/"values"/"value"
    const formParameters = formData['parameters'];

    const parameters = formParameters.map((item) => {
      const paramName = getReqParamName(item.type);
      const range = item.range;
      return {
        ...item,
        [paramName]: range,
        range: undefined,
      };
    });

    // 根据后台要求，修改表单数据
    const object = {
      ...formData,
      parameters: parameters,
    };

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

    const request = id && !isCopy ? updateRayReq : addRayReq;
    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-hyper-parameter']}>
      <PageTitle title={title}></PageTitle>
      <div className={styles['create-hyper-parameter__content']}>
        <div>
          <Form
            name="create-hyperparameter"
            labelCol={{ flex: '160px' }}
            labelAlign="left"
            form={form}
            onFinish={handleSubmit}
            size="large"
            autoComplete="off"
            scrollToFirstError
            initialValues={{
              mode: 'max',
              parameters: [
                {
                  name: '',
                },
              ],
              points_to_evaluate: [],
            }}
          >
            <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 CreateHyperParameter;
