<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';

defineOptions({
  name: 'WorkReportPageDialog',
  inheritAttrs: false
});

interface Props {
  title?: string;
  loading?: boolean;
  showFooter?: boolean;
  approvalMode?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  title: '',
  loading: false,
  showFooter: false,
  approvalMode: false
});

const visible = defineModel<boolean>('visible', { default: false });
const route = useRoute();
const viewportWidth = ref(typeof window === 'undefined' ? 1920 : window.innerWidth);

const emit = defineEmits<{
  (e: 'close'): void;
}>();

const drawerSize = computed(() => (viewportWidth.value >= 2560 ? '60%' : '75%'));

function handleClose() {
  visible.value = false;
}

function syncViewportWidth() {
  viewportWidth.value = window.innerWidth;
}

/** 抽屉关闭动画结束后触发 close 事件 */
function onDrawerClosed() {
  emit('close');
}

const drawerBodyClass = props.approvalMode
  ? 'work-report-page-drawer__body work-report-page-drawer__body--approval'
  : 'work-report-page-drawer__body';

watch(
  () => route.fullPath,
  () => {
    if (visible.value) {
      visible.value = false;
    }
  }
);

onMounted(() => {
  syncViewportWidth();
  window.addEventListener('resize', syncViewportWidth);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', syncViewportWidth);
});
</script>

<template>
  <ElDrawer
    v-model="visible"
    class="work-report-page-drawer"
    :class="{ 'work-report-page-drawer--approval': props.approvalMode }"
    :body-class="drawerBodyClass"
    :title="props.title"
    :size="drawerSize"
    :close-on-click-modal="false"
    append-to-body
    @closed="onDrawerClosed"
  >
    <div v-loading="props.loading" class="work-report-page-drawer__content">
      <slot />
    </div>

    <div v-if="props.showFooter" class="work-report-page-drawer__footer">
      <slot name="footer" :close="handleClose" />
    </div>
  </ElDrawer>
</template>

<style scoped>
:global(.work-report-page-drawer__body) {
  display: flex;
  flex-direction: column;
  min-height: 0;
  padding-bottom: 0;
}

:global(.work-report-page-drawer__body--approval) {
  padding-bottom: 0;
}

.work-report-page-drawer__content {
  display: flex;
  flex-direction: column;
  min-height: 0;
  flex: 1;
}

.work-report-page-drawer__content :deep(.form-page) {
  display: flex;
  flex-direction: column;
  flex: 1 0 auto;
  min-height: 100%;
  box-sizing: border-box;
}

.work-report-page-drawer__footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 12px 20px;
  border-top: 1px solid var(--el-border-color-lighter);
  background: var(--el-bg-color);
}
</style>
