<template>
  <div class="info-container">
    <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="formRules" :formConfig="ruleFormConfig">
      <template #noticeAttachment>
        <Upload label="上传附件" @uploadSuccess="handleUploadSuccess" />
      </template>
      <template #isPush>
        <el-radio-group v-model="ruleFormData.isPush">
          <el-radio :value="true">是</el-radio>
          <el-radio :value="false">否</el-radio>
        </el-radio-group>
        <SelectGroup
          v-if="ruleFormData.isPush"
          ref="selectGroupRef"
          :userGroupList="ruleFormData.userGroupList || []"
          @userGroupListChange="handleUserGroupListChange"
        />
      </template>
    </BasicForm>
  </div>
</template>

<script setup lang="ts">
  import BasicForm from '@/components/BasicForm.vue';
  import Upload from '@/views/disaster/components/Upload.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { DEFENSE_NOTICE_FROM_CONFIG, DEFENSE_NOTICE_FROM_DATA, DEFENSE_NOTICE_FROM_RULES } from '../config';
  import { onMounted, ref } from 'vue';
  import { DefenseNoticeRuleForm } from '../type';
  import SelectGroup from '@/views/disaster/components/SelectGroup.vue';
  import type { FileItem } from '@/views/disaster/types';
  const basicFormRef = ref<InstanceType<typeof BasicForm>>();
  const selectGroupRef = ref<InstanceType<typeof SelectGroup>>();

  const { ruleFormConfig, ruleFormData, formRules, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook<DefenseNoticeRuleForm>(
      DEFENSE_NOTICE_FROM_CONFIG,
      DEFENSE_NOTICE_FROM_DATA,
      DEFENSE_NOTICE_FROM_RULES,
    );

  const handleUserGroupListChange = (userGroupList: number[]) => {
    ruleFormData.userGroupList = userGroupList;
  };

  const handleUploadSuccess = (fileList: FileItem[]) => {
    ruleFormData.noticeAttachment = fileList;
    if (!basicFormRef.value) return;
    basicFormRef.value.validateField('noticeAttachment');
  };

  const handleValidate = async () => {
    if (!basicFormRef.value) return;
    const parentValidateResult = await basicFormRef.value.validateForm();
    let childValidateResult = true;
    if (selectGroupRef.value) {
      childValidateResult = (await selectGroupRef.value.validateForm()) as boolean;
    }
    return parentValidateResult && childValidateResult;
  };
  const getFormData = () => {
    if (!ruleFormData.isPush) {
      ruleFormData.userGroupList = [];
    }
    cloneRuleFormData();
    return ruleFormData;
  };
  defineExpose({
    handleValidate,
    getFormData,
  });
  onMounted(() => {
    ruleFormData.createUser = 'XXX';
    cloneRuleFormData();
    beforeRouteLeave();
  });
</script>

<style scoped lang="scss">
  @use '@/views/disaster/style/info-container.scss' as *;
</style>
