<script setup lang="ts">
import { computed } from 'vue'

const props = defineProps<{
  title: string
  attachmentNo: string | number
  selectedData?: any
  isTextMode?: boolean
}>()

const emit = defineEmits<{
  (e: 'select'): void
  (e: 'delete'): void
}>()

const hasData = computed(() => {
  if (!props.selectedData) return false
  if (Array.isArray(props.selectedData)) return props.selectedData.length > 0
  if (typeof props.selectedData === 'object') return Object.keys(props.selectedData).length > 0
  return !!props.selectedData
})
</script>

<template>
  <div class="attachment-page" :class="{ 'is-filled': hasData }">
    <div class="attachment-header">
      <div class="attachment-title">
        附件{{ attachmentNo }}：{{ title }}
      </div>
      <div v-if="!isTextMode" class="attachment-actions">
        <el-button
          type="primary"
          size="small"
          plain
          @click="emit('select')"
        >
          从列表中选择
        </el-button>
        <el-button
          v-if="hasData && !isTextMode"
          type="danger"
          size="small"
          plain
          @click="emit('delete')"
        >
          删除
        </el-button>
      </div>
    </div>

    <div v-if="hasData" class="attachment-content">
      <div class="attachment-body">
        <slot :data="selectedData"></slot>
      </div>
    </div>

    <div v-else class="attachment-empty">
      <el-empty :description="isTextMode ? '' : '请点击上方按钮从列表中选择附件数据'" />
    </div>
  </div>
</template>

<style scoped lang="scss">
.attachment-page {
  width: 210mm;
  min-height: 297mm;
  margin: 4mm auto;
  padding: 10mm 14mm;
  background: #fff;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.12);
  box-sizing: border-box;

  &.is-filled {
    padding: 0;
    background: transparent;
    box-shadow: none;
    min-height: auto;
  }
}

.attachment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 8px;
  border-bottom: 1.5px solid #333;
  margin-bottom: 16px;
}

.attachment-title {
  font-size: 18px;
  font-weight: bold;
  color: #222;
}

.attachment-actions {
  display: flex;
  gap: 8px;
}

.attachment-content {
  font-size: 14px;
  line-height: 1.9;
  color: #333;
}

.attachment-body {
  padding: 4px 0;
}

.attachment-empty {
  margin-top: 40px;
}

@media print {
  .attachment-page {
    width: 100% !important;
    min-height: auto !important;
    height: auto !important;
    margin: 0 !important;
    padding: 10mm 0mm !important;
    box-shadow: none !important;
    box-sizing: border-box !important;
    page-break-after: always;
    break-after: page;
  }

  /* 保留内边距，避免内容溢出可打印区域；不要在这里清 0 */
  .attachment-page.is-filled {
    background: transparent !important;
    box-shadow: none !important;
  }

  .attachment-page:last-child {
    page-break-after: auto;
    break-after: auto;
  }
}
</style>
