<template>
  <div class="sub-table-container">
    <div class="sub-table-header">
      <h3>{{ title }}</h3>
      <vxe-button
        type="text"
        icon="vxe-icon-add"
        @click="addNewRecord"
        style="margin-left: 10px;"
      >新增记录</vxe-button>
    </div>
    
    <vxe-table
      :ref="(el) => setTableRef(el)"
      :data="tableData"
      border
      :column-config="{ resizable: true }"
      :row-config="{ keyField: 'id' }"
      auto-resize
      :cell-style="{ height: 'auto', padding: '8px' }"
      :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }"
      @cell-mode="handleCellMode"
    >
      <!-- 字段名称列 -->
      <vxe-column field="fieldName" title="项目" width="250" fixed="left"></vxe-column>
      
      <!-- 记录列 -->
      <vxe-column
        v-for="(record, index) in displayRecords"
        :key="index"
        :field="'value_' + index"
        :title="'记录 ' + (index + 1)"
        :edit-render="{}"
      >
        <template #header>
          <div style="display: flex; align-items: center; justify-content: space-between;">
            <span>记录 {{ index + 1 }}</span>
            <div>
              <vxe-button
                type="text"
                icon="vxe-icon-delete"
                @click.stop="removeRecord(index)"
                style="padding: 0 3px;"
              ></vxe-button>
            </div>
          </div>
        </template>
        <template #edit="{ row: subRow, column }">
          <template v-if="fieldTypes[subRow.originalCode] === 'yesno'">
            <vxe-radio-group v-model="displayRecords[index][subRow.originalCode]">
              <vxe-radio label="是">是</vxe-radio>
              <vxe-radio label="否">否</vxe-radio>
            </vxe-radio-group>
          </template>
          <template v-else-if="fieldTypes[subRow.originalCode] === 'radio'">
            <vxe-radio-group v-model="displayRecords[index][subRow.originalCode]">
              <vxe-radio 
                v-for="(opt, i) in fieldOptions[subRow.originalCode]" 
                :key="i" 
                :label="opt" 
                style="margin: 0 10px;"
              >{{ opt }}</vxe-radio>
            </vxe-radio-group>
          </template>
          <template v-else-if="fieldTypes[subRow.originalCode] === 'checkbox'">
            <vxe-checkbox-group 
              v-model="displayRecords[index][subRow.originalCode]" 
              :options="fieldOptions[subRow.originalCode].map(opt => ({ label: opt, value: opt }))" 
            />
          </template>
          <template v-else-if="fieldTypes[subRow.originalCode] === 'textarea'">
            <vxe-input 
              v-model="displayRecords[index][subRow.originalCode]" 
              type="textarea" 
              placeholder="请输入"
              :autosize="{minRows: 2, maxRows: 4}"
            ></vxe-input>
          </template>
          <template v-else>
            <vxe-input 
              v-model="displayRecords[index][subRow.originalCode]" 
              :type="fieldTypes[subRow.originalCode] === 'date' ? 'date' : 'text'" 
              placeholder="请输入"
            ></vxe-input>
          </template>
        </template>
        <template #default="{ row: subRow, column }">
          <template v-if="fieldTypes[subRow.originalCode] === 'checkbox'">
            {{ Array.isArray(displayRecords[index][subRow.originalCode]) ? 
               displayRecords[index][subRow.originalCode].join(', ') : 
               displayRecords[index][subRow.originalCode] }}
          </template>
          <template v-else>
            {{ displayRecords[index][subRow.originalCode] }}
          </template>
        </template>
      </vxe-column>
    </vxe-table>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, nextTick,watch } from 'vue'
import { VxeTableInstance,VxeUI } 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 displayRecords = ref<Record<string, any>[]>([])
const lastAddedIndex = ref<number | null>(null)

// 生成字段类型映射
const fieldTypes = computed(() => {
  const types: Record<string, string> = {}
  props.fields.forEach(field => {
    types[field.code] = field.formTp || 'input'
  })
  return types
})

// 生成字段选项映射
const fieldOptions = computed(() => {
  const options: Record<string, string[]> = {}
  props.fields.forEach(field => {
    if (field.options) {
      options[field.code] = field.options.split('\n')
    } else {
      options[field.code] = []
    }
  })
  return options
})

const setTableRef = (el: any) => {
  if (el) {
    tableRef.value = el
  }
}

// 计算表格数据（行列转换）
const tableData = computed(() => {
  return props.fields.map(field => {
    const rowData: Record<string, any> = {
      fieldName: field.title,
      originalCode: field.code
    }
    
    displayRecords.value.forEach((record, index) => {
      rowData[`value_${index}`] = record[field.code] || 
        (field.formTp === 'checkbox' ? [] : 
         field.formTp === 'yesno' ? '是' : '')
    })
    
    return rowData
  })
})

// 更新显示记录
const updateDisplayRecords = () => {
  // 新记录放在最前面
  const newRecords = [...props.records]
  displayRecords.value = newRecords
}

// 添加新记录
const addNewRecord = async () => {
  const newRecord: Record<string, any> = { _isNew: true }
  props.fields.forEach(field => {
    newRecord[field.code] = field.formTp === 'checkbox' ? [] : 
                           field.formTp === 'yesno' ? '是' : ''
  })
  
  // 新记录添加到数组开头
  const newRecords = [newRecord, ...props.records]
  lastAddedIndex.value = 0
  
  emit('update:records', newRecords)
  emit('change')
  
  await nextTick()
  
  // 自动激活第一个可编辑单元格
  if (tableRef.value && props.fields.length > 0) {
    tableRef.value.setActiveCell(
      tableData.value[0], 
      'value_0'
    )
  }
}

// 处理单元格模式
const handleCellMode = ({ row, column }: { row: any; column: any }) => {
  // 如果是新记录，保持编辑状态
  const recordIndex = parseInt(column.property.replace('value_', ''))
  if (lastAddedIndex.value !== null && recordIndex === lastAddedIndex.value) {
    return 'edit'
  }
  return 'default'
}

// 删除记录
const removeRecord = (index: number) => {
  if (props.records.length > 1) {
    const newRecords = [...props.records]
    newRecords.splice(index, 1)
    
    // 更新最后添加的索引
    if (lastAddedIndex.value !== null) {
      if (lastAddedIndex.value === index) {
        lastAddedIndex.value = null
      } else if (lastAddedIndex.value > index) {
        lastAddedIndex.value = lastAddedIndex.value - 1
      }
    }
    
    emit('update:records', newRecords)
    emit('change')
  } else {
    VxeUI.modal.message({ content: '至少保留一条记录', status: 'warning' })
  }
}

// 监听records变化
watch(() => props.records, () => {
  updateDisplayRecords()
}, { immediate: true, deep: true })

defineExpose({
  getTableRef: () => tableRef.value
})
</script>

<style scoped>
/* 原有样式保持不变 */
.sub-table-container {
  margin: 10px 0;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  padding: 10px;
}

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

.sub-table-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

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

.vxe-textarea {
  width: 100%;
}

/* 新行高亮样式 */
.vxe-table .vxe-body--column.col--new {
  background-color: #f0f9ff;
}
</style>