<template>
  <a-modal
    v-model:visible="visible"
    title-align="start"
    :width="800"
    :footer="false"
    top="10vh"
    :align-center="false"
    @before-open="modalBeforeOpen"
  >
    <template #title> {{ title }} </template>

    <a-tabs
      v-if="isEdit"
      v-model:activeKey="compType"
      type="card-gutter"
      hide-content
    >
      <a-tab-pane key="rule" title="基础规则"> </a-tab-pane>
      <a-tab-pane key="time" title="预约时段"> </a-tab-pane>
      <a-tab-pane key="notice" title="考试说明"> </a-tab-pane>
    </a-tabs>

    <component
      :is="formComp"
      v-if="visible && taskData"
      :row-data="taskData"
      @cancel="close"
      @modified="modifiedHandle"
    ></component>
  </a-modal>
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue';
  import useModal from '@/hooks/modal';
  import { TaskItem, TaskItemDetail } from '@/api/types/order';
  import { taskDetailInfo } from '@/api/order';

  import ruleForm from './ruleForm.vue';
  import timeForm from './timeForm.vue';
  import noticeForm from './noticeForm.vue';

  defineOptions({
    name: 'ModifyTask',
  });

  /* modal */
  const { visible, open, close } = useModal();
  defineExpose({ open, close });

  const props = defineProps<{
    rowData: TaskItem;
  }>();
  const emit = defineEmits(['modified']);

  const isEdit = computed(() => !!props.rowData.id);
  const title = computed(() => `${isEdit.value ? '编辑' : '新增'}任务`);

  const comps = {
    rule: ruleForm,
    time: timeForm,
    notice: noticeForm,
  };
  type CompNameType = keyof typeof comps;
  const compType = ref<CompNameType>('rule');
  const formComp = computed(() => comps[compType.value]);

  const taskData = ref<TaskItemDetail | null>(null);
  async function getDetail() {
    taskData.value = await taskDetailInfo(props.rowData.id);
  }

  function modifiedHandle() {
    if (props.rowData.id) getDetail();
    emit('modified');
    if (isEdit.value) return;
    close();
  }

  async function modalBeforeOpen() {
    if (props.rowData.id) {
      taskData.value = null;
      await getDetail();
    } else {
      taskData.value = {} as TaskItemDetail;
    }
    compType.value = 'rule';
  }
</script>
