<template>
  <div class="safety-platform-container">
    <div class="safety-platform-container__header">
      <BreadcrumbBack />
      <div class="breadcrumb-title">{{ headerTitle }}</div>
    </div>
    <main class="safety-platform-container__main">
      <component ref="dynamicComponentRef" :is="dynamicComponent" :id="id" />
    </main>
    <footer class="safety-platform-container__footer">
      <el-button @click="router.back()">取消</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </footer>
  </div>
</template>

<script setup lang="ts">
  import { useRoute, useRouter } from 'vue-router';
  import { ref, computed, defineAsyncComponent } from 'vue';
  import { ElMessage } from 'element-plus';
  import { addEmergencySupply, editEmergencySupply } from '@/api/emergency-supplier';

  const route = useRoute();
  const router = useRouter();
  const type = String(route.query.type);
  const id = Number(route.query.id);
  const dynamicComponentRef = ref();
  const headerTitle = computed(() => {
    const title = '应急物资';
    if (type === 'add') {
      return `添加${title}`;
    }
    return `编辑${title}`;
  });
  const dynamicComponent = computed(() => {
    if (type === 'add') {
      return defineAsyncComponent(() => import('./src/components/AddEmergencyItem.vue'));
    }
    return defineAsyncComponent(() => import('./src/components/EditEmergencyItem.vue'));
  });
  const handleSubmit = async() => {
    if (!dynamicComponentRef.value) return;
    const message = type === 'add' ? '添加' : '修改';
    const res = await dynamicComponentRef.value.handleValidate();
    if (!res) return;
    const data = dynamicComponentRef.value.getFormData();
    if (type === 'add') {
      await addEmergencySupply(data);
    } else {
      await editEmergencySupply(data);
    }
    ElMessage.success(`${message}成功`);
    router.back();
  };
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
  @use './src/styles/info-common.scss' as *;
</style>
