<template>
  <main class="safety-platform-container__main">
    <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="formRules" :formConfig="ruleFormConfig">
      <template #images>
        <UploadImages :maxCount="9" ref="uploadImagesRef" @upload-success="handleUploadChange" />
      </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" />
</template>

<script setup lang="ts">
  import { onMounted, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import BasicForm from '@/components/BasicForm.vue';
  import UploadLoading from '@/components/UploadLoading.vue';
  import UploadImages from '@/components/UploadImages/UploadImages.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { useUserInfoHook } from '@/views/disaster/hooks';
  import { createAccessRecord } from '@/api/security-confidentiality-access';
  import { CreateAccessRuleForm, CreateAccessQuery } from '../types';
  import { ACCESS_FORM_CONFIG, ACCESS_FORM_DATA, ACCESS_FORM_RULES } from '../configs/form';
  import { formatImageList } from '@/components/UploadImages/utils';

  const { realname } = useUserInfoHook();

  const { ruleFormData, formRules, ruleFormConfig, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook<CreateAccessRuleForm>(ACCESS_FORM_CONFIG, ACCESS_FORM_DATA, ACCESS_FORM_RULES);

  const basicFormRef = ref<InstanceType<typeof BasicForm>>();
  const uploadImagesRef = ref<InstanceType<typeof UploadImages>>();
  const handleValidate = async () => {
    if (!basicFormRef.value) return;
    const res = await basicFormRef.value.validateForm();
    return res;
  };

  const getFormData = async () => {
    cloneRuleFormData();
    const res: CreateAccessQuery = {
      ...ruleFormData,
      images: JSON.stringify(await formatImageList(ruleFormData.images)),
    };
    return res;
  };

  const formLoading = ref(false);
  const router = useRouter();
  const handleSubmit = async () => {
    const res = await handleValidate();
    if (!res) return;
    try {
      formLoading.value = true;
      const params = await getFormData();
      await createAccessRecord(params);
      ElMessage.success('创建成功');
      router.back();
    } catch (e) {
      console.log(e);
    } finally {
      formLoading.value = false;
    }
  };
  const handleUploadChange = () => {
    ruleFormData.images = uploadImagesRef.value!.getUploadedImages();
  };

  onMounted(() => {
    ruleFormData.createdByName = realname;
    cloneRuleFormData();
    beforeRouteLeave();
  });
</script>

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