/*
 * @Author: 赵伟
 * @Date: 2024-04-16 13:58:08
 * @Description: 创建镜像
 */
import KFIcon from '@/components/KFIcon';
import KFRadio, { type KFRadioItem } from '@/components/KFRadio';
import PageTitle from '@/components/PageTitle';
import ParameterInput from '@/components/ParameterInput';
import SubAreaTitle from '@/components/SubAreaTitle';
import { useComputingResource } from '@/hooks/resource';
import ResourceSelectorModal, {
  ResourceSelectorResponse,
  ResourceSelectorType,
  selectorTypeConfig,
} from '@/pages/Pipeline/components/ResourceSelectorModal';
import { createEditorReq } from '@/services/developmentEnvironment';
import { openAntdModal } from '@/utils/modal';
import { to } from '@/utils/promise';
import { useNavigate } from '@umijs/max';
import { App, Button, Col, Form, Input, Row, Select } from 'antd';
import { pick } from 'lodash';
import { useState } from 'react';
import styles from './index.less';

type FormData = {
  name: string;
  computing_resource: string;
  standard: string;
  image: string;
  model: ResourceSelectorResponse;
  dataset: ResourceSelectorResponse;
};

enum ComputingResourceType {
  GPU = 'GPU',
  NPU = 'NPU',
}

const EditorRadioItems: KFRadioItem[] = [
  {
    key: ComputingResourceType.GPU,
    title: '英伟达GPU',
    icon: <KFIcon type="icon-jiyugongwangjingxiang" />,
  },
  {
    key: ComputingResourceType.NPU,
    title: '昇腾NPU',
    icon: <KFIcon type="icon-bendishangchuan" />,
  },
];

function EditorCreate() {
  const navgite = useNavigate();
  const [form] = Form.useForm();
  const { message } = App.useApp();
  const [resourceStandardList, filterResourceStandard] = useComputingResource();
  const [selectedModel, setSelectedModel] = useState<ResourceSelectorResponse | undefined>(
    undefined,
  ); // 选择的模型，为了再次打开时恢复原来的选择
  const [selectedDataset, setSelectedDataset] = useState<ResourceSelectorResponse | undefined>(
    undefined,
  ); // 选择的数据集，为了再次打开时恢复原来的选择
  const [selectedMirror, setSelectedMirror] = useState<ResourceSelectorResponse | undefined>(
    undefined,
  ); // 选择的镜像，为了再次打开时恢复原来的选择

  // 创建编辑器
  const createEditor = async (formData: FormData) => {
    // const { model, dataset } = formData;
    // const params = {
    //   ...formData,
    //   model: JSON.stringify(omit(model, ['showValue'])),
    //   dataset: JSON.stringify(dataset, ['showValue']),
    // };
    const [res] = await to(createEditorReq(formData));
    if (res) {
      message.success('创建成功');
      navgite(-1);
    }
  };

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

  // 取消
  const cancel = () => {
    navgite(-1);
  };
  // 获取选择数据集、模型后面按钮 icon
  const getSelectBtnIcon = (type: ResourceSelectorType) => {
    return <KFIcon type={selectorTypeConfig[type].buttonIcon} font={16} />;
  };

  // 选择模型、镜像、数据集
  const selectResource = (name: string, type: ResourceSelectorType) => {
    let resource: ResourceSelectorResponse | undefined;
    switch (type) {
      case ResourceSelectorType.Model:
        resource = selectedModel;
        break;
      case ResourceSelectorType.Dataset:
        resource = selectedDataset;
        break;
      default:
        resource = selectedMirror;
        break;
    }
    const { close } = openAntdModal(ResourceSelectorModal, {
      type,
      defaultExpandedKeys: resource ? [resource.id] : [],
      defaultCheckedKeys: resource ? [`${resource.id}-${resource.version}`] : [],
      defaultActiveTab: resource?.activeTab,
      onOk: (res) => {
        if (res) {
          if (type === ResourceSelectorType.Mirror) {
            form.setFieldValue(name, res.path);
            setSelectedMirror(res);
          } else {
            const showValue = `${res.name}:${res.version}`;
            form.setFieldValue(name, {
              ...pick(res, ['id', 'version', 'path']),
              showValue,
            });
            if (type === ResourceSelectorType.Model) {
              setSelectedModel(res);
            } else if (type === ResourceSelectorType.Dataset) {
              setSelectedDataset(res);
            }
          }
        } else {
          if (type === ResourceSelectorType.Model) {
            setSelectedModel(undefined);
          } else if (type === ResourceSelectorType.Dataset) {
            setSelectedDataset(undefined);
          } else if (type === ResourceSelectorType.Mirror) {
            setSelectedMirror(undefined);
          }
          form.setFieldValue(name, '');
        }
        close();
      },
    });
  };

  return (
    <div className={styles['editor-create']}>
      <PageTitle title="创建编辑器"></PageTitle>
      <div className={styles['editor-create__content']}>
        <div>
          <Form
            name="editor-create"
            labelCol={{ flex: '100px' }}
            wrapperCol={{ flex: 1 }}
            labelAlign="left"
            form={form}
            initialValues={{ computing_resource: ComputingResourceType.GPU }}
            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} showCount allowClear />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={10}>
              <Col span={10}>
                <Form.Item
                  label="计算资源"
                  name="computing_resource"
                  rules={[
                    {
                      required: true,
                      message: '请选择计算资源',
                    },
                  ]}
                >
                  <KFRadio items={EditorRadioItems}></KFRadio>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={8}>
              <Col span={10}>
                <Form.Item
                  label="资源规格"
                  name="standard"
                  rules={[
                    {
                      required: true,
                      message: '请选择资源规格',
                    },
                  ]}
                >
                  <Select
                    showSearch
                    placeholder="请选择资源规格"
                    filterOption={filterResourceStandard}
                    options={resourceStandardList}
                    fieldNames={{
                      label: 'description',
                      value: 'standard',
                    }}
                  />
                </Form.Item>
              </Col>
            </Row>
            <SubAreaTitle
              title="参数设置"
              image={require('@/assets/img/editor-parameter.png')}
              style={{ marginTop: '20px', marginBottom: '24px' }}
            ></SubAreaTitle>
            <Row gutter={8}>
              <Col span={10}>
                <Form.Item
                  label="镜像"
                  name="image"
                  rules={[
                    {
                      required: true,
                      message: '请输入镜像',
                    },
                  ]}
                >
                  <ParameterInput
                    placeholder="请选择镜像"
                    canInput={false}
                    size="large"
                    onClick={() => selectResource('image', ResourceSelectorType.Mirror)}
                  />
                </Form.Item>
              </Col>
              <Col span={10}>
                <Button
                  size="large"
                  type="link"
                  icon={getSelectBtnIcon(ResourceSelectorType.Mirror)}
                  onClick={() => selectResource('image', ResourceSelectorType.Mirror)}
                >
                  选择镜像
                </Button>
              </Col>
            </Row>
            <Row gutter={8}>
              <Col span={10}>
                <Form.Item
                  label="模型"
                  name="model"
                  rules={[
                    {
                      required: true,
                      message: '请选择模型',
                    },
                  ]}
                >
                  <ParameterInput
                    placeholder="请选择模型"
                    canInput={false}
                    size="large"
                    onClick={() => selectResource('model', ResourceSelectorType.Model)}
                  />
                </Form.Item>
              </Col>
              <Col span={10}>
                <Button
                  size="large"
                  type="link"
                  icon={getSelectBtnIcon(ResourceSelectorType.Model)}
                  onClick={() => selectResource('model', ResourceSelectorType.Model)}
                >
                  选择模型
                </Button>
              </Col>
            </Row>
            <Row gutter={8}>
              <Col span={10}>
                <Form.Item
                  label="数据集"
                  name="dataset"
                  rules={[
                    {
                      required: true,
                      message: '请选择数据集',
                    },
                  ]}
                >
                  <ParameterInput
                    placeholder="请选择数据集"
                    canInput={false}
                    size="large"
                    onClick={() => selectResource('dataset', ResourceSelectorType.Dataset)}
                  />
                </Form.Item>
              </Col>
              <Col span={10}>
                <Button
                  size="large"
                  type="link"
                  icon={getSelectBtnIcon(ResourceSelectorType.Dataset)}
                  onClick={() => selectResource('dataset', ResourceSelectorType.Dataset)}
                >
                  选择数据集
                </Button>
              </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 EditorCreate;
