<template>
  <div v-if="recordData !== undefined">
    <DrillPlanRecordForm
      ref="drillPlanRecordFormRef"
      :disabled="disableForm"
      :drill-record="recordData"
      @submit-drill-record="finishSubmitDrillRecord"
    />
  </div>
</template>

<script setup lang="ts">
  import DrillPlanRecordForm from './DrillPlanRecordForm.vue';
  import { onMounted, ref } from 'vue';
  import { useRoute } from 'vue-router';
  import { DrillPlanRecord, DrillRecordRuleForm } from '../types';
  import {
    queryEmergencyDrillRecordInEdit,
    saveEmergencyDrillRecord,
    submitEmergencyDrillRecord,
  } from '@/api/emergency-drill/emergency-drill';
  import { ElMessage } from 'element-plus';
  import { UPLOAD_BIZ_TYPE, uploadFileApi } from '@/api/minio';

  const route = useRoute();
  const id = route.query.planId;
  const recordData = ref<DrillPlanRecord | null>();
  const disableForm = ref(false);

  const emits = defineEmits<{
    (e: 'recordSubmitted'): void;
  }>();

  async function getDrillData() {
    try {
      recordData.value = await queryEmergencyDrillRecordInEdit(Number(id));
      if (recordData.value.approvalStatus != null && recordData.value.approvalStatus !== 2) {
        emits('recordSubmitted');
        disableForm.value = true;
      }
    } catch (e) {
      recordData.value = null;
      console.log(e);
    }
  }

  onMounted(() => {
    getDrillData();
  });

  const drillPlanRecordFormRef = ref();
  async function saveDrillRecord() {
    if (!drillPlanRecordFormRef) return;
    const formData: DrillRecordRuleForm = drillPlanRecordFormRef.value.getFormData();
    formData.drillImage =
      '[' +
      (
        await Promise.all(
          (formData.drillImagesFile || []).map((item) => {
            if (!item.file && item.url) {
              return '"' + item.url + '"';
            } else {
              return formatImageList(item.file!);
            }
          }),
        )
      ).join(',') +
      ']';
    if (!formData.drillPlanId) formData.drillPlanId = Number(id);

    try {
      // console.log(formData);
      await saveEmergencyDrillRecord(formData);
      ElMessage.success('保存成功');
      drillPlanRecordFormRef.value.formClearValidate();
      recordData.value = undefined;
      getDrillData();
    } catch (e) {
      console.log(e);
      ElMessage.error('保存失败');
    }
  }

  async function startSubmitDrillRecord() {
    if (!drillPlanRecordFormRef) return;
    const res = await drillPlanRecordFormRef.value.formValidate();
    if (!res) return;
    drillPlanRecordFormRef.value.openApprovalDialog();
  }

  async function finishSubmitDrillRecord(innerFormData: DrillRecordRuleForm) {
    try {
      innerFormData.drillImage =
        '[' +
        (
          await Promise.all(
            (innerFormData.drillImagesFile || []).map((item) => {
              if (!item.file && item.url) {
                return '"' + item.url + '"';
              } else {
                return formatImageList(item.file!);
              }
            }),
          )
        ).join(',') +
        ']';
      if (!innerFormData.drillPlanId) innerFormData.drillPlanId = Number(id);

      await submitEmergencyDrillRecord(innerFormData);
      ElMessage.success('提交成功');
      drillPlanRecordFormRef.value.formClearValidate();
      drillPlanRecordFormRef.value.closeApprovalDialog();
      recordData.value = undefined;
      getDrillData();
    } catch (e) {
      console.log(e);
      ElMessage.error('提交失败');
    }
  }

  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 + '"';
  };

  function enableEditRecord() {
    disableForm.value = false;
  }

  defineExpose({
    saveDrillRecord,
    startSubmitDrillRecord,
    enableEditRecord,
  });
</script>

<style scoped></style>
