<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>
    <UploadLoading :form-loading="formLoading" v-if="formLoading" />
  </div>
</template>

<script lang="ts" setup>
  import { useRoute, useRouter } from 'vue-router';
  import { ref, computed, defineAsyncComponent } from 'vue';
  import { ElMessage } from 'element-plus';
  import UploadLoading from '@/components/UploadLoading.vue';
  import { createDisasterHandleTask } from '@/api/disaster-control';
  import BackIcon from 'assets/svg/back.svg';

  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}`;
    }
    return `查看${fixedTitle}`;
  });
  const dynamicComponent = computed(() => {
    if (operate === 'create') {
      return defineAsyncComponent(() => import('./src/components/CreateDisposalManagementTaskItem.vue'));
    } else {
      return defineAsyncComponent(() => import('./src/components/ViewDisposalControlItem.vue'));
    }
  });
  const dynamicComponentRef = ref();
  const formLoading = ref(false);
  const submit = async () => {
    if (!dynamicComponentRef.value) return;
    const res = await dynamicComponentRef.value.handleValidate();
    if (!res) return;
    formLoading.value = true;
    const formData = dynamicComponentRef.value.getFormData();
    try {
      await createDisasterHandleTask(formData);
      ElMessage.success('提交成功');
      router.back();
    } finally {
      formLoading.value = false;
    }
  };
</script>

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