<template>
  <div class="info-container">
    <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="formRules" :formConfig="ruleFormConfig">
      <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 { onMounted, ref } from 'vue';
  import BasicForm from '@/components/BasicForm.vue';
  import SelectGroup from '@/views/disaster/components/SelectGroup.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { WARNING_INFO_FROM_CONFIG, WARNING_INFO_FROM_DATA, WARNING_INFO_FROM_RULES } from '../config';
  import { WarningInfoRuleForm } from '../type';
  import { getWarningInfoDetail } from '@/api/disaster-warning';

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

  const basicFormRef = ref<InstanceType<typeof BasicForm>>();
  const selectGroupRef = ref<InstanceType<typeof SelectGroup>>();

  const { ruleFormConfig, ruleFormData, formRules, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook<WarningInfoRuleForm>(WARNING_INFO_FROM_CONFIG, WARNING_INFO_FROM_DATA, WARNING_INFO_FROM_RULES);

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

  const getWarningInfoDetailData = async () => {
    const res = await getWarningInfoDetail(props.id);
    for (const key in res) {
      if (key in ruleFormData) {
        ruleFormData[key] = res[key as keyof typeof res];
      }
    }
    cloneRuleFormData();
  };

  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(() => {
    getWarningInfoDetailData();
    beforeRouteLeave();
  });
</script>

<style scoped lang="scss">
  @use '@/views/disaster/style/info-container.scss' as *;
  :deep(.el-date-editor) {
    --el-date-editor-width: 100%;
  }
</style>
