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

const props = defineProps<{ df: any; record: Record<string, any>; canEdit: boolean; ctx: any }>()

const imageLoadError = ref(false)

const imageUrl = computed(() => {
  const pg = props.record
  
  if (pg && props.df.options && pg[props.df.options]) {
    return pg[props.df.options]
  }
  
  return ''
})

const hasImage = computed(() => {
  const url = imageUrl.value
  return Boolean(url && url.trim())
})

const shouldRender = computed(() => {
  return hasImage.value || imageLoadError.value
})

onMounted(() => {
})

function handleImageError(event: Event) {
  const img = event.target as HTMLImageElement
  imageLoadError.value = true
  console.error('[Image] Failed to load image:', img.src)
}

function handleImageLoad() {
  imageLoadError.value = false
}
</script>

<template>
  <div v-if="shouldRender" class="form-field">
    <div class="field-content">
      <div class="image-container">
        <div class="image-body" style="margin-bottom: 10px;">
          <img 
            v-if="hasImage && !imageLoadError" 
            :src="imageUrl" 
            class="img-responsive" 
            alt="Image"
            @error="handleImageError"
            @load="handleImageLoad"
          />
          <div v-else-if="imageLoadError" class="image-error">
            <svg class="icon icon-md" aria-hidden="true">
              <use href="#icon-restriction"></use>
            </svg>
            <div class="error-text">图片加载失败</div>
            <div class="error-url">{{ imageUrl }}</div>
          </div>
        </div>
        <div class="clearfix"></div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.form-field {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.field-content {
  min-height: 32px;
  display: flex;
  align-items: flex-start;
  flex-direction: column;
  width: 100%;
}

.image-container {
  margin: 0;
}

.image-body {
  margin-bottom: 10px;
}

.img-responsive {
  max-width: 100%;
  height: auto;
  display: block;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #dc3545;
  border: 2px dashed #dc3545;
  border-radius: 8px;
  background-color: #f8d7da;
}

.error-text {
  margin-top: 8px;
  font-size: 14px;
  font-weight: 500;
}

.error-url {
  margin-top: 4px;
  font-size: 12px;
  color: #6c757d;
  word-break: break-all;
  text-align: center;
  max-width: 100%;
}

.icon {
  width: 1em;
  height: 1em;
  fill: currentColor;
}

.icon-md {
  font-size: 1.5rem;
}

.clearfix::after {
  content: "";
  display: table;
  clear: both;
}
</style>


