/*
 * @Author: 赵伟
 * @Date: 2024-04-16 13:58:08
 * @Description: 创建推理服务
 */

import PageTitle from '@/components/PageTitle';
import SubAreaTitle from '@/components/SubAreaTitle';
import { CommonTabKeys, serviceTypeOptions } from '@/enums';
import { createServiceReq, getServiceInfoReq, updateServiceReq } from '@/services/modelDeployment';
import { ServiceCreatedMessage } from '@/utils/constant';
import { to } from '@/utils/promise';
import { useNavigate, useParams } from '@umijs/max';
import { App, Button, Col, Form, Input, Row, Select } from 'antd';
import { useEffect } from 'react';
import styles from './index.less';

// 表单数据
export type FormData = {
  service_name: string; // 服务名称
  service_type: string; // 服务类型
  description: string; // 描述
};

function CreateService() {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const { message } = App.useApp();
  const params = useParams();
  const serviceId = params.serviceId;

  useEffect(() => {
    // 获取服务详情
    const getServiceInfo = async () => {
      const [res] = await to(getServiceInfoReq(serviceId));
      if (res && res.data) {
        const { service_type, service_name, description } = res.data;
        form.setFieldsValue({
          service_type,
          service_name,
          description,
        });
      }
    };

    if (serviceId) {
      getServiceInfo();
    }
  }, [serviceId, form]);

  // 创建、更新服务
  const createService = async (formData: FormData) => {
    const request = serviceId ? updateServiceReq : createServiceReq;
    const params = serviceId
      ? {
          id: serviceId,
          ...formData,
        }
      : formData;
    const [res] = await to(request(params));
    if (res && res.data) {
      message.success('操作成功');
      navigate(-1);
      if (!serviceId) {
        setTimeout(() => {
          window.postMessage({ type: ServiceCreatedMessage, payload: res.data.id });
        }, 500);
      }
    }
  };

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

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

  const disabled = !!serviceId;
  const title = serviceId ? '编辑推理服务' : '创建推理服务';

  return (
    <div className={styles['model-deployment-create']}>
      <PageTitle title={title}></PageTitle>
      <div className={styles['model-deployment-create__content']}>
        <div>
          <Form
            name="model-deployment-create"
            labelCol={{ flex: '100px' }}
            labelAlign="left"
            form={form}
            initialValues={{ upload_type: CommonTabKeys.Public }}
            onFinish={handleSubmit}
            size="large"
            autoComplete="off"
          >
            <SubAreaTitle
              title="基本信息"
              image={require('@/assets/img/mirror-basic.png')}
              style={{ marginBottom: '26px' }}
            ></SubAreaTitle>
            <Row gutter={8}>
              <Col span={10}>
                <Form.Item
                  label="服务名称"
                  name="service_name"
                  rules={[
                    {
                      required: true,
                      message: '请输入服务名称',
                    },
                  ]}
                >
                  <Input
                    placeholder="请输入服务名称"
                    disabled={disabled}
                    maxLength={30}
                    showCount
                    allowClear
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={8}>
              <Col span={10}>
                <Form.Item
                  label="服务类型"
                  name="service_type"
                  rules={[
                    {
                      required: true,
                      message: '请选择服务类型',
                    },
                  ]}
                >
                  <Select placeholder="请选择服务类型" options={serviceTypeOptions} allowClear />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={8}>
              <Col span={20}>
                <Form.Item
                  label="描　　述"
                  name="description"
                  rules={[
                    {
                      required: true,
                      message: '请输入描述',
                    },
                  ]}
                >
                  <Input.TextArea
                    autoSize={{ minRows: 2, maxRows: 6 }}
                    placeholder="请输入描述，最长128字符"
                    maxLength={128}
                    showCount
                    allowClear
                  />
                </Form.Item>
              </Col>
            </Row>

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

export default CreateService;
