<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 fileUrl = computed(() => String((props.record as any)?.[props.df.fieldname] || ''))

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

const fileName = computed(() => {
  const url = fileUrl.value
  if (!url) return ''
  try {
    const u = new URL(url, window.location.origin)
    const pathname = u.pathname
    const last = pathname.substring(pathname.lastIndexOf('/') + 1)
    return decodeURIComponent(last || url)
  } catch (_e) {
    const idx = url.lastIndexOf('/')
    return idx >= 0 ? decodeURIComponent(url.substring(idx + 1)) : url
  }
})

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 res = await uploadFileToJingrow(file, pagetype, docname, fieldname)
    if (res.success) {
      if (res.file_url) {
        ;(props.record as any)[fieldname] = res.file_url
        try {
          if (typeof props.ctx?.save === 'function') {
            await props.ctx.save()
          }
        } catch (_err) {
          // ignore autosave failures
        }
      }
    } else {
      alert(res.error || '上传失败')
    }
  } catch (_e) {
    alert('上传失败')
  } 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-container">
      <template v-if="fileUrl">
        <div class="attach-line" @mouseenter="hovering = true" @mouseleave="hovering = false">
          <span class="link-icon"><i class="fa-regular fa-file"></i></span>
          <span class="file-link-wrap">
            <a class="file-link" :title="fileUrl" :href="fileUrl" target="_blank" rel="noopener">{{ fileName || fileUrl }}</a>
          </span>
          <div class="actions" v-if="canEdit">
            <button class="action" type="button" @click="clearValue">{{ ctx.t ? ctx.t('Clear') : 'Clear' }}</button>
          </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" style="display:none" @change="onChange" />
    </div>
  </div>
</template>

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

.attach-container { position: relative; width: 100%; }
.attach-line { display: flex; align-items: center; gap: 8px; position: relative; width: 100%; }
.link-icon { opacity: .6; 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: 1px solid #e5e7eb; padding: 4px 10px; color: inherit; cursor: pointer; font-size: 13px; border-radius: 6px; line-height: 1.4; }
.action:hover { background: #f6f7f9; }
</style>


