<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">整改处理</span>
    </header>
    <main class="disaster-precaution-container__main">
      <DisasterInfo :LossReportItemFormData="lossReportItem" v-if="lossReportItem?.isLoss" />
      <section class="disaster-information">
        <div class="disaster-information__title">
          <div class="disaster-information--line"></div>
          <span>整改处理</span>
        </div>
        <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="formRules" :formConfig="ruleFormConfig">
          <template #fixImages>
            <UploadImages ref="uploadImagesRef" @uploadSuccess="handleUploadImageSuccess" />
          </template>
          <template #fixMaterials>
            <UploadFiles ref="uploadFilesRef" label="上传材料" @uploadSuccess="handleUploadFileSuccess" />
          </template>
        </BasicForm>
      </section>
    </main>
    <footer class="disaster-precaution-container__footer">
      <el-button @click="router.back()">取消</el-button>
      <el-button type="primary" v-if="isShowNextSubmit" @click="handleNextSubmit">提交，并处置下一条</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </footer>
    <UploadLoading :form-loading="formLoading" v-if="formLoading" />
  </div>
</template>

<script lang="ts" setup>
  import BackIcon from 'assets/svg/back.svg';
  import { useRoute, useRouter } from 'vue-router';
  import { ref, onMounted, watch, computed, onUnmounted } from 'vue';
  import { ElMessage } from 'element-plus';
  import UploadLoading from '@/components/UploadLoading.vue';
  import BasicForm from '@/components/BasicForm.vue';
  import UploadImages from './src/components/UploadImages.vue';
  import UploadFiles from '@/views/disaster/components/UploadFiles.vue';
  import DisasterInfo from './src/components/DisasterInfo.vue';
  import { useDisasterControlHook } from './src/hook';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { useUserInfoHook } from '@/views/disaster/hooks';
  import type { FileItem } from '@/views/disaster/types';
  import type { DisposalRectificationFormData } from '@/types/disaster-control';
  import { createDisposalRectification } from '@/api/disaster-control';
  import { uploadFileApi, UPLOAD_BIZ_TYPE } from '@/api/minio';
  import {
    DISPOSAL_RECTIFICATION_FORM_CONFIG,
    DISPOSAL_RECTIFICATION_FORM_DATA,
    DISPOSAL_RECTIFICATION_FORM_RULES,
  } from './src/config';

  interface RectificationIds {
    id: number;
    fixTaskId: number;
  }

  const basicFormRef = ref<InstanceType<typeof BasicForm>>();
  const uploadImagesRef = ref<InstanceType<typeof UploadImages>>();
  const uploadFilesRef = ref<InstanceType<typeof UploadFiles>>();

  const { getLossReportItem, lossReportItem } = useDisasterControlHook();
  const { realname, id: userId } = useUserInfoHook();

  const router = useRouter();
  const route = useRoute();
  const id = ref<number>(Number(route.params.id));
  const handleTaskId = Number(route.query.handleTaskId);
  const fixTaskId = computed(() => {
    return Number(route.query.fixTaskId);
  });
  const formLoading = ref(false);
  const { ruleFormConfig, ruleFormData, formRules, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook<DisposalRectificationFormData>(
      DISPOSAL_RECTIFICATION_FORM_CONFIG,
      DISPOSAL_RECTIFICATION_FORM_DATA,
      DISPOSAL_RECTIFICATION_FORM_RULES,
    );
  const rectificationIds = ref<RectificationIds[]>([]);
  const isShowNextSubmit = computed(() => {
    const reportTaskIds = rectificationIds.value.map((item) => item.id);
    return rectificationIds.value.length > 1 && reportTaskIds.includes(id.value);
  });
  const handleUploadImageSuccess = (files: File[]) => {
    ruleFormData.uploadImages = files;
  };
  const handleUploadFileSuccess = (files: FileItem[]) => {
    ruleFormData.uploadFiles = files;
  };
  const formatImageList = 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 formatFileList = async (file: FileItem) => {
    if (!file.file) return file;
    const fileName = file.fileName;
    const res = await uploadFileApi({ bizType: UPLOAD_BIZ_TYPE.ATTACHMENT, fileName, file: file.file });
    const fileType = file.fileType;
    const fileSize = file.fileSize;
    const fileId = file.fileId;
    const fileUrl = res.url;
    return {
      fileName,
      fileType,
      fileSize,
      fileUrl,
      fileId,
    };
  };
  const submitDisposalRectification = async () => {
    const imagesListRes: string[] = await Promise.all(
      (ruleFormData.uploadImages || []).map((item) => formatImageList(item)),
    );
    const fileListRes: FileItem[] = await Promise.all(
      (ruleFormData.uploadFiles || []).map((item) => formatFileList(item)),
    );
    const imagesListString = JSON.stringify(imagesListRes);
    const fileListString = JSON.stringify(fileListRes);
    ruleFormData.fixImages = imagesListString;
    ruleFormData.fixMaterials = fileListString;
    await createDisposalRectification({
      fixTaskId: fixTaskId.value,
      ...ruleFormData,
    });
    ElMessage.success('提交成功');
    cloneRuleFormData();
  };
  const handleSubmit = async () => {
    if (!basicFormRef.value) return;
    const validateResult = await basicFormRef.value.validateForm();
    if (!validateResult) return;
    formLoading.value = true;
    try {
      await submitDisposalRectification();
      router.back();
    } finally {
      formLoading.value = false;
    }
  };
  const defaultRouterName = 'disaster-control-disposal-rectification-item';
  const handleNextSubmit = async () => {
    if (!basicFormRef.value) return;
    const validateResult = await basicFormRef.value.validateForm();
    if (!validateResult) return;
    formLoading.value = true;
    try {
      await submitDisposalRectification();
    } finally {
      formLoading.value = false;
    }
    const reportTaskIds = rectificationIds.value.map((item) => item.id);
    // 查找当前id在数组中的索引
    const currentIndex = reportTaskIds.indexOf(id.value);

    if (currentIndex !== -1) {
      // 从数组中移除当前id
      rectificationIds.value.splice(currentIndex, 1);

      // 确定下一个要处理的id和fixTaskId
      let nextId;
      let nextFixTaskId;
      if (currentIndex < rectificationIds.value.length) {
        // 如果不是最后一个元素，取当前索引位置的元素(移除当前id后，下一个id会自动前移)
        nextId = rectificationIds.value[currentIndex].id;
        nextFixTaskId = rectificationIds.value[currentIndex].fixTaskId;
      } else {
        // 如果是最后一个元素，取第一个元素
        nextId = rectificationIds.value[0].id;
        nextFixTaskId = rectificationIds.value[0].fixTaskId;
      }

      // 保存更新后的数组到sessionStorage
      sessionStorage.setItem('rectificationIds', JSON.stringify(rectificationIds.value));
      router.replace({
        name: defaultRouterName,
        params: {
          id: nextId,
        },
        query: {
          handleTaskId,
          fixTaskId: nextFixTaskId,
        },
      });
    }

    const mainElement = document.querySelector('.disaster-precaution-container__main');
    if (!mainElement) return;
    mainElement.scrollTop = 0;
  };
  const initRuleFormCreatedBy = () => {
    ruleFormData.createdBy = userId;
    ruleFormData.createdByName = realname;
  };
  onMounted(() => {
    initRuleFormCreatedBy();
    cloneRuleFormData();
    beforeRouteLeave();
    getLossReportItem(handleTaskId, id.value);
    const sessionRectificationIds = sessionStorage.getItem('rectificationIds') || '[]';
    rectificationIds.value = JSON.parse(sessionRectificationIds);
  });
  onUnmounted(() => {
    sessionStorage.removeItem('rectificationIds');
  });
  watch(
    () => route.params.id,
    (newId) => {
      id.value = Number(newId);
      getLossReportItem(handleTaskId, id.value);
      basicFormRef.value?.clearValidate();
      initRuleFormCreatedBy();
      uploadImagesRef.value?.removeAllImages();
      uploadFilesRef.value?.removeAllFiles();
      cloneRuleFormData();
    },
  );
</script>

<style lang="scss" scoped>
  @use '../style/disaster.scss' as *;
  @use './src/style/common.scss' as *;
  @use './src//style/view-item.scss' as *;
  .disaster-precaution-container__main {
    display: flex !important;
    flex-direction: column !important;
    gap: 30px !important;
  }
</style>
