<script setup lang="ts">
import { ref, computed } from 'vue'
import { uploadFileToJingrow, getRecords, deleteAttachment } from '@/shared/api/common'
import FileUploadDialog from '@/views/pagetype/file/FileUploadDialog.vue'

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] || ''))
const showUploadDialog = ref(false)

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

// 当前记录的上下文信息
const currentPagetype = computed(() => 
  (props.ctx?.entity && (props.ctx?.entity.value ?? props.ctx?.entity))
  || (props.record as any)?.pagetype
  || ''
)
const currentPagename = computed(() => 
  (props.ctx?.id && (props.ctx?.id.value ?? props.ctx?.id))
  || (props.record as any)?.name
  || ''
)
const currentPagefield = computed(() => props.df?.fieldname || '')

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 openUploadDialog() {
  if (!props.canEdit) return
  showUploadDialog.value = true
}

// 上传成功回调
async function onUploaded() {
  // 关闭弹窗
  showUploadDialog.value = false
  
  // 获取上传的文件URL
  try {
    const res = await getRecords('File', [
      ['attached_to_pagetype', '=', currentPagetype.value],
      ['attached_to_name', '=', currentPagename.value],
    ], ['file_url'], 'creation desc', 0, 1)
    
    if (res.success && res.data?.length) {
      const latestFile = res.data[0]
      ;(props.record as any)[currentPagefield.value] = latestFile.file_url
      
      // 自动保存（静默，不弹提示）
      try {
        if (typeof props.ctx?.saveSilent === 'function') {
          await props.ctx.saveSilent()
        } else if (typeof props.ctx?.save === 'function') {
          await props.ctx.save()
        }
      } catch (_err) {
        // ignore autosave failures
      }
    }
  } catch (_e) {
    // ignore
  }
}

async function clearValue() {
  if (!props.canEdit) return
  const fieldname = props.df.fieldname
  const fileUrl = (props.record as any)[fieldname]
  if (fileUrl) {
    try {
      const pagetype = (props.ctx?.entity && (props.ctx?.entity.value ?? props.ctx?.entity)) || ''
      const pagename = (props.ctx?.id && (props.ctx?.id.value ?? props.ctx?.id)) || ''
      if (pagetype && pagename) {
        const res = await getRecords('File', [
          ['attached_to_pagetype', '=', pagetype],
          ['attached_to_name', '=', pagename],
          ['file_url', '=', fileUrl],
        ], ['name'])
        if (res.success && res.data?.length) {
          for (const f of res.data) {
            await deleteAttachment(f.name)
          }
        }
      }
    } catch (_err) {
      // ignore file deletion failures
    }
  }
  ;(props.record as any)[fieldname] = ''
  try {
    if (typeof props.ctx?.saveSilent === 'function') {
      props.ctx.saveSilent()
    } else if (typeof props.ctx?.save === 'function') {
      props.ctx.save()
    }
  } catch (_err) {
    // ignore autosave failures
  }
}
</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="openUploadDialog">{{ ctx.t ? ctx.t('Upload') : 'Upload' }}</button>
        </div>
        <span v-else class="field-value">—</span>
      </template>
      
      <!-- 上传对话框 -->
      <FileUploadDialog 
        v-model:show="showUploadDialog"
        :pagetype="currentPagetype"
        :pagename="currentPagename"
        :pagefield="currentPagefield"
        @uploaded="onUploaded"
      />
    </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>
