<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="LossReportItemFormData?.images">
              <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 @uploadSuccess="handleUploadImageSuccess" />
          </template>
          <template #fixMaterials>
            <Upload 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">提交，并处置下一条</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 UploadLoading from '@/components/UploadLoading.vue';
  import BasicForm from '@/components/BasicForm.vue';
  import UploadImages from './src/components/UploadImages.vue';
  import Upload from '@/views/disaster/components/Upload.vue';
  import { ref, onMounted } from 'vue';
  import { useDisasterControlHook } from './src/hook';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { useUserInfoHook } from '@/views/disaster/hooks/userInfo';
  import { createDisposalRectification } from '@/api/disaster-control';
  import { uploadFileApi, UPLOAD_BIZ_TYPE } from '@/api/minio';
  import type { FileItem } from '@/views/disaster/types';
  import type { disasterReportRecordDetailListResponse, DisposalRectificationFormData } from '@/types/disaster-control';
  import {
    DISPOSAL_RECTIFICATION_FORM_CONFIG,
    DISPOSAL_RECTIFICATION_FORM_DATA,
    DISPOSAL_RECTIFICATION_FORM_RULES,
  } from './src/config';
  import { ElMessage } from 'element-plus';

  const basicFormRef = ref<InstanceType<typeof BasicForm>>();

  const LossReportItemFormData = ref<disasterReportRecordDetailListResponse>();
  const { getLossReportItem, getSafetyLevel, getSafetyLevelDict } = useDisasterControlHook();
  const { realname, id: userId } = useUserInfoHook();

  const router = useRouter();
  const route = useRoute();
  const id = 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);
    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 = ref(false);
  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 handleSubmit = async () => {
    if (!basicFormRef.value) return;
    const validateResult = await basicFormRef.value.validateForm();
    if (!validateResult) return;
    formLoading.value = true;
    try {
      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();
      router.back();
    } finally {
      formLoading.value = false;
    }
  };
  onMounted(() => {
    ruleFormData.createdBy = userId;
    ruleFormData.createdByName = realname;
    cloneRuleFormData();
    beforeRouteLeave();
    getLossReportItemData();
    getSafetyLevelDict();
    const sessionRectificationIds = sessionStorage.getItem('rectificationIds') || '[]';
    rectificationIds.value = JSON.parse(sessionRectificationIds);
    isShowNextSubmit.value = rectificationIds.value.length > 1 && rectificationIds.value.includes(id);
  });
</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;
  }
  :deep(.el-date-editor) {
    --el-date-editor-width: 100%;
  }
</style>
