/*
 * @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, updateServiceReq } from '@/services/modelDeployment';
import { to } from '@/utils/promise';
import {
  getSessionStorageItem,
  removeSessionStorageItem,
  serviceInfoKey,
} from '@/utils/sessionStorage';
import { useNavigate } from '@umijs/max';
import { App, Button, Col, Form, Input, Row, Select } from 'antd';
import { pick } from 'lodash';
import { useEffect, useState } from 'react';
import { ServiceData, ServiceOperationType } from '../types';
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 [operationType, setOperationType] = useState(ServiceOperationType.Create);
  const [serviceInfo, setServiceInfo] = useState<ServiceData | undefined>(undefined);
  const { message } = App.useApp();

  useEffect(() => {
    const res = getSessionStorageItem(serviceInfoKey, true);
    if (res) {
      setOperationType(res.operationType);
      setServiceInfo(res);
      form.setFieldsValue(pick(res, ['service_name', 'service_type', 'description']));
    }
    return () => {
      removeSessionStorageItem(serviceInfoKey);
    };
  }, []);

  // 创建、更新服务
  const createService = async (formData: FormData) => {
    const request =
      operationType === ServiceOperationType.Create ? createServiceReq : updateServiceReq;
    const params =
      operationType === ServiceOperationType.Create
        ? formData
        : {
            id: serviceInfo?.id,
            ...formData,
          };
    const [res] = await to(request(params));
    if (res) {
      message.success('操作成功');
      navigate(-1);
    }
  };

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

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

  const disabled = operationType !== ServiceOperationType.Create;
  const title = operationType === ServiceOperationType.Create ? '创建推理服务' : '更新推理服务';

  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;
