<template>
  <Dialog
    showFooter
    v-model="visible"
    show-cancel-button
    show-confirm-button
    :diaTitle="mode === 'add' ? $t('知识库.新增') : $t('知识库.编辑')"
    :confirm-closable="false"
    @show="onShowFun"
  >
    <template #default>
      <el-form ref='formRef' :rules="rules" :model="form" labelWidth="80">
        <el-form-item :label="$t('知识库.名称')" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div>
        <el-button @click="onCancelFun">{{ $t('通用.取消') }}</el-button>
        <el-button type="primary" @click="onConfirmFun">{{ $t('通用.确定') }}</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive, watchEffect } from 'vue';
import Dialog from '@/components/common/dialog/index.vue';
import type { FormInstance, FormRules } from 'element-plus';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
interface Props {
  modelValue: boolean;
  detail: any,
  mode: 'add' | 'edit'
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  detail: null,
  mode: 'add',
});

const emits = defineEmits(['update:modelValue', 'confirm']);
const form = ref({
  name: '',
});

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emits('update:modelValue', val),
});
watchEffect(() => {
  if (props.detail && props.mode === 'edit') {
    form.value.name = props.detail.originalName || props.detail.nodeName;
  } else {
    form.value.name = '';
  }
});
const onShowFun = () => {
  resetFun();
  if (props.detail && props.mode === 'edit') {
    form.value.name = props.detail.originalName || props.detail.nodeName;
  } else {
    form.value.name = '';
  }
};
const resetFun = () => {
  if (!formRef.value) {
    return;
  }
  formRef.value.resetFields();
};
const formRef = ref<FormInstance>();
interface RuleForm {
  name: string
}
const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: t('知识库.请输入名称'), trigger: 'blur' },
  ],
});
const onCancelFun = () => {
  visible.value = false;
};
const onConfirmFun = async () => {
  if (!formRef.value) {
    return;
  }
  await formRef.value.validate((valid) => {
    if (valid) {
      emits('confirm', form.value);
    }
  });
};
onMounted(async () => {

});
</script>
