<template>
  <div class="single-page-detail">
    <!-- 页面头部 -->
    <div class="page-header">
      <n-space justify="space-between" align="center">
        <div>
          <h1 class="page-title">{{ pageTitle }}</h1>
          <p class="page-description">{{ pageDescription }}</p>
        </div>
        <n-space>
          <n-button type="default" @click="goBack" :disabled="loading">
            <template #icon>
              <n-icon><Icon icon="tabler:arrow-left" /></n-icon>
            </template>
            {{ t('Back') }}
          </n-button>
          <n-button type="primary" :disabled="loading" @click="handleSave" v-if="canEdit">
            {{ t('Save') }}
          </n-button>
        </n-space>
      </n-space>
    </div>

    <!-- 表单内容 - 按照 jingrow 方式渲染 -->
    <div class="form-layout">
      <div class="form-page">
        <!-- 标签页 -->
        <div v-if="hasTabs" class="form-tabs-list">
          <ul class="nav form-tabs">
            <li 
              v-for="tab in tabs" 
              :key="tab.key"
              class="nav-item"
              @click="activeTab = tab.key"
            >
              <a 
                :class="['nav-link', { active: activeTab === tab.key }]"
                href="#"
              >
                {{ t(tab.label) }}
              </a>
            </li>
          </ul>
        </div>

        <!-- 标签内容 -->
        <div class="form-tab-content">
          <div 
            v-for="tab in tabs" 
            :key="tab.key"
            :class="['tab-pane', { active: activeTab === tab.key }]"
          >
            <div class="form-sections">
              <!-- 渲染每个 Section -->
              <div v-for="section in getTabSections(tab)" :key="section.key" class="form-section">
                <!-- Section 标题 -->
                <div v-if="section.label && !isStructuralField({ fieldname: section.label, fieldtype: 'Section Break' })" class="section-header">
                  <h4>{{ t(section.label) }}</h4>
                </div>
                
                <!-- Section 内容 -->
                <div class="section-body">
                  <!-- 渲染每个 Column -->
                  <div 
                    v-for="column in section.columns" 
                    :key="column.key" 
                    class="form-column"
                  >
                        <!-- Column 字段 -->
                        <div 
                          v-for="field in column.fields" 
                          :key="field.fieldname" 
                          class="form-field"
                          v-show="shouldShowField(field)"
                        >
                      <div class="field-label">
                        <label>{{ t(field.label || field.fieldname) }}</label>
                        <span v-if="field.reqd" class="required">*</span>
                      </div>
                      <div class="field-content">
                        <!-- 文本类型字段 -->
                        <template v-if="['Data', 'Password', 'Phone', 'Barcode'].includes(field.fieldtype)">
                          <n-input 
                            v-model:value="record[field.fieldname]" 
                            :type="field.fieldtype === 'Password' ? 'password' : 'text'"
                            :placeholder="t(field.fieldname)"
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <!-- Text 类型字段 (10行) -->
                        <template v-else-if="field.fieldtype === 'Text'">
                          <n-input 
                            v-model:value="record[field.fieldname]" 
                            type="textarea"
                            :rows="12"
                            :placeholder="t(field.fieldname)"
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <!-- Small Text 类型字段 (3行) -->
                        <template v-else-if="field.fieldtype === 'Small Text'">
                          <n-input 
                            v-model:value="record[field.fieldname]" 
                            type="textarea"
                            :rows="3"
                            :placeholder="t(field.fieldname)"
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <!-- 只读字段 -->
                        <template v-else-if="field.fieldtype === 'Read Only'">
                          <span class="field-value">{{ formatDisplayValue(record[field.fieldname]) }}</span>
                        </template>
                        
                        <!-- 长文本类型字段 -->
                        <template v-else-if="['Long Text', 'Comment'].includes(field.fieldtype)">
                          <n-input 
                            v-model:value="record[field.fieldname]" 
                            type="textarea"
                            :placeholder="t(field.fieldname)"
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <!-- 选择类型字段 -->
                        <template v-else-if="field.fieldtype === 'Select'">
                          <n-select 
                            v-model:value="record[field.fieldname]" 
                            :options="getSelectOptions(field)"
                            :placeholder="t(field.fieldname)"
                            :disabled="!canEdit"
                            
                          />
                        </template>
                        
                        <!-- 多选类型字段 -->
                        <template v-else-if="['MultiSelect', 'MultiSelect Pills', 'MultiSelect List'].includes(field.fieldtype)">
                          <n-select 
                            v-model:value="record[field.fieldname]" 
                            :options="getSelectOptions(field)"
                            multiple
                            :placeholder="t(field.fieldname)"
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <!-- 数字类型字段 -->
                        <template v-else-if="['Int', 'Float', 'Currency'].includes(field.fieldtype)">
                          <n-input-number 
                            v-model:value="record[field.fieldname]" 
                            :precision="field.fieldtype === 'Float' ? 2 : 0"
                            :placeholder="t(field.fieldname)"
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <!-- 复选框类型字段 -->
                        <template v-else-if="field.fieldtype === 'Check'">
                          <n-checkbox 
                            :checked="!!record[field.fieldname]"
                            @update:checked="(checked) => { record[field.fieldname] = checked ? 1 : 0; }"
                            :disabled="!canEdit"
                          >
                            {{ t(field.label || field.fieldname) }}
                          </n-checkbox>
                        </template>
                        
                        <!-- 多复选框类型字段 -->
                        <template v-else-if="field.fieldtype === 'MultiCheck'">
                          <div class="multicheck-container">
                            <n-checkbox 
                              v-for="option in getSelectOptions(field)"
                              :key="option.value"
                              :checked="getMultiCheckValue(field.fieldname, option.value)"
                              @update:checked="updateMultiCheckValue(field.fieldname, option.value, $event)"
                              :disabled="!canEdit"
                            >
                              {{ option.label }}
                            </n-checkbox>
                          </div>
                        </template>
                        
                        <!-- 日期时间类型字段 -->
                        <template v-else-if="field.fieldtype === 'Date'">
                          <n-date-picker 
                            v-model:value="record[field.fieldname]" 
                            type="date"
                            :placeholder="t(field.fieldname)"
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <template v-else-if="field.fieldtype === 'Time'">
                          <n-time-picker 
                            v-model:value="record[field.fieldname]" 
                            :placeholder="t(field.fieldname)"
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <template v-else-if="field.fieldtype === 'Datetime'">
                          <n-date-picker 
                            v-model:value="record[field.fieldname]" 
                            type="datetime"
                            :placeholder="t(field.fieldname)"
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <template v-else-if="field.fieldtype === 'Date Range'">
                          <n-date-picker 
                            v-model:value="record[field.fieldname]" 
                            type="daterange"
                            :placeholder="t(field.fieldname)"
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <!-- 进度条类型字段 -->
                        <template v-else-if="field.fieldtype === 'Percent'">
                          <n-progress 
                            type="line" 
                            :percentage="Number(record[field.fieldname]) || 0" 
                            :show-indicator="true"
                          />
                        </template>
                        
                        <!-- 评分类型字段 -->
                        <template v-else-if="field.fieldtype === 'Rating'">
                          <n-rate 
                            v-model:value="record[field.fieldname]" 
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <!-- 颜色类型字段 -->
                        <template v-else-if="field.fieldtype === 'Color'">
                          <n-color-picker 
                            v-model:value="record[field.fieldname]" 
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <!-- 代码类型字段 -->
                        <template v-else-if="field.fieldtype === 'Code'">
                          <pre class="json-content">{{ formatJson(record[field.fieldname]) }}</pre>
                        </template>
                        
                        <!-- JSON 类型字段 -->
                        <template v-else-if="field.fieldtype === 'JSON'">
                          <div class="json-field-container">
                            <n-input 
                              :value="getJsonDisplayValue(record[field.fieldname])"
                              @update:value="updateJsonValue(field.fieldname, $event)"
                              type="textarea"
                              :rows="12"
                              :placeholder="t(field.fieldname)"
                              :disabled="!canEdit"
                              class="json-textarea"
                            />
                          </div>
                        </template>
                        
                        <!-- 链接类型字段 -->
                        <template v-else-if="['Link', 'Dynamic Link'].includes(field.fieldtype)">
                          <n-input 
                            v-model:value="record[field.fieldname]" 
                            :placeholder="t(field.fieldname)"
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <!-- 编辑器类型字段 -->
                        <template v-else-if="field.fieldtype === 'Jeditor'">
                          <JeditorControl
                            :df="field"
                            v-model:modelValue="record[field.fieldname]"
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <!-- 特殊类型字段 -->
                        <template v-else-if="field.fieldtype === 'Cron Editor'">
                          <n-input 
                            v-model:value="record[field.fieldname]" 
                            :placeholder="t(field.fieldname)"
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <template v-else-if="field.fieldtype === 'Duration'">
                          <n-input 
                            v-model:value="record[field.fieldname]" 
                            :placeholder="t(field.fieldname)"
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <template v-else-if="field.fieldtype === 'Icon'">
                          <n-input 
                            v-model:value="record[field.fieldname]" 
                            :placeholder="t(field.fieldname)"
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <template v-else-if="field.fieldtype === 'Geolocation'">
                          <n-input 
                            v-model:value="record[field.fieldname]" 
                            :placeholder="t(field.fieldname)"
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <template v-else-if="field.fieldtype === 'Signature'">
                          <div class="signature-container">
                            <span class="field-value">{{ formatDisplayValue(record[field.fieldname]) }}</span>
                          </div>
                        </template>
                        
                        <template v-else-if="field.fieldtype === 'Image'">
                          <div class="image-container">
                            <span class="field-value">{{ formatDisplayValue(record[field.fieldname]) }}</span>
                          </div>
                        </template>
                        
                        <template v-else-if="field.fieldtype === 'Attach'">
                          <div class="attach-container">
                            <span class="field-value">{{ formatDisplayValue(record[field.fieldname]) }}</span>
                          </div>
                        </template>
                        
                        <template v-else-if="field.fieldtype === 'Attach Image'">
                          <div class="attach-image-container">
                            <span class="field-value">{{ formatDisplayValue(record[field.fieldname]) }}</span>
                          </div>
                        </template>
                        
                        <template v-else-if="field.fieldtype === 'Table'">
                          <!-- 专门渲染 seen_by 子表为简洁表格 -->
                          <template v-if="field.fieldname === 'seen_by'">
                            <n-data-table
                              :columns="seenByColumns"
                              :data="getSeenByData()"
                              size="small"
                              :bordered="false"
                              :single-line="true"
                              :pagination="false"
                            />
                          </template>
                          <template v-else>
                            <div class="table-container">
                              <span class="field-value">{{ formatDisplayValue(record[field.fieldname]) }}</span>
                            </div>
                          </template>
                        </template>
                        
                        <template v-else-if="field.fieldtype === 'Table MultiSelect'">
                          <div class="table-multiselect-container">
                            <span class="field-value">{{ formatDisplayValue(record[field.fieldname]) }}</span>
                          </div>
                        </template>
                        
                        <template v-else-if="field.fieldtype === 'Button'">
                          <n-button 
                            :disabled="!canEdit"
                            @click="handleButtonClick(field)"
                          >
                            {{ t(field.label || field.fieldname) }}
                          </n-button>
                        </template>
                        
                        <template v-else-if="field.fieldtype === 'Heading'">
                          <h3 class="field-heading">{{ t(field.label || field.fieldname) }}</h3>
                        </template>
                        
                        <template v-else-if="field.fieldtype === 'HTML'">
                          <div class="html-content" v-html="record[field.fieldname]"></div>
                        </template>
                        
                        <template v-else-if="field.fieldtype === 'Autocomplete'">
                          <n-auto-complete 
                            v-model:value="record[field.fieldname]" 
                            :options="getSelectOptions(field)"
                            :placeholder="t(field.fieldname)"
                            :disabled="!canEdit"
                          />
                        </template>
                        
                        <!-- 默认显示 -->
                        <template v-else>
                          <span class="field-value">{{ formatDisplayValue(record[field.fieldname]) }}</span>
                        </template>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { NButton, NSpace, NIcon, NProgress, NInput, NSelect, NInputNumber, NCheckbox, NDatePicker, NTimePicker, NRate, NColorPicker, NAutoComplete, NDataTable, useMessage } from 'naive-ui'
import JeditorControl from '../../core/components/form/controls/Jeditor.vue'
import { Icon } from '@iconify/vue'
import axios from 'axios'
import { t } from '../../shared/i18n'
import { get_session_api_headers } from '../../shared/api/auth'
import { usePageTypeSlug } from '../../shared/utils/slug'
import { getSinglePageData, saveSinglePageData } from '../../shared/utils/pagetype'

const route = useRoute()
const router = useRouter()
const message = useMessage()

// 使用组合式函数处理URL slug
const { entity } = usePageTypeSlug(route)
const canEdit = ref(false)

const record = ref<any>({})
const metaFields = ref<any[]>([])
const pageMeta = ref<any>({})
const activeTab = ref('default')
const loading = ref(false)

const pageTitle = computed(() => {
  return record.value.name || record.value.label || t(entity.value)
})

const pageDescription = computed(() => {
  return ''
})

// 按照 jingrow 系统完全一致的逻辑解析字段结构
const tabs = computed(() => {
  const orderedFields = getOrderedFields()
  
  const result: any[] = []
  let currentTab: any = null
  let currentSection: any = null
  let currentColumn: any = null
  
  // 检查是否有 Tab Break 字段
  const hasTabBreak = orderedFields.some(field => field.fieldtype === 'Tab Break')
  
  // 如果没有 Tab Break，创建一个默认的 Tab（按照 jingrow 逻辑）
  if (!hasTabBreak) {
    currentTab = {
      key: 'default',
      label: t('Detail'),
      sections: []
    }
  }
  
  for (const field of orderedFields) {
    
    switch (field.fieldtype) {
      case 'Tab Break':
        
        // 保存当前 Tab（如果有的话）
        if (currentTab) {
          // 保存当前 Section（如果有的话）
          if (currentSection) {
            // 保存当前 Column（如果有的话）
            if (currentColumn && currentColumn.fields.length > 0) {
              if (!currentSection.columns) currentSection.columns = []
              currentSection.columns.push({ ...currentColumn })
            }
            // 保存 Section
            if (currentSection.columns && currentSection.columns.length > 0) {
              if (!currentTab.sections) currentTab.sections = []
              currentTab.sections.push({ ...currentSection })
            }
          }
          // 保存 Tab
          if (currentTab.sections && currentTab.sections.length > 0) {
            result.push({ ...currentTab })
          }
        }
        
        // 开始新 Tab
        currentTab = {
          key: field.fieldname || field.label || `tab_${result.length + 1}`,
          label: field.label || field.fieldname || t('Detail'),
          sections: []
        }
        currentSection = null
        currentColumn = null
        break
        
      case 'Section Break':
        
        // 保存当前 Section（如果有的话）
        if (currentSection) {
          // 保存当前 Column（如果有的话）
          if (currentColumn && currentColumn.fields.length > 0) {
            if (!currentSection.columns) currentSection.columns = []
            currentSection.columns.push({ ...currentColumn })
          }
          // 保存 Section
          if (currentSection.columns && currentSection.columns.length > 0) {
            if (!currentTab.sections) currentTab.sections = []
            currentTab.sections.push({ ...currentSection })
          }
        }
        
        // 开始新 Section
        currentSection = {
          key: field.fieldname || field.label || `section_${currentTab ? currentTab.sections.length + 1 : 1}`,
          label: field.label || field.fieldname || '',
          columns: []
        }
        currentColumn = null
        break
        
      case 'Column Break':
        
        // 确保有 Tab 和 Section
        if (!currentTab) {
          currentTab = {
            key: 'default',
            label: t('Detail'),
            sections: []
          }
        }
        if (!currentSection) {
          currentSection = {
            key: 'default',
            label: '',
            columns: []
          }
        }
        
        // 保存当前 Column（如果有的话）
        if (currentColumn && currentColumn.fields.length > 0) {
          if (!currentSection.columns) currentSection.columns = []
          currentSection.columns.push({ ...currentColumn })
        }
        
        // 开始新 Column
        currentColumn = {
          key: `column_${currentSection.columns ? currentSection.columns.length : 0}`,
          fields: []
        }
        break
        
      default:
        // 普通字段
        // 确保有 Tab、Section 和 Column
        if (!currentTab) {
          currentTab = {
            key: 'default',
            label: t('Detail'),
            sections: []
          }
        }
        if (!currentSection) {
          currentSection = {
            key: 'default',
            label: '',
            columns: []
          }
        }
        if (!currentColumn) {
          currentColumn = {
            key: 'default',
            fields: []
          }
        }
        
        currentColumn.fields.push(field)
        break
    }
  }
  
  // 保存最后的 Tab、Section 和 Column
  if (currentTab) {
    if (currentSection) {
      if (currentColumn && currentColumn.fields.length > 0) {
        if (!currentSection.columns) currentSection.columns = []
        currentSection.columns.push({ ...currentColumn })
      }
      if (currentSection.columns && currentSection.columns.length > 0) {
        if (!currentTab.sections) currentTab.sections = []
        currentTab.sections.push({ ...currentSection })
      }
    }
    if (currentTab.sections && currentTab.sections.length > 0) {
      result.push({ ...currentTab })
    }
  }
  
  return result
})

const hasTabs = computed(() => tabs.value.length > 1)

// 按照 field_order 获取有序字段
function getOrderedFields() {
  const fieldsMap = new Map()
  metaFields.value.forEach(field => {
    fieldsMap.set(field.fieldname, field)
  })
  
  
  // 按照 pageMeta.field_order 排序
  if (pageMeta.value.field_order && Array.isArray(pageMeta.value.field_order)) {
    const ordered = pageMeta.value.field_order
      .filter((fieldname: string) => fieldsMap.has(fieldname))
      .map((fieldname: string) => fieldsMap.get(fieldname))
    
    // 添加不在 field_order 中的字段
    const orderedFieldnames = new Set(pageMeta.value.field_order)
    const remaining = metaFields.value.filter(f => !orderedFieldnames.has(f.fieldname))
    
    
    return [...ordered, ...remaining]
  }
  
  // 如果没有 field_order，按原来的顺序
  return metaFields.value
}

function getTabSections(tab: any) {
  return tab.sections || []
}

function getSelectOptions(field: any) {
  if (!field.options) return []
  const options = field.options.split('\n').filter((s: string) => s.trim() !== '')
  return options.map((opt: string) => ({ label: t(opt), value: opt }))
}

// Seen By 简洁表格列定义（仅显示用户）
const seenByColumns = [
  { title: t('User'), key: 'user' }
]

// 保留通用格式化函数以供其它字段使用（当前表不使用）

function getSeenByData() {
  const list = Array.isArray(record.value?.seen_by) ? record.value.seen_by : []
  return list.map((item: any) => ({
    user: item.user || item.owner || '—'
  }))
}

// 按照 jingrow 系统逻辑评估字段依赖条件
function evaluateDependsOn(expression: string) {
  if (!expression) return true

  try {
    // 支持 eval: 前缀的表达式，允许使用 pg.<field>、&&、||、!、括号、比较等
    if (expression.startsWith('eval:')) {
      const code = expression.substring(5)
      const pg = record.value
      // 仅暴露 pg 到表达式环境，避免访问全局
      const evaluator = new Function('pg', `return !!(${code})`)
      return !!evaluator(pg)
    }

    // 非 eval: 的简单依赖，按字段 truthy 判断
    return !!record.value[expression]
  } catch (_err) {
    // 对于 eval 表达式出错，保守返回 false，避免无条件显示
    if (expression.startsWith('eval:')) return false
    return true
  }
}

// 检查字段是否是结构字段（不需要显示）
function isStructuralField(field: any) {
  const isStructural = ['Tab Break', 'Section Break', 'Column Break'].includes(field.fieldtype)
  if (isStructural) {
  }
  return isStructural
}

// 检查字段是否应该显示
function shouldShowField(field: any) {
  
  // 首先检查是否是结构字段
  if (isStructuralField(field)) {
    return false
  }

  // 单页详情不显示已读用户子表
  if (field && field.fieldname === 'seen_by') {
    return false
  }
  
  if (!field.depends_on) {
    return true
  }
  
  const result = evaluateDependsOn(field.depends_on)
  return result
}

// 处理多选复选框的值
function getMultiCheckValue(fieldname: string, optionValue: string) {
  const value = record.value[fieldname]
  if (Array.isArray(value)) {
    return value.includes(optionValue)
  }
  return false
}

// 更新多选复选框的值
function updateMultiCheckValue(fieldname: string, optionValue: string, checked: boolean) {
  if (!record.value[fieldname]) {
    record.value[fieldname] = []
  }
  if (!Array.isArray(record.value[fieldname])) {
    record.value[fieldname] = []
  }
  
  if (checked) {
    if (!record.value[fieldname].includes(optionValue)) {
      record.value[fieldname].push(optionValue)
    }
  } else {
    const index = record.value[fieldname].indexOf(optionValue)
    if (index > -1) {
      record.value[fieldname].splice(index, 1)
    }
  }
}

// 处理按钮点击
function handleButtonClick(_field: any) {
  // 这里可以添加按钮点击的处理逻辑
}

function formatDisplayValue(value: any) {
  if (value === null || value === undefined) return '—'
  if (typeof value === 'string' && value.length > 0) {
    return t(value)
  }
  return value
}

function formatJson(value: any) {
  if (!value) return ''
  try {
    return JSON.stringify(value, null, 2)
  } catch {
    return String(value)
  }
}

// 获取 JSON 字段的显示值
function getJsonDisplayValue(value: any) {
  if (!value) return ''
  
  // 如果已经是字符串，直接返回
  if (typeof value === 'string') {
    try {
      // 尝试格式化字符串 JSON
      const parsed = JSON.parse(value)
      return JSON.stringify(parsed, null, 2)
    } catch {
      // 如果不是有效 JSON，返回原字符串
      return value
    }
  }
  
  // 如果是对象，格式化为 JSON 字符串
  try {
    return JSON.stringify(value, null, 2)
  } catch {
    return String(value)
  }
}

// 更新 JSON 字段的值
function updateJsonValue(fieldName: string, value: string) {
  if (!value.trim()) {
    record.value[fieldName] = null
    return
  }
  
  try {
    // 尝试解析为 JSON 对象
    record.value[fieldName] = JSON.parse(value)
  } catch {
    // 如果解析失败，保存为字符串
    record.value[fieldName] = value
  }
}

// 加载元数据
async function loadMeta() {
  loading.value = true
  try {
    const url = `/api/data/PageType/${encodeURIComponent(entity.value)}`
    const res = await axios.get(url, { headers: get_session_api_headers(), withCredentials: true })
    const data = res.data?.data
    
    metaFields.value = data?.fields || []
    pageMeta.value = data || {}
    
    
    canEdit.value = true // 默认支持编辑
    
    // 设置默认活动标签：显示第一个标签页
    if (tabs.value.length > 0) {
      activeTab.value = tabs.value[0].key
    }
    
  } catch (error) {
    message.error(t('Failed to load metadata'))
    console.error('Failed to load metadata:', error)
  } finally {
    loading.value = false
  }
}

// 加载单页数据 - 使用专门的单页API
async function loadSinglePageData() {
  loading.value = true
  
  try {
    const result = await getSinglePageData(entity.value)
    
    if (result.success) {
      record.value = result.data || {}
    } else {
      message.error(result.message || t('Failed to load data'))
      record.value = {}
    }
  } catch (error) {
    message.error(t('Failed to load data'))
    console.error('Failed to load data:', error)
    record.value = {}
  } finally {
    loading.value = false
  }
}

// 保存
async function handleSave() {
  loading.value = true
  try {
    const result = await saveSinglePageData(entity.value, record.value)
    
    if (result.success) {
      message.success(t('Saved successfully'))
      // 重新加载数据以获取最新状态
      await loadSinglePageData()
    } else {
      message.error(result.message || t('Save failed'))
    }
  } catch (error) {
    message.error(t('Save failed'))
    console.error('Save failed:', error)
  } finally {
    loading.value = false
  }
}

// 简化的返回逻辑
function goBack() {
  // 返回首页
  router.push('/')
}

onMounted(async () => {
  await loadMeta()
  await loadSinglePageData()
})

// 监听路由参数变化
watch(() => route.params.entity, async (newEntity, oldEntity) => {
  if (newEntity !== oldEntity) {
    // 重新加载元数据和数据
    await loadMeta()
    await loadSinglePageData()
  }
})
</script>

<style scoped>
.single-page-detail {
  padding: 16px;
  width: 100%;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px 0;
}

.page-description {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

/* Jingrow 风格的 Form Layout */
.form-layout {
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.form-page {
  padding: 24px;
}

/* Tabs */
.form-tabs-list {
  border-bottom: 1px solid #e5e7eb;
  margin-bottom: 24px;
}

.nav.form-tabs {
  display: flex;
  list-style: none;
  margin: 0;
  padding: 0;
}

.nav-item {
  margin-right: 8px;
}

.nav-link {
  display: block;
  padding: 12px 16px;
  color: #6b7280;
  text-decoration: none;
  border-bottom: 2px solid transparent;
  transition: all 0.2s;
}

.nav.li.nav-item a:hover {
  color: #2563eb;
}

.nav-link.active {
  color: #2563eb;
  border-bottom-color: #2563eb;
}

/* Tab Content */
.form-tab-content {
  min-height: 400px;
}

.tab-pane {
  display: none;
}

.tab-pane.active {
  display: block;
}

/* Sections */
.form-sections {
  display: flex;
  flex-direction: column;
  gap: 32px;
}

.form-section {
  background: #f9fafb;
  border-radius: 8px;
  padding: 20px;
}

.section-header h4 {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 20px 0;
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 8px;
}

.section-body {
  display: grid;
  gap: 24px;
}

/* Columns */
.form-column {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* Two column layout */
.section-body:has(.form-column:nth-child(2)) {
  grid-template-columns: 1fr 1fr;
}

/* Three column layout */
.section-body:has(.form-column:nth-child(3)) {
  grid-template-columns: 1fr 1fr 1fr;
}

/* Four column layout */
.section-body:has(.form-column:nth-child(4)) {
  grid-template-columns: 1fr 1fr 1fr 1fr;
}

/* Fields */
.form-field {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.field-label {
  display: flex;
  align-items: center;
  gap: 4px;
}

.field-label label {
  font-weight: 500;
  color: #374151;
  font-size: 14px;
}

.required {
  color: #ef4444;
  font-weight: bold;
}

.field-content {
  min-height: 32px;
  display: flex;
  align-items: flex-start;
  flex-direction: column;
  width: 100%;
}

/* 确保所有输入组件都是全宽的 */
.field-content :deep(.n-input),
.field-content :deep(.n-select),
.field-content :deep(.n-input-number),
.field-content :deep(.n-date-picker),
.field-content :deep(.n-time-picker),
.field-content :deep(.n-rate),
.field-content :deep(.n-color-picker),
.field-content :deep(.n-auto-complete) {
  width: 100%;
}

.field-value {
  color: #111827;
  font-size: 14px;
  word-break: break-word;
}

.json-content {
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 12px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  white-space: pre-wrap;
  word-break: break-word;
  max-height: 200px;
  overflow-y: auto;
}

/* JSON 字段容器样式 */
.json-field-container {
  position: relative;
  width: 100%;
}

/* JSON 输入框样式 */
.json-textarea {
  width: 100%;
}

.json-textarea :deep(.n-input__input-el) {
  font-family: 'Courier New', monospace !important;
  font-size: 12px !important;
  line-height: 1.4 !important;
  white-space: pre !important;
  overflow-wrap: normal !important;
  width: 100% !important;
}

/* 特殊字段类型样式 */
.multicheck-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.signature-container,
.image-container,
.attach-container,
.attach-image-container,
.table-container,
.table-multiselect-container {
  padding: 12px;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  min-height: 40px;
  display: flex;
  align-items: center;
}

.field-heading {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  padding: 8px 0;
  border-bottom: 1px solid #e5e7eb;
}

.html-content {
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 12px;
  min-height: 40px;
}
</style>
