/*
 * @Author: 赵伟
 * @Date: 2024-04-16 13:58:08
 * @Description: 创建模型部署
 */
import PageTitle from '@/components/PageTitle';
import SubAreaTitle from '@/components/SubAreaTitle';
import { CommonTabKeys } from '@/enums';
import { createMirrorReq } from '@/services/mirror';
import { getComputingResourceReq } from '@/services/pipeline';
import { to } from '@/utils/promise';
import { getSessionItemThenRemove, mirrorNameKey } from '@/utils/sessionStorage';
import { validateUploadFiles } from '@/utils/ui';
import { useNavigate } from '@umijs/max';
import { Button, Col, Form, Input, Row, Select, UploadFile, message, type SelectProps } from 'antd';
import { omit } from 'lodash';
import { useEffect, useState } from 'react';
import styles from './create.less';

type FormData = {
  name: string;
  tag: string;
  description: string;
  path?: string;
  upload_type: string;
  fileList?: UploadFile[];
};

function ModelDeploymentCreate() {
  const navgite = useNavigate();
  const [form] = Form.useForm();
  const [nameDisabled, setNameDisabled] = useState(false);
  const [resourceStandardList, setResourceStandardList] = useState([]);

  useEffect(() => {
    const name = getSessionItemThenRemove(mirrorNameKey);
    if (name) {
      form.setFieldValue('name', name);
      setNameDisabled(true);
    }
    getComputingResource();
  }, []);

  const getComputingResource = async () => {
    const params = {
      page: 0,
      size: 1000,
      resource_type: '',
    };
    const [res] = await to(getComputingResourceReq(params));
    if (res && res.data && res.data.content) {
      setResourceStandardList(res.data.content);
    }
  };

  const filterResourceStandard: SelectProps['filterOption'] = (
    input: string,
    { computing_resource = '' },
  ) => {
    return computing_resource.toLocaleLowerCase().includes(input.toLocaleLowerCase());
  };

  // 创建公网、本地镜像
  const createPublicMirror = async (formData: FormData) => {
    const upload_type = formData['upload_type'];
    let params;
    if (upload_type === CommonTabKeys.Public) {
      params = {
        ...omit(formData, ['upload_type']),
        upload_type: 0,
        image_type: 0,
      };
    } else {
      const fileList = formData['fileList'] ?? [];
      if (validateUploadFiles(fileList)) {
        const file = fileList[0];
        params = {
          ...omit(formData, ['fileList', 'upload_type']),
          path: file.response.data.url,
          file_size: file.response.data.fileSize,
          upload_type: 1,
          image_type: 0,
        };
      }
    }

    const [res] = await to(createMirrorReq(params));
    if (res) {
      message.success('创建成功');
      navgite(-1);
    }
  };

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

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

  return (
    <div className={styles['model-deployment-create']}>
      <PageTitle title="创建推理服务"></PageTitle>
      <div className={styles['model-deployment-create__content']}>
        <div>
          <Form
            name="model-deployment-create"
            labelCol={{ flex: '130px' }}
            wrapperCol={{ flex: 1 }}
            labelAlign="left"
            form={form}
            initialValues={{ upload_type: CommonTabKeys.Public }}
            onFinish={handleSubmit}
            size="large"
          >
            <SubAreaTitle
              title="基本信息"
              image={require('@/assets/img/mirror-basic.png')}
              style={{ marginBottom: '26px' }}
            ></SubAreaTitle>
            <Row gutter={10}>
              <Col span={10}>
                <Form.Item
                  label="服务名称"
                  name="name"
                  rules={[
                    {
                      required: true,
                      message: '请输入服务名称',
                    },
                  ]}
                >
                  <Input
                    placeholder="请输入服务名称"
                    maxLength={64}
                    disabled={nameDisabled}
                    showCount
                    allowClear
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={10}>
              <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>
            <SubAreaTitle
              title="部署构建"
              image={require('@/assets/img/mirror-version.png')}
              style={{ marginTop: '20px', marginBottom: '24px' }}
            ></SubAreaTitle>

            <Row gutter={10}>
              <Col span={10}>
                <Form.Item
                  label="选择模型"
                  name="name"
                  rules={[
                    {
                      required: true,
                      message: '请输入模型',
                    },
                  ]}
                >
                  <Input
                    placeholder="请输入模型"
                    maxLength={64}
                    disabled={nameDisabled}
                    showCount
                    allowClear
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={10}>
              <Col span={10}>
                <Form.Item
                  label="选择镜像"
                  name="name"
                  rules={[
                    {
                      required: true,
                      message: '请输入镜像',
                    },
                  ]}
                >
                  <Input
                    placeholder="请输入镜像"
                    maxLength={64}
                    disabled={nameDisabled}
                    showCount
                    allowClear
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={10}>
              <Col span={10}>
                <Form.Item
                  label="资源规格"
                  name="name"
                  rules={[
                    {
                      required: true,
                      message: '请选择资源规格',
                    },
                  ]}
                >
                  <Select
                    showSearch
                    placeholder="请选择资源规格"
                    filterOption={filterResourceStandard}
                    options={resourceStandardList}
                    fieldNames={{
                      label: 'description',
                      value: 'standard',
                    }}
                  />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={10}>
              <Col span={10}>
                <Form.Item
                  label="副本数量"
                  name="name"
                  rules={[
                    {
                      required: true,
                      message: '请输入副本数量',
                    },
                  ]}
                >
                  <Input
                    placeholder="请输入副本数量"
                    maxLength={64}
                    disabled={nameDisabled}
                    showCount
                    allowClear
                  />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={10}>
              <Col span={10}>
                <Form.Item label="环境变量" name="name">
                  <Button type="link" style={{ padding: '0' }}>
                    添加环境变量
                  </Button>
                </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 ModelDeploymentCreate;
