<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">
      <section class="disaster-information">
        <div class="disaster-information__title">
          <div class="disaster-information--line"></div>
          <span>受灾信息</span>
        </div>
        <div class="disaster-information__content">
          <section class="disaster-information__content--loss" v-if="LossReportItemFormData?.isLoss">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="disaster-information__content--item">
                  <span class="label">受灾物品：</span>
                  <span class="value">{{ LossReportItemFormData?.affectedItems }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="disaster-information__content--item">
                  <span class="label">地点：</span>
                  <span class="value">
                    {{ LossReportItemFormData?.buildingNo }}
                    {{ LossReportItemFormData?.floorNo }}
                    {{ LossReportItemFormData?.roomNo }}
                  </span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="disaster-information__content--item">
                  <span class="label">上报时间：</span>
                  <span class="value">{{ LossReportItemFormData?.updatedAt }}</span>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="disaster-information__content--item">
                  <span class="label">影响安全评估：</span>
                  <span class="value">{{ getSafetyLevel(LossReportItemFormData?.safetyLevel) }}</span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="disaster-information__content--item">
                  <span class="label">是否影响正常工作：</span>
                  <span class="value">
                    {{ LossReportItemFormData?.isAffectWork === 1 ? '是' : '否' }}
                  </span>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="disaster-information__content--item" v-if="LossReportItemFormData?.estimatedLoss">
                  <span class="label">损失金额评估：</span>
                  <span class="value">{{ LossReportItemFormData?.estimatedLoss }}元</span>
                </div>
              </el-col>
            </el-row>
            <div class="disaster-information__content--item">
              <span class="label">损失描述：</span>
              <span class="value">{{ LossReportItemFormData?.description }}</span>
            </div>
            <div class="disaster-information__content--item" v-if="JSON.parse(LossReportItemFormData?.images).length">
              <span class="label">受灾图片：</span>
              <div class="image-container">
                <el-image
                  v-for="(image, index) in JSON.parse(LossReportItemFormData?.images)"
                  :key="index"
                  :src="image"
                  :zoom-rate="1.2"
                  :max-scale="7"
                  :min-scale="0.2"
                  :preview-src-list="JSON.parse(LossReportItemFormData?.images)"
                  show-progress
                  :initial-index="index"
                  fit="contain"
                />
              </div>
            </div>
            <div class="disaster-information__content--item" v-if="LossReportItemFormData?.remark">
              <span class="label">备注：</span>
              <span class="value">{{ LossReportItemFormData?.remark }}</span>
            </div>
          </section>
        </div>
      </section>
      <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 { useDisasterControlHook } from './src/hook';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { useUserInfoHook } from '@/views/disaster/hooks';
  import type { FileItem } from '@/views/disaster/types';
  import type { disasterReportRecordDetailListResponse, 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';

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

  const LossReportItemFormData = ref<disasterReportRecordDetailListResponse>();
  const { getLossReportItem, getSafetyLevel, getSafetyLevelDict } = 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 = Number(route.query.fixTaskId);
  const formLoading = ref(false);
  const getLossReportItemData = async () => {
    const res = await getLossReportItem(handleTaskId, id.value);
    LossReportItemFormData.value = res;
  };
  const { ruleFormConfig, ruleFormData, formRules, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook<DisposalRectificationFormData>(
      DISPOSAL_RECTIFICATION_FORM_CONFIG,
      DISPOSAL_RECTIFICATION_FORM_DATA,
      DISPOSAL_RECTIFICATION_FORM_RULES,
    );
  const rectificationIds = ref<number[]>([]);
  const isShowNextSubmit = computed(() => {
    return rectificationIds.value.length > 1 && rectificationIds.value.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,
      ...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;
    try {
      await submitDisposalRectification();
    } finally {
      formLoading.value = false;
    }
    // 查找当前id在数组中的索引
    const currentIndex = rectificationIds.value.indexOf(id.value);

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

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

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

    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();
    getLossReportItemData();
    getSafetyLevelDict();
    const sessionRectificationIds = sessionStorage.getItem('rectificationIds') || '[]';
    rectificationIds.value = JSON.parse(sessionRectificationIds);
  });
  onUnmounted(() => {
    sessionStorage.removeItem('rectificationIds');
  });
  watch(
    () => route.params.id,
    (newId) => {
      id.value = Number(newId);
      getLossReportItemData();
      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>
