<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" ref="dynamicComponentRef" />
    </main>
    <footer class="disaster-precaution-container__footer" v-if="operate">
      <el-button @click="router.back()">取消</el-button>
      <el-button type="primary" @click="handleSubmitNext" v-if="operate === 'create'">提交，并创建下一条</el-button>
      <el-button type="primary" @click="handleSubmitSingle">提交</el-button>
    </footer>
    <UploadLoading :form-loading="formLoading" v-if="formLoading" />
  </div>
</template>

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

  const router = useRouter();
  const route = useRoute();
  const reportTaskId = Number(route.params.id);
  const dynamicComponentRef = ref();
  const operate = route.query.operation;
  const headerTitle = computed(() => {
    const fixedTitle = '损失记录';
    if (operate === 'create') {
      return `创建${fixedTitle}`;
    } else if (operate === 'edit') {
      return `编辑${fixedTitle}`;
    } else {
      return `查看${fixedTitle}`;
    }
  });
  const dynamicComponent = computed(() => {
    if (operate === 'create') {
      return defineAsyncComponent(() => import('./src/components/CreateLossReportItem.vue'));
    } else if (operate === 'edit') {
      return defineAsyncComponent(() => import('./src/components/EditLossReportItem.vue'));
    } else {
      return '';
    }
  });
  const formLoading = ref(false);
  const formatAttachmentList = async (file: File) => {
    if (!file) return file;
    const fileName = file.name;
    const res = await uploadFileApi({ bizType: UPLOAD_BIZ_TYPE.ATTACHMENT, fileName, file });
    return res.url;
  };
  const createLossReportFunc = async (formData: LossRecordFormData) => {
    const imagesListRes: string[] = await Promise.all(
      (formData.uploadImages || []).map((item) => formatAttachmentList(item)),
    );
    const createParam = {
      reportTaskId,
      ...formData,
      images: imagesListRes,
    };
    await createLossRecord(createParam);
  };

  const editLossReportFunc = async (formData: LossRecordFormData) => {
    const imagesListRes: string[] = await Promise.all(
      (formData.uploadImages || []).map((item) => formatAttachmentList(item)),
    );
    formData.images = [...(formData.images || []), ...imagesListRes];
    const editParam = {
      id: reportTaskId,
      ...formData,
    };
    await editLossRecord(editParam);
  };

  const handleSubmit = async () => {
    const validateResult = await dynamicComponentRef.value?.validateForm();
    if (!validateResult) return;
    const formData = dynamicComponentRef.value?.getFormData();
    formLoading.value = true;
    let message;
    try {
      if (operate === 'create') {
        await createLossReportFunc(formData);
        message = '创建成功';
      } else {
        await editLossReportFunc(formData);
        message = '编辑成功';
      }
      ElMessage.success(message);
      return true; // 成功时返回true
    } catch (error) {
      return false; // 失败时返回false
    } finally {
      formLoading.value = false;
    }
  };
  const handleSubmitSingle = async () => {
    const success = await handleSubmit();
    if (!success) return;
    router.back();
  };
  const handleSubmitNext = async () => {
    const success = await handleSubmit();
    if (!success) return;
    dynamicComponentRef.value?.initFormData();
    // 滚动到页面顶部 - 使用更可靠的方法
    const mainElement = document.querySelector('.info-container');
    if (!mainElement) return;
    mainElement.scrollTop = 0;
  };
</script>

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