<script setup lang="ts">
import { ref, computed } from 'vue'
import { uploadFileToJingrow } from '@/shared/api/common'

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

const inputRef = ref<HTMLInputElement | null>(null)
const hovering = ref(false)
const imgUrl = computed(() => String(props.record?.[props.df.fieldname] || ''))

// Label布局：上下结构(vertical) 或 左右结构(horizontal)
const labelLayout = computed(() => props.df.label_layout || 'vertical')

function choose() {
  if (!props.canEdit) return
  inputRef.value?.click()
}

async function onChange(e: Event) {
  const el = e.target as HTMLInputElement
  const file = el.files?.[0]
  if (!file) return
  try {
    const pagetype = (props.ctx?.entity && (props.ctx?.entity.value ?? props.ctx?.entity))
      || (props.record as any)?.pagetype
      || ''
    const docname = (props.ctx?.id && (props.ctx?.id.value ?? props.ctx?.id))
      || (props.record as any)?.name
      || ''
    const fieldname = props.df?.fieldname

    const oldValue = (props.record as any)?.[fieldname]
    console.debug('[AttachImage] upload params', { pagetype, docname, fieldname, file: file.name, oldValue })

    const res = await uploadFileToJingrow(file, pagetype, docname, fieldname)
    console.debug('[AttachImage] upload result', res)
    if (res.success) {
      console.debug('[AttachImage] server returned', { file_url: res.file_url, file_name: res.file_name, local_path: (res as any).local_path })
      if (res.file_url) {
        ;(props.record as any)[fieldname] = res.file_url
        console.debug('[AttachImage] set field value locally', { fieldname, value: res.file_url })
        try {
          if (typeof props.ctx?.save === 'function') {
            await props.ctx.save()
            console.debug('[AttachImage] auto save triggered')
          }
        } catch (err) {
          console.warn('[AttachImage] auto save failed', err)
        }
      }

    } else {
      alert(res.error || '上传失败')
      console.warn('[AttachImage] upload failed', res)
    }
  } catch (_e) {
    alert('上传失败')
    console.error('[AttachImage] upload error', _e)
  } finally {
    if (el) el.value = ''
  }
}

function clearValue() {
  if (!props.canEdit) return
  ;(props.record as any)[props.df.fieldname] = ''
}
</script>

<template>
  <div :class="['field-wrapper', `layout-${labelLayout}`]">
    <label class="field-label">
      {{ ctx.t(df.label || df.fieldname) }}
      <span v-if="df.reqd" class="required">*</span>
    </label>
    <div class="attach-image-container">
      <template v-if="imgUrl">
        <div class="attach-line">
          <span class="link-icon"><i class="fa-solid fa-link"></i></span>
          <span class="file-link-wrap">
            <a class="file-link" :title="imgUrl" href="javascript:void(0)" @mouseenter="hovering = true" @mouseleave="hovering = false">{{ imgUrl }}</a>
          </span>
          <div class="actions" v-if="canEdit">
            <button class="action" type="button" @click="clearValue">{{ ctx.t ? ctx.t('Clear') : 'Clear' }}</button>
          </div>
          <div v-if="hovering" class="preview-popover">
            <img :src="imgUrl" alt="preview" />
          </div>
        </div>
      </template>
      <template v-else>
        <div class="actions actions-left" v-if="canEdit">
          <button class="action" type="button" @click="choose">{{ ctx.t ? ctx.t('Upload') : 'Upload' }}</button>
        </div>
        <span v-else class="field-value">—</span>
      </template>
      <input ref="inputRef" type="file" accept="image/*" style="display:none" @change="onChange" />
    </div>
  </div>
</template>

<style scoped>
.field-wrapper :deep(.attach-image-container) {
  flex: 1;
}

.attach-image-container { position: relative; width: 100%; }
.attach-line { display: flex; align-items: center; gap: 8px; position: relative; width: 100%; }
.link-icon { opacity: .5; color: inherit; display: inline-flex; align-items: center; }
.file-link-wrap { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.file-link { color: inherit; text-decoration: none; display: inline-block; }
.file-link:hover { text-decoration: underline; }
.actions { margin-left: auto; display: inline-flex; gap: 12px; }
.actions-left { margin-left: 0; }
.action { background: transparent; border: none; padding: 2px 6px; color: inherit; cursor: pointer; font-size: 13px; border-radius: 6px; line-height: 1.4; }
.action:hover { text-decoration: underline; background: #f2f3f5; }
.preview-popover { position: absolute; bottom: calc(100% + 8px); left: 0; background: #fff; border: 1px solid #e5e7eb; border-radius: 10px; padding: 8px; box-shadow: 0 8px 24px rgba(0,0,0,.12); z-index: 20; }
.preview-popover img { width: 160px; height: 160px; object-fit: contain; border-radius: 8px; display: block; }
</style>


