<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { NModal, NButton, NSpace, NIcon, NTag, NConfigProvider, NSelect } from 'naive-ui'
import FieldRenderer from '@/core/pagetype/form/FieldRenderer.vue'
import Link from './Link.vue'
import Date from './Date.vue'
import Float from './Float.vue'
import Currency from './Currency.vue'
import { Icon } from '@iconify/vue'
import axios from 'axios'
import { getPageTypeMeta } from '@/shared/api/common'

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

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

// 自定义按钮主题 - 与Button字段保持一致
const buttonThemeOverrides = {
  Button: {
    colorDefault: '#f3f4f6',
    colorHoverDefault: '#e5e7eb',
    colorPressedDefault: '#d1d5db',
    textColorDefault: '#374151',
    textColorHoverDefault: '#374151',
    textColorPressedDefault: '#374151',
    borderDefault: '1px solid #d1d5db',
    borderHoverDefault: '1px solid #9ca3af',
    borderPressedDefault: '1px solid #9ca3af',
  }
}

// Seen By 特殊处理
const seenByExpanded = ref(false)
const seenByUsers = computed(() => {
  const list = Array.isArray(props.record?.seen_by) ? props.record.seen_by : []
  return list.map((item: any, idx: number) => ({
    key: item.name || item.user || String(idx),
    label: item.user || item.owner || '—'
  }))
})

function toggleSeenBy() {
  seenByExpanded.value = !seenByExpanded.value
}

type Field = { label: string; fieldname: string; fieldtype: string; in_list_view?: boolean; columns?: number; options?: string }

const loading = ref(false)
const childFields = ref<Field[]>([])

const rows = computed<any[]>(() => {
  const value = (props.record as any)?.[props.df.fieldname]
  return Array.isArray(value) ? value : []
})

const selectedRows = ref<Set<number>>(new Set())
const selectAll = ref(false)

// 弹窗编辑状态
const showEditModal = ref(false)
const editIndex = ref<number | null>(null)
const editForm = ref<Record<string, any>>({})

// Inner edit state
const editingCell = ref<{ rowIndex: number; fieldName: string } | null>(null)
const tableContainer = ref<HTMLElement | null>(null)

// 构建子表布局结构：Tab → Section → Column → Field
const childTabs = computed(() => {
  const fields = childFields.value
  const result: any[] = []
  let currentTab: any = null
  let currentSection: any = null
  let currentColumn: any = null
  
  // 检查是否有 Tab Break 字段
  const hasTabBreak = fields.some(field => field.fieldtype === 'Tab Break')
  
  // 如果没有 Tab Break，创建一个默认的 Tab
  if (!hasTabBreak) {
    currentTab = {
      key: 'default',
      label: t('Detail'),
      sections: []
    }
  }
  
  for (const field of fields) {
    switch (field.fieldtype) {
      case 'Tab Break':
        // 保存当前 Tab（如果有的话）
        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 })
          }
        }
        
        // 开始新 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) {
          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 })
          }
        }
        
        // 开始新 Section
        currentSection = {
          key: field.fieldname || field.label || `section_${currentTab ? currentTab.sections.length + 1 : 1}`,
          label: field.label || '', // 只使用label，不使用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:
        // 普通字段
        // 检查是否是结构字段（通过字段类型判断）
        if (['Tab Break', 'Section Break', 'Column Break'].includes(field.fieldtype)) {
          // 跳过结构字段，不添加到fields中
          break
        }
        
        // 确保有 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 t = (key: string) => (props.ctx?.t ? props.ctx.t(key) : key)

async function loadChildMeta() {
  const pagetype = props.df?.options
  if (!pagetype) return
  loading.value = true
  try {
    const result = await getPageTypeMeta(pagetype)
    if (result.success && result.data) {
      const fields: Field[] = result.data.fields || []
      childFields.value = fields
    }
  } catch (error) {
    console.error('Failed to load child meta for', pagetype, ':', error)
  } finally {
    loading.value = false
  }
}

function getTableColumns() {
  const table_fields = childFields.value
  const columns: Array<[Partial<Field>, number]> = []
  let total = 1
  // No. column - fixed narrow width for row numbers
  columns.push([{ label: t('No.') }, 0.5])

  for (const tf of table_fields) {
    const isLayout = ['Section Break', 'Column Break', 'Tab Break'].includes(tf.fieldtype)
    if (isLayout) continue
    if (!tf.in_list_view || !tf.label) continue
    // Force wider columns for Date/Datetime to show full date
    let colsize: number
    if (['Date', 'Datetime'].includes(tf.fieldtype)) {
      colsize = Math.max(tf.columns ? Number(tf.columns) : 0, 3)
    } else {
      colsize = tf.columns ? Number(tf.columns) : defaultCol(tf)
    }
    if (total > 11 + colsize) continue
    total += colsize
    columns.push([{ label: tf.label, fieldname: tf.fieldname, fieldtype: tf.fieldtype, options: tf.options }, colsize])
  }

  adjust(total, true)
  adjust(total, false)

  function defaultCol(f: Field) {
    // Rough mapping to match cloud behavior
    const narrow = ['Int', 'Check', 'Percent']
    const medium = ['Float', 'Currency']
    const wide = ['Link', 'Text', 'Long Text', 'Date', 'Datetime']
    if (narrow.includes(f.fieldtype)) return 1
    if (medium.includes(f.fieldtype)) return 2
    if (wide.includes(f.fieldtype)) return 3
    return 2
  }

  function adjust(_total: number, increase?: boolean) {
    let passes = 0
    let totalRef = _total
    const startCond = () => (increase ? totalRef < 11 : totalRef >= 11)
    while (startCond() && passes < 11) {
      for (let i = 0; i < columns.length; i++) {
        const col = columns[i]
        const size = col[1]
        const fieldname = (col[0] as any).fieldname
        if (!fieldname) continue
        if (size > 1 && size < 11) {
          if (increase) {
            col[1] += 1
            totalRef++
          } else {
            col[1] -= 1
            totalRef--
          }
        }
        if (increase && totalRef > 9) break
        if (!increase && totalRef < 11) break
      }
      passes++
    }
  }

  return columns
}

const columns = computed(() => getTableColumns())

function addRow() {
  if (!props.canEdit) return
  const arr = Array.isArray((props.record as any)[props.df.fieldname]) ? (props.record as any)[props.df.fieldname] : (((props.record as any)[props.df.fieldname] = []), (props.record as any)[props.df.fieldname])
  const idx = (arr?.length || 0) + 1
  const row: any = { idx }
  // 预置字段为空值
  for (const [meta] of columns.value.slice(1)) {
    const fn = (meta as any).fieldname
    if (fn && !(fn in row)) row[fn] = ''
  }
  arr.push(row)
}

function removeRow(i: number) {
  if (!props.canEdit) return
  const arr = rows.value
  if (!arr?.length) return
  arr.splice(i, 1)
  arr.forEach((r: any, j: number) => (r.idx = j + 1))
  // 清除选中状态
  selectedRows.value.clear()
  selectAll.value = false
}

function toggleSelectAll() {
  if (selectAll.value) {
    selectedRows.value.clear()
  } else {
    selectedRows.value = new Set(Array.from({ length: rows.value.length }, (_, i) => i))
  }
  selectAll.value = !selectAll.value
}

function toggleRowSelect(index: number) {
  if (selectedRows.value.has(index)) {
    selectedRows.value.delete(index)
  } else {
    selectedRows.value.add(index)
  }
  // 更新全选状态
  selectAll.value = selectedRows.value.size === rows.value.length
}

function editRow(index: number) {
  if (!props.canEdit) return
  const row = rows.value[index]
  if (!row) return
  
  editIndex.value = index
  
  // 初始化编辑表单数据
  const data: Record<string, any> = {}
  childFields.value.forEach((f) => {
    if (f.fieldname && f.fieldname !== 'idx') {
      data[f.fieldname] = row[f.fieldname] ?? ''
    }
  })
  editForm.value = data
  showEditModal.value = true
}

function saveEdit() {
  if (editIndex.value == null) return
  const row = rows.value[editIndex.value]
  Object.keys(editForm.value).forEach((k) => {
    row[k] = editForm.value[k]
  })
  showEditModal.value = false
}

function batchDelete() {
  if (!props.canEdit || selectedRows.value.size === 0) return
  const arr = rows.value
  const indicesToDelete = Array.from(selectedRows.value).sort((a, b) => b - a) // 从后往前删除
  indicesToDelete.forEach(i => arr.splice(i, 1))
  arr.forEach((r: any, j: number) => (r.idx = j + 1))
  // 清除选中状态
  selectedRows.value.clear()
  selectAll.value = false
}

// 内联编辑功能
function startInlineEdit(rowIndex: number, fieldName: string) {
  if (!props.canEdit) return
  editingCell.value = { rowIndex, fieldName }
}

// Check if field is editable
function isFieldEditable(field: any) {
  // 排除结构字段和特殊字段
  const structuralFields = ['Tab Break', 'Section Break', 'Column Break']
  if (structuralFields.includes(field.fieldtype)) return false
  
  // 排除隐藏字段
  if (field.hidden === 1 || field.hidden === true || field.hidden === '1') return false
  
  // 检查依赖条件
  if (field.depends_on) {
    try {
      if (field.depends_on.startsWith('eval:')) {
        const code = field.depends_on.substring(5)
        const evaluator = new Function('pg', `return !!(${code})`)
        return !!evaluator(props.record)
      }
      return !!props.record[field.depends_on]
    } catch {
      return false
    }
  }
  
  return true
}

function handleClickOutside(event: Event) {
  if (!editingCell.value) return
  const target = event.target as HTMLElement
  // Check if click is outside the editing cell
  if (!target.closest('.inline-edit-input') && 
      !target.closest('.link-field-container') && 
      !target.closest('.n-date-picker') &&
      !target.closest('.n-date-panel') &&
      !target.closest('.n-input-number') &&
      !target.closest('.n-select') &&
      !target.closest('.n-base-select-menu')) {
    editingCell.value = null
  }
}

onMounted(() => {
  loadChildMeta()
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<template>
  <!-- Seen By 特殊布局 -->
  <template v-if="df.fieldname === 'seen_by'">
    <div class="seen-by-block">
      <div class="field-label">
        <div class="seen-by-header" @click="toggleSeenBy()">
          <label>{{ ctx?.t ? ctx.t(df.label || df.fieldname) : (df.label || df.fieldname) }}</label>
          <span class="seen-by-count">{{ seenByUsers.length }}</span>
          <n-icon size="16" class="chevron-icon">
            <Icon :icon="seenByExpanded ? 'tabler:chevron-up' : 'tabler:chevron-down'" />
          </n-icon>
        </div>
      </div>
      <div class="field-content" :class="{ 'seen-by-collapsed': !seenByExpanded }">
        <transition name="fade">
          <div v-show="seenByExpanded" class="seen-by-chips">
            <n-tag v-for="u in seenByUsers" :key="u.key" size="small" round class="seen-by-chip" :bordered="false">
              <span class="chip-text">{{ u.label }}</span>
            </n-tag>
          </div>
        </transition>
      </div>
    </div>
  </template>
  
  <!-- 标准Table布局 -->
  <div v-else :class="['field-wrapper', `layout-${labelLayout}`]">
    <label class="field-label">
      {{ ctx?.t ? ctx.t(df.label || df.fieldname) : (df.label || df.fieldname) }}
      <span v-if="df.reqd" class="required">*</span>
    </label>
    <div ref="tableContainer" class="table-container">
      <template v-if="columns.length > 0">
        <div class="table-grid">
          <div class="table-head">
            <div class="table-cell head checkbox" v-if="canEdit" style="width: 4%">
              <input type="checkbox" :checked="selectAll" @change="toggleSelectAll" />
            </div>
            <div
              v-for="([meta, size], i) in columns"
              :key="i"
              class="table-cell head"
              :style="i === 0 ? { width: '5%', minWidth: '40px' } : { width: (size * 8) + '%' }"
            >
              {{ t((meta as any).label) }}
            </div>
            <div class="table-cell head actions" v-if="canEdit" style="width: 8%">{{ t('Actions') }}</div>
          </div>

          <div class="table-body" v-if="rows.length">
            <div class="table-row" v-for="(r, i) in rows" :key="i">
              <div class="table-cell checkbox" v-if="canEdit" style="width: 4%">
                <input type="checkbox" :checked="selectedRows.has(i)" @change="toggleRowSelect(i)" />
              </div>
              <div
                v-for="([meta, size], k) in columns"
                :key="k"
                class="table-cell"
                :style="k === 0 ? { width: '5%', minWidth: '40px' } : { width: (size * 8) + '%' }"
              >
                <template v-if="k === 0">{{ i + 1 }}</template>
                <template v-else>
                  <!-- Date field -->
                  <template v-if="(meta as any).fieldtype === 'Date' || (meta as any).fieldtype === 'Datetime'">
                    <template v-if="editingCell?.rowIndex === i && editingCell?.fieldName === (meta as any).fieldname">
                      <Date
                        :df="meta"
                        :record="rows[i]"
                        :canEdit="canEdit"
                        :ctx="ctx"
                        :onlyInput="true"
                      />
                    </template>
                    <template v-else>
                      <span 
                        v-if="!canEdit || !isFieldEditable(meta)"
                        class="cell-display"
                      >
                        {{ r[(meta as any).fieldname] ?? '' }}
                      </span>
                      <span 
                        v-else
                        class="cell-display editable-cell"
                        @click.stop="startInlineEdit(i, (meta as any).fieldname)"
                        :title="t('Click to edit') + ' ' + t((meta as any).label)"
                      >
                        {{ r[(meta as any).fieldname] ?? '' }}
                      </span>
                    </template>
                  </template>
                  <!-- Inner edit mode for other fields -->
                  <template v-else-if="editingCell?.rowIndex === i && editingCell?.fieldName === (meta as any).fieldname">
                    <template v-if="(meta as any).fieldtype === 'Link'">
                      <Link
                        :df="meta"
                        :record="rows[i]"
                        :canEdit="canEdit"
                        :ctx="ctx"
                        :onlyInput="true"
                      />
                    </template>
                    <template v-else-if="(meta as any).fieldtype === 'Float' || (meta as any).fieldtype === 'Int'">
                      <Float
                        :df="meta"
                        :record="rows[i]"
                        :canEdit="canEdit"
                        :ctx="ctx"
                        :onlyInput="true"
                      />
                    </template>
                    <template v-else-if="(meta as any).fieldtype === 'Currency'">
                      <Currency
                        :df="meta"
                        :record="rows[i]"
                        :canEdit="canEdit"
                        :ctx="ctx"
                        :onlyInput="true"
                      />
                    </template>
                    <template v-else-if="(meta as any).fieldtype === 'Select'">
                      <n-select
                        v-model:value="rows[i][(meta as any).fieldname]"
                        :options="ctx.getSelectOptions ? ctx.getSelectOptions(meta) : []"
                        placeholder=""
                        :disabled="!canEdit"
                        size="small"
                      />
                    </template>
                    <template v-else>
                      <input
                        v-model="rows[i][(meta as any).fieldname]"
                        class="inline-edit-input"
                        :placeholder="(meta as any).label"
                        autofocus
                      />
                    </template>
                  </template>
                  <!-- Display mode -->
                  <template v-else>
                    <span 
                      v-if="!canEdit || !isFieldEditable(meta)"
                      class="cell-display"
                    >
                      {{ r[(meta as any).fieldname] ?? '' }}
                    </span>
                    <span 
                      v-else
                      class="cell-display editable-cell"
                      @click.stop="startInlineEdit(i, (meta as any).fieldname)"
                      :title="t('Click to edit') + ' ' + t((meta as any).label)"
                    >
                      {{ r[(meta as any).fieldname] ?? '' }}
                    </span>
                  </template>
                </template>
              </div>
              <div class="table-cell actions" v-if="canEdit" style="width: 8%">
                <button class="link-btn edit-btn" type="button" @click="editRow(i)" title="编辑">
                  <i class="fa-regular fa-edit"></i>
                </button>
                <button class="link-btn delete-btn" type="button" @click="removeRow(i)" title="删除">
                  <i class="fa-regular fa-trash-can"></i>
                </button>
              </div>
            </div>
          </div>

          <div class="grid-empty" v-else>
            <span>{{ t('No Data') }}</span>
          </div>
        </div>

        <div class="grid-footer" v-if="canEdit">
          <div class="footer-actions">
            <button 
              v-if="selectedRows.size > 0" 
              class="btn btn-danger" 
              type="button" 
              @click="batchDelete"
            >
              {{ t('Delete') }} ({{ selectedRows.size }})
            </button>
            <n-config-provider :theme-overrides="buttonThemeOverrides">
              <n-button type="default" @click="addRow">{{ t('Add Row') }}</n-button>
            </n-config-provider>
          </div>
        </div>
      </template>
      <template v-else>
        <span class="field-value">{{ loading ? t('Loading') + '…' : '—' }}</span>
      </template>
      
      <!-- 编辑弹窗 -->
      <n-modal 
        v-model:show="showEditModal" 
        :show-icon="false" 
        :mask-closable="true"
        :style="{ width: '90%', maxWidth: '1200px' }"
        :auto-focus="false"
        preset="card"
        :title="t('Edit Child Row')"
      >
        <div class="child-form-layout">
          <!-- 渲染完整的表单布局：Tab → Section → Column → Field -->
          <div v-for="tab in childTabs" :key="tab.key" class="form-tab">
            <div v-for="section in tab.sections" :key="section.key" class="form-section">
              <!-- Section 标题 -->
              <div v-if="section.label" class="section-header">
                <h4 class="section-title">{{ 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"
                  >
                    <FieldRenderer
                      :df="{ ...field, fieldname: field.fieldname }"
                      :record="editForm"
                      :canEdit="canEdit"
                      :ctx="ctx"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <template #footer>
          <div class="modal-footer">
            <n-space>
              <n-button @click="showEditModal = false">{{ t('Cancel') }}</n-button>
              <n-button type="primary" @click="saveEdit">{{ t('Save') }}</n-button>
            </n-space>
          </div>
        </template>
      </n-modal>
    </div>
  </div>
</template>

<style scoped>
/* 字段包装器样式 */
.field-wrapper {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.field-wrapper.layout-horizontal {
  flex-direction: row;
  align-items: flex-start;
  gap: 12px;
}

.field-label {
  font-weight: 500;
  color: #374151;
  font-size: 14px;
  line-height: 1.5;
  display: flex;
  align-items: center;
  gap: 4px;
}

.field-wrapper.layout-horizontal .field-label {
  min-width: 120px;
  flex-shrink: 0;
  margin-top: 8px;
}

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

/* Seen By 特殊布局样式 */
.seen-by-block {
  width: 100%;
}

.seen-by-header {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  color: #374151;
  user-select: none;
}

.seen-by-header label {
  font-weight: 500;
  color: #374151;
  font-size: 14px;
  line-height: 1.5;
}

.seen-by-count {
  margin: 0 6px;
  color: #9ca3af;
  font-size: 12px;
}

.chevron-icon {
  transition: transform 0.2s ease;
}

.seen-by-chips {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.seen-by-chip {
  background: #f3f4f6;
}

.chip-text {
  padding: 0 2px;
}

.fade-enter-active, .fade-leave-active { 
  transition: opacity 0.15s ease; 
}

.fade-enter-from, .fade-leave-to { 
  opacity: 0; 
}

/* 收起态去除多余高度与间距 */
.field-content.seen-by-collapsed {
  min-height: 0;
  padding: 0;
}

.table-container { width: 100%; }
.table-grid { width: 100%; }
.table-head { display: flex; background: #fff; border: 1px solid var(--table-border-color, #e5e7eb); border-top-left-radius: 6px; border-top-right-radius: 6px; }
.table-body { border: 1px solid var(--table-border-color, #e5e7eb); border-top: none; border-bottom-left-radius: 6px; border-bottom-right-radius: 6px; }
.table-row { display: flex; border-top: 1px solid var(--table-border-color, #e5e7eb); }
.table-cell { padding: 8px 10px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; border-left: 1px solid var(--table-border-color, #e5e7eb); }
.table-cell:first-child { border-left: none; }
.table-cell.head { background: #fff; font-weight: 600; }
.table-cell.actions { text-align: center; }
.table-cell.actions .link-btn { margin: 0 2px; }
.table-cell.checkbox { text-align: center; padding: 8px 4px; }
.table-cell.checkbox input[type="checkbox"] { margin: 0; }
.grid-empty { padding: 16px; text-align: center; color: #6b7280; border: 1px dashed #e5e7eb; border-radius: 6px; background: #fff; }
.grid-footer { margin-top: 12px; }
.footer-actions { display: flex; gap: 8px; align-items: center; }
.btn { padding: 6px 12px; border-radius: 6px; cursor: pointer; font-size: 13px; border: 1px solid #e5e7eb; }
.btn-primary { background: #3b82f6; color: white; border-color: #3b82f6; }
.btn-primary:hover { background: #2563eb; }
.btn-danger { background: #ef4444; color: white; border-color: #ef4444; }
.btn-danger:hover { background: #dc2626; }
.link-btn { background: transparent; border: none; cursor: pointer; padding: 2px; }
.link-btn.edit-btn { color: #6b7280; }
.link-btn.edit-btn:hover { color: #374151; }
.link-btn.delete-btn { color: #ef4444; }
.link-btn.delete-btn:hover { color: #dc2626; }

/* 子表编辑弹窗样式 - 统一整体设计 */
.child-form-layout {
  width: 100%;
  max-height: 60vh;
  overflow-y: auto;
  padding: 0;
}

.form-tab {
  width: 100%;
}

.form-section {
  margin-bottom: 32px;
}

.form-section:last-child {
  margin-bottom: 0;
}

.section-header {
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f3f4f6;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.section-title::before {
  content: '';
  width: 4px;
  height: 18px;
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
  border-radius: 2px;
}

.section-body {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
  align-items: start;
}

.form-column {
  display: flex;
  flex-direction: column;
  gap: 18px;
  min-width: 0;
  overflow: hidden;
}

.form-field {
  width: 100%;
}

.field-content {
  width: 100%;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  padding-top: 16px;
  border-top: 1px solid #f3f4f6;
  margin-top: 24px;
}

/* 内联编辑样式 */
.inline-edit-input {
  width: 100%;
  border: 1px solid #3b82f6;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 13px;
  background: #ffffff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.cell-display {
  display: block;
  width: 100%;
  min-height: 20px;
  padding: 2px 4px;
  word-break: break-word;
}

.editable-cell {
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s ease;
}

.editable-cell:hover {
  background-color: #f3f4f6;
  border: 1px dashed #d1d5db;
  padding: 1px 3px;
}
</style>


