<template>
  <div>
    <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="formRules" :formConfig="ruleFormConfig">
      <template #drillImage>
        <UploadImages
          v-if="!uploadImgDisabled"
          :maxCount="9"
          ref="uploadImagesRef"
          :image-list="recordImageList"
          @upload-success="handleUploadChange"
        />
        <ShowImages style="min-height: 100px" v-else :image-list="recordImageList" />
      </template>
    </BasicForm>
  </div>
  <DrillApprovalDialog
    v-if="approvalInfo"
    ref="drillApprovalDialogRef"
    :approval-data="approvalInfo"
    @filled="handleSubmitRecord"
  />
</template>

<script setup lang="ts">
  import BasicForm from '@/components/BasicForm.vue';
  import UploadImages from '@/views/disaster/disaster-control/src/components/UploadImages.vue';
  import ShowImages from './ShowImages.vue';
  import DrillApprovalDialog from './DrillApprovalDialog.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { DRILL_RECORD_FORM_CONFIG, DRILL_RECORD_FORM_RULES, DRILL_RECORD_FORM_DATA } from '../configs/plan/form';
  import { DrillApprovalItem, DrillApprovalRuleForm, DrillPlanRecord, DrillRecordRuleForm } from '../types';
  import { computed, onMounted, ref, watch } from 'vue';
  import { queryDrillApproval } from '@/api/emergency-drill/emergency-drill';
  import { useRoute } from 'vue-router';

  const props = defineProps<{
    disabled: boolean;
    drillRecord?: DrillPlanRecord | null;
  }>();

  const emits = defineEmits<{
    (e: 'submitDrillRecord', data: DrillRecordRuleForm): void;
  }>();

  const route = useRoute();
  const uploadImagesRef = ref<InstanceType<typeof UploadImages>>();
  const handleUploadChange = (val) => {
    // console.log('files', val);
    // console.log('files', uploadImagesRef.value!.getUploadedImages());
    ruleFormData.drillImagesFile = uploadImagesRef.value!.getUploadedImages();
  };

  const approvalInfo = ref();

  async function getApprovalInfo() {
    const planId = Number(route.query.planId);
    const approvalId = Number(route.query.approvalId);
    try {
      approvalInfo.value = await queryDrillApproval(approvalId, planId);
      // console.log(approvalInfo.value);
    } catch (e) {
      console.log(e);
    }
  }

  onMounted(async () => {
    getApprovalInfo();
  });

  // 表单
  const basicFormRef = ref<typeof BasicForm>();

  const { ruleFormConfig, ruleFormData, formRules, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook<DrillRecordRuleForm>(
      DRILL_RECORD_FORM_CONFIG,
      props.drillRecord
        ? {
            drillPlanId: props.drillRecord.drillPlanId,
            participants: props.drillRecord.participants,
            drillDescription: props.drillRecord.drillDescription,
            drillImage: props.drillRecord.drillImage,
            drillEffectAssess: props.drillRecord.drillEffectAssess,
          }
        : DRILL_RECORD_FORM_DATA,
      DRILL_RECORD_FORM_RULES,
    );

  const formValidate = async () => {
    if (!basicFormRef.value) return;
    const validateResult = await basicFormRef.value.validateForm();
    return validateResult;
  };

  const formClearValidate = () => {
    if (!basicFormRef.value) return;
    basicFormRef.value.clearValidate();
  };

  function getFormData() {
    return ruleFormData;
  }

  const uploadImgDisabled = ref(false);

  watch(
    () => props.disabled,
    (val) => {
      uploadImgDisabled.value = val;
      ruleFormConfig.value.forEach((x) => {
        if (x.componentProps) x.componentProps.disabled = val;
      });
    },
    {
      immediate: true,
    },
  );

  const recordImageList = computed(() => {
    if (!ruleFormData.drillImage) return [];
    // return '';
    return JSON.parse(ruleFormData.drillImage);
  });

  // 弹窗
  const drillApprovalDialogRef = ref();

  function openApprovalDialog() {
    drillApprovalDialogRef.value.openDialog();
  }

  function closeApprovalDialog() {
    drillApprovalDialogRef.value.closeDialog();
  }

  function handleSubmitRecord(approverData: DrillApprovalRuleForm) {
    ruleFormData.approvalDescription = approverData.approvalDescription;
    ruleFormData.approvalInfoList = approverData.approverListInfo.map((x) => {
      return {
        approvalOrder: x.approvalOrder,
        approverIdList:
          '[' + (x.approverType === 1 ? x.approverList.map((x) => x.id).join(',') : x.approverIds?.join(',')) + ']',
      };
    });
    emits('submitDrillRecord', ruleFormData);
  }

  defineExpose({
    formValidate,
    formClearValidate,
    getFormData,
    openApprovalDialog,
    closeApprovalDialog,
  });
</script>

<style scoped></style>
