<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <BreadcrumbBack />
      <span class="breadcrumb-title">{{ headerTitle }}</span>
    </header>
    <TaskInfoSection :task-name="taskName" @export-loss-detail="exportLossDetail" v-if="!operate" />
    <main class="safety-platform-container__main">
      <component :is="dynamicComponent" ref="dynamicComponentRef" />
    </main>
    <footer class="safety-platform-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 TaskInfoSection from './src/components/TaskInfoSection.vue';
  import { exportLossRecord } from '@/views/disaster/disaster-control/src/util';
  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 id = Number(route.query.id);
  const taskName = String(route.query.taskName);
  const deptId = Number(route.query.deptId);
  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 '灾害损失记录明细';
    }
  });
  const exportLossDetail = async () => {
    const params = {
      handleTaskId: reportTaskId,
      reportDeptId: deptId,
    };
    await exportLossRecord(params, taskName);
    ElMessage.success(`导出${taskName}损失明细成功`);
  };
  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 defineAsyncComponent(() => import('./src/components/ViewLossReportItem.vue'));
    }
  });
  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,
      ...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 '@/styles/page-details-layout.scss' as *;
  @use './src/style/common.scss' as *;
</style>
