<script setup lang="ts">
import { reactive, watch, ref, computed } from 'vue'
import { useUpload, pdfFileToImageFiles } from '@/components/UploadFile/src/useUpload'

const message = useMessage()

const props = withDefaults(defineProps<{
  isTextMode?: boolean
  modelValue?: { images?: string[] }
  title?: string
  description?: string
  elderId?: string | number
  elderName?: string
  funName?: string
}>(), {
  isTextMode: false,
  modelValue: () => ({}),
  title: '',
  description: '',
  elderId: '',
  elderName: '',
  funName: '附件'
})

const emit = defineEmits<{
  (e: 'update:modelValue', val: { images?: string[] }): void
}>()

const form = reactive<{ images: string[] }>({
  images: []
})

watch(
  () => props.modelValue,
  (val) => {
    if (!val) return
    if (Array.isArray(val.images)) {
      form.images = [...val.images]
    } else {
      form.images = []
    }
  },
  { immediate: true, deep: true }
)

const updateForm = () => {
  emit('update:modelValue', {
    images: form.images ? [...form.images] : []
  })
}

const { httpRequest: uploadFn } = useUpload(props.funName, { elderId: props.elderId, elderName: props.elderName })

const uploadingCount = ref(0)
const uploading = computed(() => uploadingCount.value > 0)

const uploadSingleFile = (file: File) => {
  uploadingCount.value++
  return uploadFn({ file } as any)
    .then((res: any) => {
      if (res.code === 0) {
        form.images.push(res.data)
        updateForm()
      }
    })
    .finally(() => {
      uploadingCount.value--
    })
}

const handleFileChange = async (e: Event) => {
  const target = e.target as HTMLInputElement
  const files = target.files
  if (!files || files.length === 0) return

  for (let i = 0; i < files.length; i++) {
    const file = files[i]
    if (file.type === 'application/pdf') {
      try {
        const imageFiles = await pdfFileToImageFiles(file)
        for (const imgFile of imageFiles) {
          await uploadSingleFile(imgFile)
        }
      } catch (error) {
        console.error('PDF 解析失败', error)
        message.error(`PDF 解析失败：${file.name}`)
      }
    } else {
      await uploadSingleFile(file)
    }
  }

  target.value = ''
}

const removeImage = (index: number) => {
  form.images.splice(index, 1)
  updateForm()
}

const fileInputRef = ref<HTMLInputElement | null>(null)
const triggerUpload = () => {
  fileInputRef.value?.click()
}

defineExpose({ form })
</script>

<template>
  <div class="document-attachment-body">
    <div v-if="title" class="doc-title">{{ title }}</div>
    <p v-if="description" class="doc-desc">{{ description }}</p>

    <!-- 编辑模式：上传区域 -->
    <div v-if="!isTextMode" class="edit-section">
      <div class="upload-box" @click="triggerUpload">
        <div class="upload-placeholder">
          <span class="upload-icon">+</span>
          <span class="upload-text">{{ uploading ? '上传中...' : '点击上传图片或 PDF（支持多张）' }}</span>
        </div>
        <input
          ref="fileInputRef"
          type="file"
          accept="image/*,application/pdf"
          multiple
          style="display: none"
          @change="handleFileChange"
        />
      </div>

      <div v-if="form.images && form.images.length > 0" class="image-list">
        <div v-for="(img, idx) in form.images" :key="idx" class="image-item">
          <img :src="img" class="image-thumb" />
          <button class="remove-btn" @click.stop="removeImage(idx)">×</button>
        </div>
      </div>
    </div>

    <!-- 文本/打印模式：仅展示图片 -->
    <div v-else class="preview-section">
      <div v-if="form.images && form.images.length > 0" class="image-preview-list">
        <img
          v-for="(img, idx) in form.images"
          :key="idx"
          :src="img"
          class="preview-img"
        />
      </div>
      <div v-else class="empty-box">
        <span>（暂无图片）</span>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.document-attachment-body {
  width: 210mm;
  max-width: 100%;
  margin: 0 auto;
  font-family: 'SimSun', 'Microsoft YaHei', serif;
  font-size: 14px;
  color: #333;
  background: #fff;
  padding: 5mm;

  @media print {
    width: 210mm !important;
    padding: 0;
    border: none;
    margin: 0;
    box-sizing: border-box;
  }
}

.doc-title {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 16px;
}

.doc-desc {
  text-indent: 2em;
  margin: 0 0 16px;
  line-height: 1.8;
}

.edit-section {
  .upload-box {
    width: 100%;
    height: 160px;
    border: 2px dashed #ccc;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: border-color 0.2s;
    margin-bottom: 16px;

    &:hover {
      border-color: #409eff;
    }
  }

  .upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #999;

    .upload-icon {
      font-size: 32px;
      line-height: 1;
      margin-bottom: 8px;
    }

    .upload-text {
      font-size: 14px;
    }
  }

  .image-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .image-item {
    position: relative;
    width: 100%;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    overflow: hidden;

    .image-thumb {
      width: 100%;
      display: block;
      object-fit: contain;
    }

    .remove-btn {
      position: absolute;
      top: 8px;
      right: 8px;
      width: 28px;
      height: 28px;
      border: none;
      border-radius: 50%;
      background: rgba(0, 0, 0, 0.5);
      color: #fff;
      font-size: 18px;
      line-height: 1;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;

      &:hover {
        background: rgba(0, 0, 0, 0.7);
      }
    }
  }
}

.preview-section {
  .image-preview-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .preview-img {
    width: 100%;
    display: block;
    object-fit: contain;
    border: 1px solid #333;
    box-sizing: border-box;
  }

  .empty-box {
    width: 100%;
    min-height: 400px;
    border: 1px solid #333;
    padding: 12px;
    box-sizing: border-box;
    color: #999;
  }
}
</style>
