<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <BreadcrumbBack />
      <span class="breadcrumb-title">整改处理</span>
    </header>
    <main class="safety-platform-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="safety-platform-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 { 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 '@/components/UploadImages/UploadImages.vue';
  import UploadFiles from '@/components/UploadFiles/UploadFiles.vue';
  import { formatAttachment } from '@/components/UploadFiles/utils';
  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 '@/components/UploadFiles/types.ts';
  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 uuid = Math.random().toString(36).substring(2, 9);
    const timestamp = Date.now().toString();
    const random = Math.random().toString(36).substring(2, 4);
    const res = await uploadFileApi({
      bizType: UPLOAD_BIZ_TYPE.ATTACHMENT,
      fileName: `${uuid}-${timestamp}-${random}`,
      file,
    });
    return res.url;
  };

  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) => formatAttachment(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 '@/styles/page-details-layout.scss' as *;
  @use './src/style/common.scss' as *;
  @use './src//style/view-item.scss' as *;
  .safety-platform-container__main {
    display: flex !important;
    flex-direction: column !important;
    gap: 30px !important;
  }
</style>
