<script setup lang="ts">
import { computed, ref, onMounted, onUnmounted } from 'vue'
import FormBuilderComponent from '@/core/features/form_builder/FormBuilder.vue'
import { useMessage } from 'naive-ui'

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

// FormBuilder ref
const formBuilderRef = ref<InstanceType<typeof FormBuilderComponent> | null>(null)

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

// 检查是否是form_builder字段
const isFormBuilder = computed(() => props.df.fieldname === 'form_builder')

// Customize Form mode: dynamic based on current entity
const isCustomizeFormMode = computed(() => props.ctx?.entity === 'Customize Form')

// Form builder configuration
// In Customize Form mode, use pg_type as the target pagetype; otherwise use record name
const pagetypeName = computed(() => {
  if (isCustomizeFormMode.value && props.record?.pg_type) {
    return props.record.pg_type
  }
  return props.record?.name || ''
})
const fields = computed(() => {
  if (!isFormBuilder.value) return []
  
  // 从record中获取fields数据
  try {
    const fieldsData = props.record?.fields
    if (typeof fieldsData === 'string') {
      return JSON.parse(fieldsData)
    }
    return Array.isArray(fieldsData) ? fieldsData : []
  } catch (e) {
    console.error('Failed to parse fields:', e)
    return []
  }
})

// 获取最新的 fields（供父组件调用）
function getLatestFields() {
  if (formBuilderRef.value) {
    return formBuilderRef.value.getFields()
  }
  return null
}

// 同步 fields 到 record（在保存前调用）
function syncFieldsToRecord() {
  if (!isFormBuilder.value || !props.canEdit) return
  
  const latestFields = getLatestFields()
  if (latestFields && props.record) {
    try {
      props.record.fields = latestFields
    } catch (e) {
      console.error('[HTML.vue] Failed to sync fields:', e)
    }
  }
}

// 监听全局保存事件
function handleSyncEvent() {
  syncFieldsToRecord()
}

onMounted(() => {
  window.addEventListener('sync-form-builder-fields', handleSyncEvent)
})

onUnmounted(() => {
  window.removeEventListener('sync-form-builder-fields', handleSyncEvent)
})

// Handle field updates from form builder
function handleFieldsUpdate(newFields: any[]) {
  if (props.canEdit && isFormBuilder.value) {
    // 更新record中的fields字段
    try {
      const fieldsJson = JSON.stringify(newFields)
      if (props.record) {
        props.record.fields = fieldsJson
      }
    } catch (e) {
      console.error('Failed to update fields:', e)
    }
  }
}

// Handle save event
function handleSave(newFields: any[]) {
  handleFieldsUpdate(newFields)
  if (props.ctx?.t) {
    message.success(props.ctx.t('Fields updated'))
  }
}

// Handle dirty state change
function handleDirtyChange(isDirty: boolean) {
  // 不在这里同步 fields，避免触发组件重新渲染导致输入失焦
  // fields 只在保存时同步
}

// Expose methods to parent
defineExpose({
  getLatestFields
})
</script>

<template>
  <!-- 如果是form_builder字段，渲染Form Builder组件 -->
  <div v-if="isFormBuilder" class="form-builder-field">
    <FormBuilderComponent
      ref="formBuilderRef"
      :fields="fields"
      :pagetype="pagetypeName"
      :pagetype-record="record"
      :readOnly="!canEdit"
      :isCustomizeForm="isCustomizeFormMode"
      @update:fields="handleFieldsUpdate"
      @save="handleSave"
      @dirty-change="handleDirtyChange"
    />
  </div>
  
  <!-- 否则渲染普通HTML内容 -->
  <div v-else :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="html-content" v-html="record[df.fieldname]"></div>
  </div>
</template>

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

.form-builder-field {
  min-height: 600px;
  max-height: calc(100vh - 300px);
  width: 100%;
  margin: 16px 0;
  overflow: auto;
  border: 1px solid #e0e0e6;
  border-radius: 6px;
  background: #fafafa;
}

/* 确保FormBuilder组件内部也支持滚动 */
.form-builder-field :deep(.form-builder-container) {
  height: 100%;
  overflow: visible;
}
</style>


