<script setup lang="ts">
import type { EditorService } from '@core/editor.service';
import { type FormInstance, message } from 'ant-design-vue';
import { isError } from 'lodash-es';
import { inject, type InjectionKey, reactive, ref, type ShallowRef, shallowRef } from 'vue';
import { useI18n } from 'vue-i18n';

type Props = {
  token: InjectionKey<ShallowRef<EditorService>>;
};
const props = defineProps<Props>();
const editor = inject(props.token)!;

export type RobotGroupRenameModalRef = Ref;
type Ref = {
  open: (id: string, label: string) => void;
};
const open: Ref['open'] = (id, label) => {
  form.value?.resetFields();
  data.id = id;
  data.label = label;
  show.value = true;
};
defineExpose<Ref>({ open });

const { t } = useI18n();

const show = ref<boolean>(false);

const form = shallowRef<FormInstance>();
const data = reactive<{ id: string; label: string }>({ id: '', label: '' });

const submit = async () => {
  try {
    await form.value?.validate();
    editor.value.updateRobotGroupLabel(data.id, data.label);
    show.value = false;
  } catch (error) {
    if (isError(error)) {
      message.error(t(error?.message));
    } else {
      console.debug(error);
    }
  }
};
</script>

<template>
  <a-modal :width="460" :title="$t('修改组名称')" v-model:open="show" :mask-closable="false" centered @ok="submit">
    <a-form ref="form" class="mr-14" :model="data">
      <a-form-item :label="$t('机器人组名称')" name="label" :rules="[{ required: true, message: '' }]">
        <a-input :placeholder="$t('请输入')" :maxlength="16" v-model:value="data.label" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
