<template>
  <Dialog
    v-model="visible"
    :diaTitle="`${id ? '编辑' : '新建'}文件夹`"
    :width="400"
    @close="closeFun"
  >
    <div class="content">
      <TableForm
        ref="tableFormRef"
        v-model:data="formData"
        :itemNum="1"
        tableName="DATA_OVERVIEW_DIR_DETAIL"
      />
    </div>
    <template #footer>
      <div>
        <el-button @click="closeFun">关闭</el-button>
        <el-button type="primary" @click="submitFun">确定</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import Dialog from '@/components/common/dialog/index.vue';
import { ElMessage } from 'element-plus';
import TableForm from '@/components/common/table/tableForm.vue';
import { dataCreateDirApi, dataRenameDirApi } from '@/api/data/data';

const emit = defineEmits(['update:modelValue', 'submit']);
const visible = ref(false);
const tableFormRef = ref<any>();

interface Props {
  modelValue: boolean;
  id: any;
  data: any;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  id: '',
  data: {},
});

const formData = ref<any>({});

watch(
  () => props.modelValue,
  (val: boolean) => {
    visible.value = val;
    if (val) {
      if (props.id) {
        formData.value.dirName = props.data.originalName;
      }
    } else {
      formData.value = {};
      if (tableFormRef.value) {
        tableFormRef.value.resetFun();
      }
    }
  }
);

const submitFun = async () => {
  const valid = await tableFormRef.value.validateFun();
  if (valid) {
    let params: any = {};
    let api: any = null;
    if (props.id) {
      params = {
        dirId: props.data.id,
        oldName: props.data.originalName,
        newName: formData.value.dirName,
        type: 0,
      };
      api = dataRenameDirApi;
    } else {
      params = {
        parDirId: props.data.id,
        dirType: 2, // 1知识库文件夹 2项目节点文件夹 3头像库文件夹 4仿真参数库文件夹 5训练模型文件夹
        ...formData.value,
      };
      api = dataCreateDirApi;
    }
    api(params).then((res: any) => {
      if (res.code === 200) {
        ElMessage.success('操作成功');
        closeFun();
        emit('submit');
      }
    });
  }
};

const closeFun = () => {
  emit('update:modelValue', false);
};
</script>
