<script setup lang="ts">
import { defineAsyncComponent, computed } from 'vue'
import { resolveControlOverride } from '@/core/registry/controlOverride'

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

// 计算最终的编辑权限
// 逻辑：字段可编辑 = 页面可编辑 AND 字段未设置只读
const finalCanEdit = computed(() => {
  // 页面不可编辑，则字段不可编辑
  if (!props.canEdit) {
    return false
  }
  // 页面可编辑，但字段设置为只读
  if (props.df.read_only === 1) {
    return false
  }
  // 页面可编辑且字段未设置只读
  return true
})

function normalize(name: string) {
  return name.replace(/\s+/g, '')
}

const Comp = computed(() => {
  const name = normalize(String(props.df.fieldtype || ''))
  if (!name) return null
  
  // 如果有entity信息，尝试加载pagetype特定的控件覆盖
  const entity = props.ctx?.entity
  if (entity) {
    try {
      return defineAsyncComponent(async () => {
        // 尝试加载pagetype特定的控件覆盖
        const overrideControl = await resolveControlOverride(entity, name)
        if (overrideControl) {
          return overrideControl
        }
        // 如果覆盖控件不存在，回退到默认控件
        return import(`./controls/${name}.vue`)
      })
    } catch (_e) {
      // 如果异步加载失败，回退到默认控件
    }
  }
  
  // 默认控件加载
  try {
    return defineAsyncComponent(() => import(`./controls/${name}.vue`))
  } catch (_e) {
    return null
  }
})
</script>

<template>
  <component
    :is="Comp"
    v-if="Comp"
    :df="df"
    :record="record"
    :can-edit="finalCanEdit"
    :ctx="ctx"
    :modelValue="record[df.fieldname]"
    @update:modelValue="(v: any) => (record[df.fieldname] = v)"
    :disabled="!finalCanEdit"
  />
  <template v-else>
    <span class="field-value">{{ ctx.t('Unsupported field type') }}: {{ df.fieldtype }}</span>
  </template>
</template>

<style scoped>
</style>


