<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import BusinessFormDialog from '@/components/custom/business-form-dialog.vue';
import type { WorklogChangedPayload } from '../shared';
import TaskWorklogContent from './task-worklog-content.vue';

defineOptions({ name: 'ProjectExecutionTaskWorklogDialog' });

interface Props {
  task: Api.Project.ProjectTask | null;
}

interface Emits {
  (e: 'changed', payload: WorklogChangedPayload): void;
  (e: 'closedAfterChange'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const changedDuringOpen = ref(false);

const dialogTitle = computed(() => (props.task ? `工作日志 - ${props.task.taskTitle}` : '工作日志'));

function handleChanged(payload: WorklogChangedPayload) {
  changedDuringOpen.value = true;
  emit('changed', payload);
}

function handleClosed() {
  if (!changedDuringOpen.value) {
    return;
  }

  changedDuringOpen.value = false;
  emit('closedAfterChange');
}

watch(visible, value => {
  if (value) {
    changedDuringOpen.value = false;
  }
});
</script>

<template>
  <BusinessFormDialog
    v-model="visible"
    :title="dialogTitle"
    preset="xl"
    :show-footer="false"
    :scrollbar="false"
    @closed="handleClosed"
  >
    <TaskWorklogContent :task="task" :active="visible" @changed="handleChanged" />
  </BusinessFormDialog>
</template>
