<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">{{ headerTitle }}</span>
    </header>
    <main class="disaster-precaution-container__main">
      <component :is="dynamicComponent" :id="id" ref="dynamicComponentRef" />
    </main>
    <footer class="disaster-precaution-container__footer" v-if="operate">
      <el-button @click="router.back()">取消</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </footer>
    <UploadLoading :form-loading="formLoading" v-if="formLoading" />
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, defineAsyncComponent } from 'vue';
  import UploadLoading from '@/components/UploadLoading.vue';
  import { useRoute, useRouter } from 'vue-router';
  import BackIcon from 'assets/svg/back.svg';
  import { ElMessage } from 'element-plus';
  import type { DefenseNoticeRuleForm } from './src/type';
  import { uploadFileApi, UPLOAD_BIZ_TYPE } from '@/api/minio';
  import type { FileItem } from '@/views/disaster/types';
  import { createDefenseNoticeItem, editDefenseNoticeItem } from '@/api/disaster-warning/index';
  const router = useRouter();
  const route = useRoute();
  const operate = route.query.operate;
  const id = route.query.id;
  const headerTitle = computed(() => {
    const fixedTitle = '灾害防御通知';
    if (operate === 'create') {
      return `创建${fixedTitle}`;
    } else if (operate === 'edit') {
      return `编辑${fixedTitle}`;
    }
    return `查看${fixedTitle}`;
  });
  const dynamicComponent = computed(() => {
    if (operate === 'create') {
      return defineAsyncComponent(() => import('./src/components/CreateDefenseNoticeItem.vue'));
    } else if (operate === 'edit') {
      return defineAsyncComponent(() => import('./src/components/EditDefenseNoticeItem.vue'));
    } else {
      return defineAsyncComponent(() => import('./src/components/ViewDefenseNoticeItem.vue'));
    }
  });
  const dynamicComponentRef = ref();
  const formLoading = ref(false);
  const formatAttachmentList = 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 createDefenseNoticeItemFunc = async (formData: DefenseNoticeRuleForm) => {
    const attachmentListRes: FileItem[] = await Promise.all(
      formData.attachmentListRes.map((item) => formatAttachmentList(item)),
    );
    const createParam = {
      disasterType: formData.disasterType,
      disasterLevel: formData.disasterLevel,
      title: formData.title,
      content: formData.content,
      attachmentListRes,
      isPush: formData.isPush,
      userGroupList: formData.isPush ? formData.userGroupList : [],
    };
    await createDefenseNoticeItem(createParam);
  };
  const editDefenseNoticeItemFunc = async (formData: DefenseNoticeRuleForm) => {
    const attachmentListRes: FileItem[] = await Promise.all(
      formData.attachmentListRes.map((item) => formatAttachmentList(item)),
    );
    const editParam = {
      id: Number(id),
      disasterType: formData.disasterType,
      disasterLevel: formData.disasterLevel,
      title: formData.title,
      content: formData.content,
      attachmentListRes,
      isPush: formData.isPush,
      userGroupList: formData.isPush ? formData.userGroupList : [],
    };
    await editDefenseNoticeItem(editParam);
  };
  const submit = async () => {
    if (!dynamicComponentRef.value) return;
    const res = await dynamicComponentRef.value.handleValidate();
    if (!res) return;
    formLoading.value = true;
    const formData = dynamicComponentRef.value.getFormData();
    let message;
    try {
      if (operate === 'create') {
        await createDefenseNoticeItemFunc(formData);
        message = '创建成功';
      } else if (operate === 'edit') {
        await editDefenseNoticeItemFunc(formData);
        message = '编辑成功';
      }
      ElMessage.success(message);
      router.back();
    } finally {
      formLoading.value = false;
    }
  };
</script>

<style lang="scss" scoped>
  @use '../style/disaster.scss' as *;
  @use './src/common.scss' as *;
</style>
