<template>
  <div class="disaster-control-container">
    <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="formRules" :formConfig="ruleFormConfig">
      <template #userGroupList>
        <GroupSelect v-model="ruleFormData.userGroupList" :groupOptions="groupOptions" />
      </template>
      <template #isPush>
        <el-radio-group v-model="ruleFormData.isPush">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </template>
    </BasicForm>
  </div>
</template>

<script setup lang="ts">
  import { useRoute } from 'vue-router';
  import { onMounted, ref } from 'vue';
  import BasicForm from '@/components/BasicForm.vue';
  import GroupSelect from '@/components/PersonGroup/components/GroupSelect.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { useGroupInfoHook } from '@/components/PersonGroup/hook/groupInfo';
  import type { DisposalManagementRuleFormEdit } from '@/types/disaster-control';
  import { getDisasterControlTableData } from '@/api/disaster-control';
  import {
    DISPOSAL_MANAGEMENT_ITEM_FROM_CONFIG_EDIT,
    DISPOSAL_MANAGEMENT_TASK_FROM_DATA_EDIT,
    DISPOSAL_MANAGEMENT_ITEM_FROM_RULES_EDIT,
  } from '../config';

  const route = useRoute();
  const id = Number(route.params.id);
  const reportTaskId = Number(route.query.reportTaskId);
  const basicFormRef = ref<InstanceType<typeof BasicForm>>();

  const { ruleFormConfig, ruleFormData, formRules, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook<DisposalManagementRuleFormEdit>(
      DISPOSAL_MANAGEMENT_ITEM_FROM_CONFIG_EDIT,
      DISPOSAL_MANAGEMENT_TASK_FROM_DATA_EDIT,
      DISPOSAL_MANAGEMENT_ITEM_FROM_RULES_EDIT,
    );
  const { getUserGroupList, groupOptions } = useGroupInfoHook();

  const handleValidate = async () => {
    if (!basicFormRef.value) return;
    const parentValidateResult = await basicFormRef.value.validateForm();
    return parentValidateResult;
  };
  const getFormData = () => {
    cloneRuleFormData();
    return ruleFormData;
  };
  defineExpose({
    handleValidate,
    getFormData,
  });
  const getFormDetail = async () => {
    const res = await getDisasterControlTableData({ handleTaskIds: [id] });
    const taskItem = res[0].disasterReportTaskInfoList.find((tableItem) => tableItem.id === reportTaskId);
    if (!taskItem) return;
    for (const key in ruleFormData) {
      if (key in taskItem) {
        ruleFormData[key] = taskItem[key];
        ruleFormData.userGroupList = JSON.parse(taskItem.userGroupList) || [];
      }
    }
    cloneRuleFormData();
  };
  onMounted(() => {
    getFormDetail();
    getUserGroupList();
    beforeRouteLeave();
  });
</script>

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