<template>
  <div class="table-container">
    <div class="sub-table-container">
      <div class="table-wrapper">
        <vxe-grid
          border
          ref="gridRef"
          :data="transposedData"
          :columns="gridColumns"
          :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }"
          :key="tableKey"
          auto-resize
          :row-config="{ keyField: 'fieldCode', isHover: true }"
          :column-config="{ resizable: true }"

          :toolbar-Config ="{
            refresh: true,
            zoom: true,
            custom: true,
            export: true,
            print: false,
            slots: {
              buttons: 'toolbar_buttons',
            },
          }"
        >

        <template #toolbar_buttons>
          {{title}}
          <vxe-button  type="text" icon="vxe-icon-add" @click="safeAddNewRecord" style="margin: 0 5px;">新增记录</vxe-button>
        </template>

          <!-- 项目名称列 -->
          <template #fieldName_default="{ row }">
            <span>{{ row.fieldName }}</span>
          </template>
          
          <!-- 动态生成每列的默认显示模板 -->
          <!-- <template v-for="(_, recordIndex) in internalRecords" #[`record_${recordIndex}_default`]="{ row }">
            <span :key="`default_${recordIndex}`">
              {{ formatCellValue(internalRecords[recordIndex][row.fieldCode], row.fieldType) }}
            </span>
          </template> -->
          
          <!-- 动态生成每列的编辑模板 -->
          <template v-for="(_, recordIndex) in internalRecords" #[`record_${recordIndex}_default`]="{ row }">
            <div :key="`edit_${recordIndex}`" class="edit-cell-container">
              <template v-if="row.fieldType === 'yesno'">
                <vxe-radio-group v-model="internalRecords[recordIndex][row.fieldCode]">
                  <vxe-radio label="是" content="是"></vxe-radio>
                  <vxe-radio label="否" content="否"></vxe-radio>
                </vxe-radio-group>
                <div v-if="internalRecords[recordIndex][row.fieldCode]" class="dropdown-content" style="margin:10px">
                  <template v-for="(opt, i) in row.fieldOptions" :key="i">
                    <template v-if="opt.label === internalRecords[recordIndex][row.fieldCode]">
                      <template v-if="opt.extraFields">
                        <div 
                          v-for="(extraObject, extraIndex) in opt.extraFields" 
                          :key="`extra-${extraIndex}`" 
                          class="extra-field"
                        >
                          <span class="extra-label">{{ extraObject.label }}：</span>
                          <component 
                            :is="getExtraFieldComponent(extraObject.formType)"
                            v-model="internalRecords[recordIndex][extraObject.field]" 
                            :options="extraObject.options"
                            :type="extraObject.formType === 'number' ? 'number' : undefined"
                            class="extra-input"
                          />
                          <span v-if="extraObject.extraUnit" class="unit">{{ extraObject.unit }}</span>
                        </div>
                      </template>
                    </template>
                  </template>
                </div>
              </template>
             
              <template v-else-if="row.fieldType === 'select'">
                <div class="dropdown-radio-group">
                  <vxe-select
                    v-model="internalRecords[recordIndex][row.fieldCode]"
                    placeholder="请选择"
                    clearable
                    @change="handleDropdownChange(row, recordIndex)"
                  >
                    <vxe-option
                      v-for="(opt, i) in row.fieldOptions"
                      :key="i"
                      :value="opt.label"
                      :label="opt.label"
                    ></vxe-option>
                  </vxe-select>
                  
                  <div 
                    v-if="internalRecords[recordIndex][row.fieldCode]"
                    class="dropdown-content"
                  >
                    <template v-for="(opt, i) in row.fieldOptions" :key="i">
                      <template v-if="opt.label === internalRecords[recordIndex][row.fieldCode]">
                        <template v-if="opt.extraFields">
                          <div 
                            v-for="(extraObject, extraIndex) in opt.extraFields" 
                            :key="`extra-${extraIndex}`" 
                            class="extra-field"
                          >
                            <span class="extra-label">{{ extraObject.label }}: </span>
                            <component 
                              :is="getExtraFieldComponent(extraObject.formType)"
                              v-model="internalRecords[recordIndex][extraObject.field]" 
                              :options="extraObject.options"
                              :type="extraObject.formType === 'number' ? 'number' : undefined"
                              class="extra-input"
                            />
                            <span v-if="extraObject.extraUnit" class="unit">{{ extraObject.unit }}</span>
                          </div>
                        </template>
                      </template>
                    </template>
                  </div>
                </div>
              </template>

              <template v-else-if="row.fieldType === 'radio-group'">
                  <vxe-radio-group v-model="internalRecords[recordIndex][row.fieldCode]" class="inline-radio-group">
                    <vxe-radio 
                      v-for="(opt, i) in row.fieldOptions" 
                      :key="i" 
                      :label="opt.label"
                      class="inline-radio-option"
                    >
                      <div class="inline-option-content">
                        <span class="inline-main-label">{{ opt.label }}</span>
                        
                        <template v-if="opt.extraField">
                          <span class="inline-extra-label">{{ opt.extraLabel }}</span>
                          <component 
                            :is="getExtraFieldComponent(opt.extraFormType)"
                            v-model="internalRecords[recordIndex][opt.extraField]" 
                            :options="opt.extraOptions"
                            :type="opt.extraFormType === 'number' ? 'number' : undefined"
                            class="inline-extra-input"
                          />
                          <span v-if="opt.extraUnit" class="inline-unit">{{ opt.extraUnit }}</span>
                        </template>
                        
                        <template v-else-if="opt.extraFields">
                          <template v-for="(extraObject, extraIndex) in opt.extraFields" :key="`extra-${extraIndex}`">
                            <span class="inline-extra-label">{{ extraObject.label }}: </span>
                            <component 
                              :is="getExtraFieldComponent(extraObject.formType)"
                              v-model="internalRecords[recordIndex][extraObject.field]" 
                              :options="extraObject.options"
                              :type="extraObject.formType === 'number' ? 'number' : undefined"
                              class="inline-extra-input"
                            />
                            <span v-if="extraObject.extraUnit" class="inline-unit">{{ extraObject.unit }}</span>
                          </template>
                        </template>
                      </div>
                    </vxe-radio>
                  </vxe-radio-group>
              </template>

              <template v-else-if="row.fieldType === 'checkbox-group'">
                <vxe-checkbox-group v-model="internalRecords[recordIndex][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-textarea
                  v-model="internalRecords[recordIndex][row.fieldCode]" 
                  placeholder="请输入"
                  :autosize="{minRows: 2, maxRows: 4}"
                  :rows="row.rows||3"
                ></vxe-textarea>
              </template>

              <template v-else-if="row.fieldType === 'combinaform'">
                <div v-for="(item,itemInd) in row.childs" :key="itemInd">
                  <span class="extra-label">{{ item.label }}：</span>
                  <component 
                    :is="getExtraFieldComponent(item.formType)"
                    v-model="internalRecords[recordIndex][item.field]" 
                    :options="item.options"
                    :type="item.formType === 'number' ? 'number' : undefined"
                    class="extra-input"
                  />
                  <span v-if="item.unit" class="unit">{{ item.unit }}</span>
                </div>
              </template>


              <template v-else-if="row.fieldType === 'table'">
                <div>
                  <vxe-grid v-bind="row.gridOptions" v-on="row.gridEvents"></vxe-grid>
                </div>
              </template>

              <template v-else-if="row.fieldType === 'AttachTable'">

                <AttachTable
                  title="111"
                  :records="row.gridOptions.datas"
                  :fields="row.gridOptions.columns"
                  :pcode="row.fieldCode"
                  :mergeCells="row.gridOptions.mergeCells"
                  style="margin:0px;padding:0px"
                />
              </template>



              <template v-else>
                <vxe-input 
                  v-model="internalRecords[recordIndex][row.fieldCode]" 
                  :type="row.fieldType === 'date' ? 'date' : 'text'" 
                  placeholder="请输入"
                ></vxe-input>
              </template>
            </div>
          </template>
          
          <!-- 动态生成每列的表头模板 -->
          <template v-for="(_, recordIndex) in internalRecords" #[`header_${recordIndex}`]>
            <div :key="`header_${recordIndex}`" style="display: flex; align-items: center; justify-content: space-between;">
              <span>记录 {{ recordIndex + 1 }}</span>
              <div>
                <vxe-button
                  type="text"
                  :icon="activeEditRecord === recordIndex ? 'vxe-icon-finished' : 'vxe-icon-edit'"
                  @click.stop="toggleRecordEdit(recordIndex)"
                  style="padding: 0 3px; margin-right: 5px;"
                  :title="activeEditRecord === recordIndex ? '完成编辑' : '编辑整行'"
                ></vxe-button>
                <vxe-button
                  type="text"
                  icon="vxe-icon-delete"
                  @click.stop="safeRemoveRecord(recordIndex)"
                  style="padding: 0 3px;"
                  title="删除记录"
                ></vxe-button>
              </div>
            </div>
          </template>
        </vxe-grid>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch,nextTick } from 'vue'
import { VxeGridInstance, VxeUI } from 'vxe-table'
import AttachTable from './AttachTable.vue'

interface FieldInfo {
  field: string
  name: string
  formType?: string
  options?: any[]
  childs?: Record<string, any>[]
  gridEvents?: Record<string, any>
  gridOptions?: Record<string, any>
  rowCount:number
}

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

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

const gridRef = ref<VxeGridInstance>()
const internalRecords = ref<Record<string, any>[]>([])
const tableKey = ref(0)
const activeEditRecord = ref<number | null>(null)

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

// 转换数据结构为行列反转格式
const transposedData = computed(() => {
  return props.fields.map(field => ({
    fieldName: field.name,
    fieldCode: field.field,
    fieldType: field.formType || 'input',
    fieldOptions: field.options || [],
    childs: field.childs || [],
    gridOptions: field.gridOptions || {},
    gridEvents: field.gridEvents || {},
    rowCount: field.rows || 3,
  }))
})

// 网格列配置
const gridColumns = computed(() => {
  const columns: any[] = [
    {
      field: 'fieldName',
      title: '项目',
      width: 250,
      fixed: 'left',
      slots: {
        default: 'fieldName_default'
      }
    }
  ]

  internalRecords.value.forEach((_, recordIndex) => {
    columns.push({
      field: `record_${recordIndex}`,
      title: `记录 ${recordIndex + 1}`,
      slots: {
        default: `record_${recordIndex}_default`,
        edit: `record_${recordIndex}_edit`,
        header: `header_${recordIndex}`
      },
      editRender: { name: 'input' }
    })
  })

  return columns
})

// 切换整行编辑状态
const toggleRecordEdit = (recordIndex: number) => {
  if (!gridRef.value) return

  if (activeEditRecord.value === recordIndex) {
    // 如果点击的是已编辑的行，则退出编辑
    activeEditRecord.value = null
    gridRef.value.clearEdit()
    //emit('change')
  } else {
    // 进入整行编辑模式
    activeEditRecord.value = recordIndex
    nextTick(() => {
      transposedData.value.forEach((row) => {
        const columnField = `record_${recordIndex}`
        gridRef.value?.setEditRow(row, { field: columnField })
      })
    })
  }
}
// 安全添加新记录
const safeAddNewRecord = async () => {
  try {
    const newRecord: Record<string, any> = {}
    props.fields.forEach(field => {
      newRecord[field.field] = field.formType === 'checkbox' ? [] : 
       field.formType === 'yesno' ? '是' : ''
    })
    
    internalRecords.value = [newRecord, ...internalRecords.value]
    emit('update:records', internalRecords.value)
    
    tableKey.value += 1
    
    await nextTick()
    toggleRecordEdit(0)
  } catch (error) {
    console.error('添加记录出错:', error)
    VxeUI.modal.message({ content: '添加记录失败', status: 'error' })
  }
}

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

  try {
    if (activeEditRecord.value === index) {
      activeEditRecord.value = null
    } else if (activeEditRecord.value !== null && activeEditRecord.value > index) {
      activeEditRecord.value -= 1
    }
    
    internalRecords.value.splice(index, 1)
    emit('update:records', internalRecords.value)
    emit('change')
    
    tableKey.value += 1
    
    await nextTick()
  } catch (error) {
    console.error('删除记录出错:', error)
    VxeUI.modal.message({ content: '删除记录失败', status: 'error' })
  }
}

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

// 获取额外字段组件
const getExtraFieldComponent = (type: string) => {
  switch(type) {
    case 'radio': return 'vxe-radio-group'
    case 'checkbox': return 'vxe-checkbox-group'
    case 'date': return 'vxe-input'
    case 'number': return 'vxe-input'
    default: return 'vxe-input'
  }
}

// 处理下拉选择变化
const handleDropdownChange = (row: any, recordIndex: number) => {
  const selectedOption = row.fieldOptions.find(
    (opt: any) => opt.label === internalRecords.value[recordIndex][row.fieldCode]
  )
  
  if (!selectedOption) return
  
  if (selectedOption.extraField) {
    internalRecords.value[recordIndex][selectedOption.extraField] = 
      selectedOption.extraFormType === 'checkbox' ? [] : ''
  }
  
  if (selectedOption.extraFields) {
    selectedOption.extraFields.forEach((field: any) => {
      internalRecords.value[recordIndex][field.field] = 
        field.formType === 'checkbox' ? [] : ''
    })
  }
  
  emit('change')
}
</script>


<style lang="less" scoped>


.inline-radio-group {
  display: flex;
  flex-direction: column;
  gap: 8px;

  .inline-radio-option {
    margin: 4px 0;
    display: flex;
    align-items: center;

    .inline-option-content {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 8px;
      margin-left: 8px;

      .inline-main-label {
        font-weight: 500;
        white-space: nowrap;
      }

      .inline-extra-label {
        color: #666;
        white-space: nowrap;
      }

      .inline-extra-input {
        width: auto;
        min-width: 150px;
        margin: 0;
      }

      .inline-unit {
        color: #999;
        white-space: nowrap;
      }
    }
  }

  // 调整vxe-radio默认样式
  :deep(.vxe-radio--icon) {
      margin-right: 4px;
    }
  }


 .dropdown-radio-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
  
  .vxe-select {
    width: 100%;
    max-width: 300px;
  }
  
  .dropdown-content {
    margin-top: 8px;
    padding: 12px;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    background-color: #f9f9f9;
    
    .extra-field {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .extra-label {
        min-width: 100px;
        color: #666;
      }
      .extra-input {
        flex: 1;
        max-width: 200px;
      }
      
      .unit {
        margin-left: 8px;
        color: #999;
      }
    }
  }
}

</style>
