<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <BreadcrumbBack />
      <span class="breadcrumb-title">{{ type === 'edit' ? '编辑' : '上传' }}灾后评估材料及重建方案</span>
    </header>
    <main class="safety-platform-container__main">
      <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="formRules" :formConfig="ruleFormConfig">
        <template #disasterAssessMaterials>
          <UploadFiles
            label="上传文件"
            ref="uploadFilesRef"
            :fileList="ruleFormData.disasterAssessMaterials"
            @upload-success="handleUploadSuccessAssessMaterials"
          />
        </template>
        <template #disasterReconstructMaterials>
          <UploadFiles
            label="上传文件"
            ref="uploadFilesRef"
            :fileList="ruleFormData.disasterReconstructMaterials"
            @upload-success="handleUploadSuccessReconstructMaterials"
          />
        </template>
      </BasicForm>
    </main>
    <footer class="safety-platform-container__footer">
      <el-button @click="router.back()">取消</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </footer>
    <UploadLoading :form-loading="formLoading" v-if="formLoading" />
  </div>
</template>

<script setup lang="ts">
  import { onMounted, ref } from 'vue';
  import { storeToRefs } from 'pinia';
  import { useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { usePostDisasterMaterial } from '@/store/modules/usePostDisasterMaterial';
  import BasicForm from '@/components/BasicForm.vue';
  import UploadFiles from '@/components/UploadFiles/UploadFiles.vue';
  import UploadLoading from '@/components/UploadLoading.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { POST_DISASTER_MATERIAL_FORM_CONFIG, POST_DISASTER_MATERIAL_FORM_DATA } from './src/config/form';
  import { FileItem } from '@/components/UploadFiles/types';
  import { unformatAttachment, formatAttachmentList } from '@/components/UploadFiles/utils';
  import type { UpdateDisasterHandleTaskQuery } from '@/types/disaster-control';
  import { updateDisasterHandleTask } from '@/api/disaster-control';

  interface PostDisasterMaterialFormData {
    disasterAssessMaterials: FileItem[];
    disasterReconstructMaterials: FileItem[];
  }

  const { ruleFormConfig, ruleFormData, formRules, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook<PostDisasterMaterialFormData>(
      POST_DISASTER_MATERIAL_FORM_CONFIG,
      POST_DISASTER_MATERIAL_FORM_DATA,
    );

  const postDisasterMaterialStore = usePostDisasterMaterial();
  const { id, type, disasterAssessMaterials, disasterReconstructMaterials } = storeToRefs(postDisasterMaterialStore);

  const router = useRouter();
  const formLoading = ref(false);

  const getDetail = async () => {
    ruleFormData.disasterAssessMaterials = unformatAttachment(disasterAssessMaterials.value) || [];
    ruleFormData.disasterReconstructMaterials = unformatAttachment(disasterReconstructMaterials.value) || [];
    cloneRuleFormData();
  };

  const getFormData = async () => {
    cloneRuleFormData();
    const res: UpdateDisasterHandleTaskQuery = {
      id: id.value,
      disasterAssessMaterials: JSON.stringify(await formatAttachmentList(ruleFormData.disasterAssessMaterials)),
      disasterReconstructMaterials: JSON.stringify(
        await formatAttachmentList(ruleFormData.disasterReconstructMaterials),
      ),
    };
    return res;
  };

  const handleUploadSuccessAssessMaterials = (fileList: FileItem[]) => {
    ruleFormData.disasterAssessMaterials = fileList;
  };

  const handleUploadSuccessReconstructMaterials = (fileList: FileItem[]) => {
    ruleFormData.disasterReconstructMaterials = fileList;
  };

  const handleSubmit = async () => {
    const hasAssessMaterials = ruleFormData.disasterAssessMaterials?.length;
    const hasReconstructMaterials = ruleFormData.disasterReconstructMaterials?.length;
    if (!hasAssessMaterials && !hasReconstructMaterials) {
      ElMessage.warning('请上传相关文件');
      return;
    }
    try {
      formLoading.value = true;
      const params = await getFormData();
      await updateDisasterHandleTask(params);
      ElMessage.success(type.value === 'edit' ? '编辑成功' : '上传成功');
      router.back();
    } catch (e) {
      console.log(e);
    } finally {
      formLoading.value = false;
    }
  };

  onMounted(() => {
    beforeRouteLeave();
    getDetail();
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;

  .safety-platform-container__header {
    flex-direction: row !important;
    justify-content: flex-start !important;
    gap: 8px !important;
  }
</style>
