<template>
  <div class="disaster-warning-container">
    <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="formRules" :formConfig="ruleFormConfig">
      <template #disasterType>
        <el-select v-model="ruleFormData.disasterType" placeholder="请选择预警类型" filterable>
          <el-option
            v-for="item in warningTypeDice"
            :key="item.itemCode"
            :label="item.itemValue"
            :value="item.itemCode"
          />
        </el-select>
      </template>
      <template #disasterLevel>
        <el-select v-model="ruleFormData.disasterLevel" placeholder="请选择灾害等级">
          <el-option
            v-for="item in disasterLevelDice"
            :key="item.itemCode"
            :label="item.itemValue"
            :value="item.itemCode"
          />
        </el-select>
      </template>
      <template #isEmergency>
        <el-radio-group v-model="ruleFormData.isEmergency">
          <el-radio :value="IS_EMERGENCY.EMERGENCY">是</el-radio>
          <el-radio :value="IS_EMERGENCY.NOT_EMERGENCY">否</el-radio>
        </el-radio-group>
      </template>
      <template #eventType>
        <el-select v-model="ruleFormData.eventType" placeholder="请选择应急事件类型" filterable>
          <el-option
            v-for="item in emergencyEventDice"
            :key="item.itemCode"
            :label="item.itemValue"
            :value="item.itemValue"
          />
        </el-select>
      </template>
      <template #isPush>
        <el-radio-group v-model="ruleFormData.isPush">
          <el-radio :value="IS_PUSH.PUSH">是</el-radio>
          <el-radio :value="IS_PUSH.NOT_PUSH">否</el-radio>
        </el-radio-group>
        <SelectGroup
          v-if="ruleFormData.isPush"
          ref="selectGroupRef"
          :user-group-list="ruleFormData.userGroupList || []"
          @user-group-list-change="handleUserGroupListChange"
        />
      </template>
    </BasicForm>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, ref, watch } from 'vue';
  import BasicForm from '@/components/BasicForm.vue';
  import SelectGroup from '@/components/PersonGroup/SelectGroup.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { useUserInfoHook } from '@/views/disaster/hooks';
  import { useDisasterWarningHook } from '../hook';
  import { useEmergencyProcedureHook } from '@/views/emergency/emergency-procedure/hooks';
  import type { WarningInfoRuleForm } from '../type';
  import { WARNING_INFO_FROM_CONFIG, WARNING_INFO_FROM_DATA, WARNING_INFO_FROM_RULES } from '../config';
  import { IS_PUSH, IS_EMERGENCY } from '@/views/disaster/constant';

  const { realname } = useUserInfoHook();
  const basicFormRef = ref<InstanceType<typeof BasicForm>>();
  const selectGroupRef = ref<InstanceType<typeof SelectGroup>>();

  const { warningTypeDice, disasterLevelDice, getWarningInfoDict, getDisasterLevelDict } = useDisasterWarningHook();
  const { emergencyEventDice, getEmergencyEventDict } = useEmergencyProcedureHook();

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

  // 应急事件类型配置
  const EVENT_TYPE_PROP = 'eventType';
  const initialFormConfig = [...ruleFormConfig.value];
  const eventTypeIndex = initialFormConfig.findIndex((item) => item.prop === EVENT_TYPE_PROP);
  const eventTypeConfig = eventTypeIndex > -1 ? initialFormConfig[eventTypeIndex] : null;
  const eventTypeRules = formRules[EVENT_TYPE_PROP];

  // 如果应急事件未启动，则默认启动应急事件
  if (ruleFormData.isEmergency === undefined || ruleFormData.isEmergency === null) {
    ruleFormData.isEmergency = IS_EMERGENCY.EMERGENCY;
  }

  watch(
    () => ruleFormData.isEmergency,
    (value) => {
      const isEmergencyOpen = value === IS_EMERGENCY.EMERGENCY;

      // 如果应急事件未启动，则清空应急事件类型
      if (!isEmergencyOpen) {
        if (ruleFormData.eventType) {
          ruleFormData.eventType = '';
        }
        // 如果应急事件类型配置存在，则删除应急事件类型配置
        if (eventTypeConfig && ruleFormConfig.value.some((item) => item.prop === EVENT_TYPE_PROP)) {
          const withoutEventType = ruleFormConfig.value.filter((item) => item.prop !== EVENT_TYPE_PROP);
          ruleFormConfig.value = withoutEventType;
        }
        // 如果应急事件类型规则存在，则删除应急事件类型规则
        if (formRules[EVENT_TYPE_PROP]) {
          delete formRules[EVENT_TYPE_PROP];
        }
        return;
      }

      // 如果应急事件已启动，则添加应急事件类型配置
      if (eventTypeConfig && !ruleFormConfig.value.some((item) => item.prop === EVENT_TYPE_PROP)) {
        const newConfig = [...ruleFormConfig.value];
        const insertIndex =
          eventTypeIndex > -1 && eventTypeIndex <= newConfig.length ? eventTypeIndex : newConfig.length;
        newConfig.splice(insertIndex, 0, eventTypeConfig);
        ruleFormConfig.value = newConfig;
      }

      if (eventTypeRules) {
        formRules[EVENT_TYPE_PROP] = eventTypeRules;
      }
    },
    { immediate: true },
  );

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

  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 = [];
    }
    if (ruleFormData.isEmergency !== IS_EMERGENCY.EMERGENCY) {
      ruleFormData.eventType = '';
    }
    cloneRuleFormData();
    return ruleFormData;
  };
  defineExpose({
    handleValidate,
    getFormData,
  });

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

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