<template>
  <div class="disaster-precaution-container">
    <header class="disaster-precaution-container__header">
      <img :src="BackIcon" alt="back" class="back-icon" @click="router.back()" />
      <span class="disaster-precaution-container__title">{{ headerTitle }}</span>
    </header>
    <main class="disaster-precaution-container__main">
      <component :is="dynamicComponent" :id="id" ref="dynamicComponentRef" />
    </main>
    <footer class="disaster-precaution-container__footer" v-if="operate">
      <el-button @click="router.back()">取消</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </footer>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, defineAsyncComponent } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import BackIcon from 'assets/svg/back.svg';
  import { ElMessage } from 'element-plus';
  const router = useRouter();
  const route = useRoute();
  const operate = route.query.operate;
  const id = route.query.id;
  const headerTitle = computed(() => {
    const fixedTitle = '灾害预警信息';
    if (operate === 'create') {
      return `创建${fixedTitle}`;
    } else if (operate === 'edit') {
      return `编辑${fixedTitle}`;
    }
    return '未知操作';
  });
  const dynamicComponent = computed(() => {
    if (operate === 'create') {
      return defineAsyncComponent(() => import('./src/components/CreateWarningInfoItem.vue'));
    } else if (operate === 'edit') {
      return defineAsyncComponent(() => import('./src/components/EditWarningInfoItem.vue'));
    } else {
      return '';
    }
  });
  const dynamicComponentRef = ref();
  const submit = async () => {
    if (!dynamicComponentRef.value) return;
    const res = await dynamicComponentRef.value.handleValidate();
    if (res) {
      const formData = dynamicComponentRef.value.getFormData();
      console.log(formData);
      ElMessage.success('提交成功');
      router.back();
    } else {
      console.log('不提交');
    }
  };
</script>

<style lang="scss" scoped>
  @use '../style/disaster.scss' as *;
  @use './src/common.scss' as *;
</style>
