<template>
  <main class="safety-platform-container__main">
    <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="formRules" :formConfig="ruleFormConfig">
      <template #images>
        <UploadImages
          :maxCount="9"
          ref="uploadImagesRef"
          :image-list="imageList"
          @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 { updateAccessRecord, getAccessRecordDetail } from '@/api/security-confidentiality-access';
  import type { AccessDetailResponse, CreateAccessRuleForm, UpdateAccessQuery } from '../types';
  import { ACCESS_FORM_CONFIG, ACCESS_FORM_DATA, ACCESS_FORM_RULES } from '../configs/form';
  import { formatImageList, unformatImage } from '@/components/UploadImages/utils';

  const props = defineProps<{
    id: number;
  }>();

  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 imageList = ref<string[]>([]);

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

  const getDetail = async () => {
    const res: AccessDetailResponse = await getAccessRecordDetail(props.id);
    if (!res) return;
    ruleFormData.eventDescription = res.eventDescription;
    ruleFormData.eventLocation = res.eventLocation;
    ruleFormData.eventTime = res.eventTime;
    ruleFormData.remark = res.remark;
    ruleFormData.createdByName = res.createdByName;
    ruleFormData.images = unformatImage(res.images)?.map((x) => {
      return { url: x };
    });

    imageList.value = ruleFormData.images?.map((x) => x.url)!;
    cloneRuleFormData();
  };

  const getFormData = async () => {
    cloneRuleFormData();
    const res: UpdateAccessQuery = {
      id: props.id,
      ...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 updateAccessRecord(params);
      ElMessage.success('创建成功');
      router.back();
    } catch (e) {
      console.log(e);
    } finally {
      formLoading.value = false;
    }
  };
  const handleUploadChange = () => {
    ruleFormData.images = uploadImagesRef.value!.getUploadedImages();
  };

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

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