<template>
  <div class="metadata-form">
    <div v-if="loading" class="loading-wrapper">
      <el-skeleton :rows="3" animated />
    </div>
    
    <template v-else>
      <div v-if="allFields.length === 0" class="empty-fields">
        <el-empty description="暂无适用的元数据字段" :image-size="60" />
      </div>
      
      <template v-else>
        <el-row :gutter="16">
          <el-col
            v-for="field in visibleFields"
            :key="field.id"
            :xs="24"
            :sm="12"
            :md="colSpan"
          >
            <MetadataFieldRenderer
              :field="field"
              :model-value="localMetadata[field.field_key]"
              :prop-path="`metadata.${field.field_key}`"
              :disabled="disabled || (field.status === 'deprecated' && !showDeprecatedEditable)"
              :is-new-object="isNewObject"
              @update:model-value="handleFieldUpdate(field.field_key, $event)"
            />
          </el-col>
        </el-row>

        <div v-if="deprecatedFields.length > 0 && showDeprecated" class="deprecated-section">
          <el-divider content-position="left">
            <el-tag type="danger" size="small">已废弃字段</el-tag>
          </el-divider>
          <el-row :gutter="16">
            <el-col
              v-for="field in deprecatedFields"
              :key="field.id"
              :xs="24"
              :sm="12"
              :md="colSpan"
            >
              <MetadataFieldRenderer
                :field="field"
                :model-value="localMetadata[field.field_key]"
                :prop-path="`metadata.${field.field_key}`"
                disabled
                :is-new-object="isNewObject"
                @update:model-value="handleFieldUpdate(field.field_key, $event)"
              />
            </el-col>
          </el-row>
        </div>
      </template>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import MetadataFieldRenderer from './MetadataFieldRenderer.vue'
import { metadataSchemaApi } from '@/api/metadata-schema'
import type { MetadataFieldDefinition, MetadataPayload, MetadataScope } from '@/types/metadata'

const props = withDefaults(defineProps<{
  scope: MetadataScope
  modelValue?: MetadataPayload
  disabled?: boolean
  isNewObject?: boolean
  showDeprecated?: boolean
  showDeprecatedEditable?: boolean
  colSpan?: number
}>(), {
  modelValue: () => ({}),
  disabled: false,
  isNewObject: true,
  showDeprecated: true,
  showDeprecatedEditable: false,
  colSpan: 8
})

const emit = defineEmits<{
  (e: 'update:modelValue', value: MetadataPayload): void
  (e: 'fields-loaded', fields: MetadataFieldDefinition[]): void
}>()

const loading = ref(false)
const allFields = ref<MetadataFieldDefinition[]>([])
const localMetadata = ref<MetadataPayload>({})

const activeFields = computed(() => {
  return allFields.value.filter(f => f.status === 'active')
})

const deprecatedFields = computed(() => {
  return allFields.value.filter(f => f.status === 'deprecated')
})

const visibleFields = computed(() => {
  // Show all fields except deprecated in edit mode, so users can change draft to active
  if (props.isNewObject) {
    return activeFields.value
  }
  return allFields.value.filter(f => f.status !== 'deprecated')
})

const loadFields = async () => {
  loading.value = true
  try {
    const res = await metadataSchemaApi.getByScope(props.scope, props.showDeprecated)
    // Handle both formats: direct array or { items: array }
    allFields.value = Array.isArray(res) ? res : (res.items || [])
    emit('fields-loaded', allFields.value)
    
    applyDefaults()
  } catch (error: any) {
    console.error('加载元数据字段失败', error)
    ElMessage.error('加载元数据字段失败')
  } finally {
    loading.value = false
  }
}

const applyDefaults = () => {
  const defaults: MetadataPayload = {}
  activeFields.value.forEach(field => {
    if (field.default !== undefined && localMetadata.value[field.field_key] === undefined) {
      defaults[field.field_key] = field.default
    }
  })
  if (Object.keys(defaults).length > 0) {
    localMetadata.value = { ...defaults, ...localMetadata.value }
    emit('update:modelValue', { ...localMetadata.value })
  }
}

const handleFieldUpdate = (fieldKey: string, value: string | number | boolean | string[] | undefined) => {
  localMetadata.value[fieldKey] = value
  emit('update:modelValue', { ...localMetadata.value })
}

watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    localMetadata.value = { ...newVal }
  }
}, { immediate: true, deep: true })

watch(() => props.scope, () => {
  loadFields()
})

onMounted(() => {
  loadFields()
})

defineExpose({
  validate: async () => {
    const errors: { field_key: string; message: string }[] = []
    
    activeFields.value.forEach(field => {
      if (field.required) {
        const value = localMetadata.value[field.field_key]
        if (value === undefined || value === null || value === '' || 
            (Array.isArray(value) && value.length === 0)) {
          errors.push({
            field_key: field.field_key,
            message: `${field.label} 为必填项`
          })
        }
      }
      
      if (field.type === 'enum' || field.type === 'array_enum') {
        const value = localMetadata.value[field.field_key]
        if (value !== undefined && value !== null && field.options) {
          if (field.type === 'enum' && !field.options.includes(value as string)) {
            errors.push({
              field_key: field.field_key,
              message: `${field.label} 的值不在有效选项中`
            })
          }
          if (field.type === 'array_enum' && Array.isArray(value)) {
            const invalidValues = value.filter(v => !field.options!.includes(v))
            if (invalidValues.length > 0) {
              errors.push({
                field_key: field.field_key,
                message: `${field.label} 包含无效选项: ${invalidValues.join(', ')}`
              })
            }
          }
        }
      }
    })
    
    return {
      valid: errors.length === 0,
      errors
    }
  },
  getMetadata: () => ({ ...localMetadata.value }),
  getFields: () => allFields.value
})
</script>

<style scoped>
.metadata-form {
  width: 100%;
}

.loading-wrapper {
  padding: 16px;
}

.empty-fields {
  padding: 16px;
  text-align: center;
}

.deprecated-section {
  margin-top: 16px;
  padding: 12px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 6px;
}
</style>
