<template>
  <div class="sub-table-container" :class="{ 'fullscreen-mode': isFullscreen }">
    <div class="sub-table-header">
      <h3>{{ title }}</h3>
      <div class="action-buttons">
        <vxe-button
          type="text"
          icon="vxe-icon-add"
          @click="safeAddNewRecord"
          style="margin: 0 5px;"
        >新增记录</vxe-button>
        <vxe-button
          type="text"
          :icon="isFullscreen ? 'vxe-icon-minimize' : 'vxe-icon-fullscreen'"
          @click="toggleFullscreen"
          style="margin: 0 5px;"
        >{{ isFullscreen ? '退出全屏' : '全屏' }}</vxe-button>
      </div>
    </div>
    
    <div class="table-wrapper" ref="tableWrapper">
      <vxe-table
        border
        ref="tableRef"
        :data="transposedData"
        :column-config="{ resizable: true }"
        :row-config="{ keyField: 'fieldCode' }"
        :edit-config="{ trigger: 'manual', mode: 'cell', showStatus: true }"
        :key="tableKey"
        :height="isFullscreen ? 'auto' : undefined"
        auto-resize
      >
        <!-- 字段名称列 -->
        <vxe-column field="fieldName" title="项目" width="250" fixed="left"></vxe-column>
        
        <!-- 动态生成记录列 -->
        <vxe-column
          v-for="(record, index) in internalRecords"
          :key="`record_${index}_${tableKey}`"
          :field="`record_${index}`"
          :title="`记录 ${index + 1}`"
          :edit-render="{}"
        >
          <template #header>
            <div style="display: flex; align-items: center; justify-content: space-between;">
              <span>记录 {{ index + 1 }}</span>
              <vxe-button
                type="text"
                icon="vxe-icon-delete"
                @click.stop="safeRemoveRecord(index)"
                style="padding: 0 3px;"
              ></vxe-button>
            </div>
          </template>
          <template #edit="{ row }">
            <template v-if="row.fieldType === 'yesno'">
              <vxe-radio-group v-model="internalRecords[index][row.fieldCode]">
                <vxe-radio label="是" content="是"></vxe-radio>
                <vxe-radio label="否" content="否"></vxe-radio>
              </vxe-radio-group>
            </template>
            <template v-else-if="row.fieldType === 'radio'">
              <vxe-radio-group v-model="internalRecords[index][row.fieldCode]">
                <vxe-radio 
                  v-for="(opt, i) in row.fieldOptions" 
                  :key="i" 
                  :label="opt"
                  :content="opt"
                  style="margin: 0 10px;"
                ></vxe-radio>
              </vxe-radio-group>
            </template>
            <template v-else-if="row.fieldType === 'checkbox'">
              <vxe-checkbox-group v-model="internalRecords[index][row.fieldCode]">
                <vxe-checkbox
                  v-for="(opt, i) in row.fieldOptions"
                  :key="i"
                  :label="opt"
                  :content="opt"
                ></vxe-checkbox>
              </vxe-checkbox-group>
            </template>
            <template v-else-if="row.fieldType === 'textarea'">
              <vxe-input 
                v-model="internalRecords[index][row.fieldCode]" 
                placeholder="请输入"
                :autosize="{minRows: 2, maxRows: 4}"
              ></vxe-input>
            </template>
            <template v-else>
              <vxe-input 
                v-model="internalRecords[index][row.fieldCode]" 
                :type="row.fieldType === 'date' ? 'date' : 'text'" 
                placeholder="请输入"
              ></vxe-input>
            </template>
          </template>
          <template #default="{ row }">
            {{ formatCellValue(internalRecords[index][row.fieldCode], row.fieldType) }}
          </template>
        </vxe-column>
      </vxe-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, nextTick, watch, onMounted, onUnmounted } from 'vue'
import { VxeTableInstance } from 'vxe-table'

interface FieldInfo {
  code: string
  title: string
  formTp?: string
  options?: string
}

interface Props {
  title: string
  records: Record<string, any>[]
  fields: FieldInfo[]
}

const props = defineProps<Props>()
const emit = defineEmits(['update:records', 'change'])

const tableRef = ref<VxeTableInstance>()
const tableWrapper = ref<HTMLElement>()
const internalRecords = ref<Record<string, any>[]>([])
const tableKey = ref(0)
const isFullscreen = ref(false)
const originalStyle = ref({
  position: '',
  zIndex: '',
  width: '',
  height: '',
  top: '',
  left: ''
})

// 初始化内部记录
watch(() => props.records, (newRecords) => {
  internalRecords.value = JSON.parse(JSON.stringify(newRecords))
}, { immediate: true, deep: true })

// 转换数据结构为行列反转格式
const transposedData = computed(() => {
  return props.fields.map(field => ({
    fieldName: field.title,
    fieldCode: field.code,
    fieldType: field.formTp || 'input',
    fieldOptions: field.options ? field.options.split('\n') : []
  }))
})

// 切换全屏状态
const toggleFullscreen = () => {
  if (!tableWrapper.value) return

  if (!isFullscreen.value) {
    // 进入全屏
    originalStyle.value = {
      position: tableWrapper.value.style.position,
      zIndex: tableWrapper.value.style.zIndex,
      width: tableWrapper.value.style.width,
      height: tableWrapper.value.style.height,
      top: tableWrapper.value.style.top,
      left: tableWrapper.value.style.left
    }

    tableWrapper.value.style.position = 'fixed'
    tableWrapper.value.style.zIndex = '9999'
    tableWrapper.value.style.width = '100vw'
    tableWrapper.value.style.height = '100vh'
    tableWrapper.value.style.top = '0'
    tableWrapper.value.style.left = '0'
  } else {
    // 退出全屏
    tableWrapper.value.style.position = originalStyle.value.position
    tableWrapper.value.style.zIndex = originalStyle.value.zIndex
    tableWrapper.value.style.width = originalStyle.value.width
    tableWrapper.value.style.height = originalStyle.value.height
    tableWrapper.value.style.top = originalStyle.value.top
    tableWrapper.value.style.left = originalStyle.value.left
  }

  isFullscreen.value = !isFullscreen.value
  tableKey.value += 1 // 强制重新渲染表格

  // 调整表格大小
  nextTick(() => {
    tableRef.value?.syncScroll()
  })
}

// 安全添加新记录
const safeAddNewRecord = async () => {
  try {
    const newRecord: Record<string, any> = {}
    props.fields.forEach(field => {
      newRecord[field.code] = field.formTp === 'checkbox' ? [] : 
                            field.formTp === 'yesno' ? '是' : ''
    })
    
    internalRecords.value = [newRecord, ...internalRecords.value]
    emit('update:records', internalRecords.value)
    
    // 强制重新渲染表格
    tableKey.value += 1
    
    await nextTick()
    await nextTick()
    
    // 激活编辑状态
    if (tableRef.value) {
      const columns = tableRef.value.getColumns()
      if (columns.length > 1) {
        transposedData.value.forEach(row => {
          tableRef.value?.setEditCell(row, columns[1].property)
        })
      }
    }
  } catch (error) {
    console.error('添加记录出错:', error)
  }
}

// 安全删除记录
const safeRemoveRecord = async (index: number) => {
  if (internalRecords.value.length <= 1) {
    VxeUI.modal.message({ content: '至少保留一条记录', status: 'warning' })
    return
  }

  try {
    internalRecords.value.splice(index, 1)
    emit('update:records', internalRecords.value)
    
    // 强制重新渲染表格
    tableKey.value += 1
    
    await nextTick()
  } catch (error) {
    console.error('删除记录出错:', error)
  }
}

// 格式化单元格显示值
const formatCellValue = (value: any, fieldType: string) => {
  if (fieldType === 'checkbox' && Array.isArray(value)) {
    return value.join(', ')
  }
  return value || ''
}

// 处理ESC键退出全屏
const handleKeyDown = (e: KeyboardEvent) => {
  if (e.key === 'Escape' && isFullscreen.value) {
    toggleFullscreen()
  }
}

// 添加键盘事件监听
onMounted(() => {
  window.addEventListener('keydown', handleKeyDown)
})

// 移除键盘事件监听
onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown)
  // 确保退出全屏
  if (isFullscreen.value && tableWrapper.value) {
    tableWrapper.value.style.position = originalStyle.value.position
    tableWrapper.value.style.zIndex = originalStyle.value.zIndex
    tableWrapper.value.style.width = originalStyle.value.width
    tableWrapper.value.style.height = originalStyle.value.height
    tableWrapper.value.style.top = originalStyle.value.top
    tableWrapper.value.style.left = originalStyle.value.left
  }
})
</script>

<style scoped>
.sub-table-container {
  margin: 10px 0;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  padding: 10px;
  position: relative;
}

.sub-table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 0 10px;
}

.action-buttons {
  display: flex;
  align-items: center;
}

.table-wrapper {
  overflow: auto;
  max-height: 600px;
}

.fullscreen-mode {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 9998;
  background: white;
  padding: 20px;
}

.fullscreen-mode .table-wrapper {
  max-height: calc(100vh - 60px);
}

.vxe-radio,
.vxe-checkbox {
  margin-right: 15px;
}

.vxe-radio .vxe-radio--label,
.vxe-checkbox .vxe-checkbox--label {
  margin-left: 5px;
}
</style>