<script setup lang="ts">
import { defineAsyncComponent, inject, ref } from 'vue';

// 从主组件注入状态
const tableState: any = inject('tableState');
const tableMethods: any = inject('tableMethods');
const { uiConfig } = tableState;

const showDialog = ref(false);
// 添加当前编辑的行数据
const currentRow = ref<any>(null);
const isEditMode = ref(false);

// 动态加载组件
const DynamicComponent = defineAsyncComponent(() => import(uiConfig.CreateVueUrl));

// 处理子组件关闭事件
const handleClose = () => {
  // console.log('关闭弹窗');
  showDialog.value = false;
  // 重置状态
  currentRow.value = null;
  isEditMode.value = false;
  // 刷新表格数据
  tableMethods.fetchData();
};

// 处理子组件提交事件
const handleSubmit = () => {
  // console.log('提交表单');
  showDialog.value = false;
  // 重置状态
  currentRow.value = null;
  isEditMode.value = false;
  // 刷新表格数据
  tableMethods.fetchData();
};

// 打开弹窗的方法
const open = (row?: any) => {
  // 如果传入了row参数，则表示是编辑模式
  if (row) {
    currentRow.value = row;
    isEditMode.value = true;
    // console.log('打开编辑模式', row);
  } else {
    currentRow.value = null;
    isEditMode.value = false;
    // console.log('打开新建模式');
  }
  showDialog.value = true;
};

// 暴露方法给父组件
defineExpose({
  open
});

defineOptions({
  name: 'CreateDialog'
});
</script>

<template>
  <NModal
    :show="showDialog"
    preset="card"
    style="width: 90%; max-width: 1200px"
    :mask-closable="false"
    @update:show="showDialog = $event"
  >
    <template #header>
      <div class="dialog-header">
        <span>{{ isEditMode ? '编辑' : '新建' }}</span>
      </div>
    </template>
    <div class="dialog-content">
      <DynamicComponent
        v-if="showDialog"
        :edit-data="currentRow"
        :is-edit="isEditMode"
        @close="handleClose"
        @submit="handleSubmit"
      />
    </div>
  </NModal>
</template>

<style scoped>
.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.dialog-content {
  width: 100%;
  height: 100%;
}
</style>
