<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" class="save-btn-brand">
            <template #icon>
              <n-icon>
                <Icon icon="tabler:check" />
              </n-icon>
            </template>
            {{ 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 字段 - 使用 FieldRenderer 统一渲染 -->
                        <FieldRenderer 
                          v-for="field in column.fields" 
                          :key="field.fieldname"
                          :df="field"
                          :record="record"
                          :canEdit="canEdit"
                          :ctx="{ 
                            t: t_ctx, 
                            getSelectOptions, 
                            toDateValue, 
                            updateDateValue, 
                            handleButtonClick, 
                            getJsonDisplayValue, 
                            updateJsonValue, 
                            formatJson, 
                            entity: entity, 
                            id: entity, 
                            reload: async () => { await loadData() }, 
                            save: handleSave,
                            saveSilent: () => handleSave({ silent: true }),
                            onFieldChange
                          }"
                          v-show="shouldShowField(field)"
                        />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { NButton, NSpace, NIcon, useMessage } from 'naive-ui'
import FieldRenderer from '@/core/pagetype/form/FieldRenderer.vue'
import { Icon } from '@iconify/vue'
import axios from 'axios'
import { t, createT } from '@/shared/i18n'
import { usePageTypeSlug } from '@/shared/utils/slug'
import { getSinglePageData, saveSinglePageData } from '@/shared/utils/pagetype'
import { getPageTypeMeta, api } from '@/shared/api/common'
import { createFieldChangeTrigger } from '@/core/plugins/fieldPlugin'
import { loadAllPlugins } from '@/core/plugins/pluginLoader'

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

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

// Context-aware translation: auto-injects entity as msgctxt for all field labels/values
const t_ctx = createT(() => entity.value)

const canEdit = ref(false)

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

// Field change plugin trigger
const onFieldChange = createFieldChangeTrigger(entity.value, record)

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 || '',
          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 || []
}

// 动态字段选项缓存
const dynamicFieldOptions = ref<Record<string, string[]>>({})

function getSelectOptions(field: any) {
  // 检查是否有动态加载的选项
  if (dynamicFieldOptions.value[field.fieldname]) {
    const options = dynamicFieldOptions.value[field.fieldname]
    return options.map((opt: string) => ({ label: t_ctx(opt), value: opt }))
  }
  
  // 使用静态选项
  if (!field.options) return []
  const staticOptions = field.options.split('\n').filter((s: string) => s.trim() !== '')
  return staticOptions.map((opt: string) => ({ label: t_ctx(opt), value: opt }))
}

// 日期值转换函数（用于 Date 控件）
function toDateValue(v: any): number | null {
  if (!v) return null
  if (typeof v === 'number') return v
  if (v instanceof Date) return v.getTime()
  const parsed = new Date(v)
  if (!isNaN(parsed.getTime())) return parsed.getTime()
  return null
}

function updateDateValue(fieldname: string, v: number | null) {
  if (v === null || v === undefined) {
    record.value[fieldname] = null
  } else {
    const d = new Date(v)
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    record.value[fieldname] = `${y}-${m}-${day}`
  }
}

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

function getJsonDisplayValue(value: any) {
  if (!value) return ''
  
  if (typeof value === 'string') {
    try {
      const parsed = JSON.parse(value)
      return JSON.stringify(parsed, null, 2)
    } catch {
      return value
    }
  }
  
  try {
    return JSON.stringify(value, null, 2)
  } catch {
    return String(value)
  }
}

function updateJsonValue(fieldName: string, value: string) {
  if (!value.trim()) {
    record.value[fieldName] = null
    return
  }
  
  try {
    record.value[fieldName] = JSON.parse(value)
  } catch {
    record.value[fieldName] = value
  }
}

function handleButtonClick(_field: any) {
}

function evaluateDependsOn(expression: string) {
  if (!expression) return true

  try {
    if (expression.startsWith('eval:')) {
      const code = expression.substring(5)
      const pg = record.value
      const evaluator = new Function('pg', `return !!(${code})`)
      return !!evaluator(pg)
    }

    return !!record.value[expression]
  } catch (_err) {
    if (expression.startsWith('eval:')) return false
    return true
  }
}

function isStructuralField(field: any) {
  return ['Tab Break', 'Section Break', 'Column Break'].includes(field.fieldtype)
}

function shouldShowField(field: any) {
  if (isStructuralField(field)) {
    return false
  }

  if (field && (field.hidden === 1 || field.hidden === true || field.hidden === '1')) {
    return false
  }
  
  if (!field.depends_on) {
    return true
  }
  
  return evaluateDependsOn(field.depends_on)
}


// 加载元数据和单页数据 - 并行加载避免闪烁
async function loadData() {
  loading.value = true
  try {
    // 并行加载元数据和单页数据
    const [metaRes, dataRes] = await Promise.all([
      getPageTypeMeta(entity.value),
      getSinglePageData(entity.value)
    ])
    
    // 处理元数据
    const metaData = metaRes.success && metaRes.data ? metaRes.data : {}
    if (metaData) {
      metaFields.value = metaData.fields || []
      pageMeta.value = metaData || {}
      // Virtual PageType (e.g. System Health Report) should not be editable
      // because db_insert/db_update raise NotImplementedError
      if (pageMeta.value.is_virtual) {
        canEdit.value = false
      } else {
        canEdit.value = true
      }
    }
    
    // 处理单页数据
    if (dataRes.success) {
      record.value = dataRes.data || {}
    } else {
      message.error(dataRes.message || t('Failed to load data'))
      record.value = {}
    }
    
    // 设置默认活动标签
    if (tabs.value.length > 0) {
      activeTab.value = tabs.value[0].key
    }
    
    // 触发字段配置插件
    await applyFieldConfig()
    
  } catch (error) {
    message.error(t('Failed to load data'))
    console.error('Failed to load data:', error)
    record.value = {}
  } finally {
    loading.value = false
  }
}

// 应用字段配置插件
async function applyFieldConfig() {
  const { triggerFieldConfig } = await import('@/core/plugins/fieldPlugin')
  
  for (const field of metaFields.value) {
    if (field.fieldtype === 'Select' || field.fieldtype === 'Autocomplete') {
      const configuredField = await triggerFieldConfig(entity.value, field, record.value)
      if (configuredField.options && configuredField.options !== field.options) {
        dynamicFieldOptions.value[field.fieldname] = configuredField.options.split('\n').filter((s: string) => s.trim())
      }
    }
  }
}

// 保存
async function handleSave(options?: { silent?: boolean }) {
  const silent = options?.silent ?? false
  // Sync FormBuilder fields before save
  window.dispatchEvent(new CustomEvent('sync-form-builder-fields'))
  await new Promise(resolve => requestAnimationFrame(resolve))

  loading.value = true
  try {
    // Customize Form uses save_customization instead of regular save
    if (entity.value === 'Customize Form' && record.value.pg_type) {
      const result = await api.call('jingrow.handler.run_pg_method', {
        pgs: JSON.stringify(record.value),
        method: 'save_customization'
      })
      const updatedDoc = result?.pgs?.[0]
      if (updatedDoc) {
        Object.keys(updatedDoc).forEach(key => { record.value[key] = updatedDoc[key] })
      }
      if (!silent) message.success(t('Saved successfully'))
      return
    }

    const result = await saveSinglePageData(entity.value, record.value)
    
    if (result.success) {
      if (!silent) message.success(t('Saved successfully'))
      await loadData()
    } 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('/')
}

function handleSwitchTab(e: Event) {
  const tabKey = (e as CustomEvent).detail
  if (tabKey && tabs.value.some(t => t.key === tabKey)) {
    activeTab.value = tabKey
  }
}

onMounted(async () => {
  window.addEventListener('switch-active-tab', handleSwitchTab)
  await loadAllPlugins()
  await loadData()
})

onUnmounted(() => {
  window.removeEventListener('switch-active-tab', handleSwitchTab)
})

// 监听路由参数变化
watch(() => route.params.entity, async (newEntity, oldEntity) => {
  if (newEntity !== oldEntity) {
    // 重新加载数据
    await loadData()
  }
})
</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;
}

/* 通用字段包装器样式（支持 FieldRenderer） */
.form-column :deep(.field-wrapper) {
  display: flex;
  width: 100%;
}

.form-column :deep(.field-wrapper.layout-vertical) {
  flex-direction: column;
  gap: 6px;
}

.form-column :deep(.field-wrapper.layout-horizontal) {
  flex-direction: row;
  align-items: center;
  gap: 12px;
}

.form-column :deep(.field-wrapper.layout-horizontal .field-label) {
  min-width: 100px;
  flex-shrink: 0;
}

.form-column :deep(.field-label) {
  font-weight: 500;
  color: #374151;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.form-column :deep(.required) {
  color: #ef4444;
  font-weight: bold;
}

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

/* 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;
}

/* 特殊容器样式（由控件内部管理） */
.form-column :deep(.multicheck-container) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-column :deep(.table-container) {
  padding: 0;
  background: transparent;
  border: none;
  min-height: auto;
}

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

.form-column :deep(.html-content) {
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 12px;
  min-height: 40px;
}


/* 保存按钮 - 使用柔和的品牌色系，与列表页创建按钮一致 */
.save-btn-brand {
  background: #e6f8f0 !important;
  border: 1px solid #1fc76f !important;
  color: #0d684b !important;
}

.save-btn-brand :deep(.n-button__border) {
  border: none !important;
  border-color: transparent !important;
}

.save-btn-brand :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

.save-btn-brand:hover {
  background: #dcfce7 !important;
  border-color: #1fc76f !important;
  border: 1px solid #1fc76f !important;
  color: #166534 !important;
  box-shadow: 0 2px 8px rgba(31, 199, 111, 0.15) !important;
}

.save-btn-brand:hover :deep(.n-button__border),
.save-btn-brand:hover :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

.save-btn-brand:focus {
  background: #dcfce7 !important;
  border-color: #1fc76f !important;
  border: 1px solid #1fc76f !important;
  color: #166534 !important;
  box-shadow: 0 0 0 2px rgba(31, 199, 111, 0.2) !important;
}

.save-btn-brand:focus :deep(.n-button__border),
.save-btn-brand:focus :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

.save-btn-brand:active {
  background: #1fc76f !important;
  border-color: #1fc76f !important;
  border: 1px solid #1fc76f !important;
  color: white !important;
  box-shadow: 0 1px 4px rgba(31, 199, 111, 0.2) !important;
}

.save-btn-brand:active :deep(.n-button__border),
.save-btn-brand:active :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}

.save-btn-brand:disabled {
  background: #f1f5f9 !important;
  border: 1px solid #e2e8f0 !important;
  border-color: #e2e8f0 !important;
  color: #94a3b8 !important;
  opacity: 0.6 !important;
  cursor: not-allowed !important;
}

.save-btn-brand:disabled :deep(.n-button__border),
.save-btn-brand:disabled :deep(.n-button__state-border) {
  border: none !important;
  border-color: transparent !important;
}
</style>
