<template>
  <div class="sub-table-container">
    <div class="table-header">
      <h3 style="color:blue">{{ 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="vxe-icon-fullscreen"
          @click="toggleFullscreen"
          style="margin: 0 5px;"
        >{{ isFullscreen ? '退出全屏' : '全屏' }}
      </vxe-button>

      <a-radio-group v-model:value="curColnum" style="margin-left: 20px;">
          <a-radio-button value=1>1</a-radio-button>
          <a-radio-button value=2>2</a-radio-button>
          <a-radio-button value=3>3</a-radio-button>
          <a-radio-button value=4>4</a-radio-button>
          <a-radio-button value=5>5</a-radio-button>
          <a-radio-button value=6>6</a-radio-button>
        </a-radio-group>
      </div>
    </div>
    
    <!-- 多表格实现列折行 -->
    <div class="multi-table-wrapper" v-for="(chunk, chunkIndex) in columnChunks" :key="chunkIndex">
      <vxe-table
        border
        :ref="`tableRef${chunkIndex}`"
        :data="tableData"
        :columns="getColumnsForChunk(chunk, chunkIndex)"
        :column-config="{ resizable: true }"
        :row-config="{ keyField: 'id', isCurrent: true, isHover: true,resizable:true}"
        :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }"
        auto-resize
        :header-cell-style="{ color: 'blue' }"
      >

      <template #empty>
        <vxe-button mode="text" icon="vxe-icon-add" @click="safeAddNewRecord">
          <div style="font-size: 14px">添加</div>
        </vxe-button>
      </template>
        <!-- 序号列只在第一行显示且跨行 -->
        <vxe-column 
          v-if="chunkIndex === 0" 
          type="seq" 
          width="60"
          fixed="left"
          row-resize
        ></vxe-column>
        
        <vxe-column
          v-for="field in chunk"
          :key="field.code"
          :field="field.code"
          :title=field.title
          min-width="150"
          :edit-render="getEditConfig(field)"
         
        >
          <template #edit="{ row }">
            <template v-if="field.formTp === 'yesno'">
              <vxe-radio-group v-model="row[field.code]">
                <vxe-radio label="是" content="是"></vxe-radio>
                <vxe-radio label="否" content="否"></vxe-radio>
              </vxe-radio-group>
            </template>
            <template v-else-if="field.formTp === 'radio'">
              <vxe-radio-group v-model="row[field.code]">
                <vxe-radio 
                  v-for="(opt, i) in (field.options ? field.options.split('\n') : [])" 
                  :key="i" 
                  :label="opt"
                  :content="opt"
                  style="margin: 3px;"
                ></vxe-radio>
              </vxe-radio-group>
            </template>
            <template v-else-if="field.formTp === 'checkbox'">
              <vxe-checkbox-group v-model="row[field.code]">
                <vxe-checkbox
                  v-for="(opt, i) in (field.options ? field.options.split('\n') : [])"
                  :key="i"
                  :label="opt"
                  :content="opt"
                  style="margin:3px;"
                ></vxe-checkbox>
              </vxe-checkbox-group>
            </template>
            <template v-else-if="field.formTp === 'textarea'">
              <vxe-textarea 
                v-model="row[field.code]" 
                placeholder="请输入"
                :autosize="{minRows: 2, maxRows: 4}"
              ></vxe-textarea>
            </template>

            <template v-else-if="field.formTp === 'date'">
              <vxe-input 
                v-model="row[field.code]" 
                placeholder="请输入"
                type="date"
              ></vxe-input>
            </template>
            <template v-else-if="field.formTp === 'input'">
              <template v-if="field.tp === 'number'">
                <vxe-input  v-model="row[field.code]" placeholder="请输入" type="number">
                  <template #suffix>
                    <span class="unit"> {{ field.options }}</span>
                  </template>
                </vxe-input>   
              </template>
              <template v-else>
                <vxe-input  v-model="row[field.code]" placeholder="请输入" type="input"></vxe-input>
              </template>
            </template>
            <template v-else>
              <vxe-input 
                v-model="row[field.code]" 
                :type="field.formTp === 'date' ? 'date' : 'text'" 
                placeholder="请输入"
              ></vxe-input>
            </template>
          </template>
          <template #default="{ row }">
            {{ formatCellValue(row[field.code], field.formTp) }}
          </template>
        </vxe-column>
        
        <!-- 操作列只在最后一行显示且跨行 -->
        <vxe-column 
          v-if="chunkIndex === columnChunks.length - 1" 
          title="操作" 
          width="120"
          fixed="right"
        >
          <template #default="{rowIndex }">
            <vxe-button
              type="text"
              icon="vxe-icon-delete"
              @click.stop="safeRemoveRecord(rowIndex)"
            >删除</vxe-button>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
  </div>
</template>

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

interface FieldInfo {
  itemid:number
  itempid:number
  code: string
  title: string
  formTp?: string
  options?: string
  tp:number
}

const curColnum = ref(6)

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

const props = withDefaults(defineProps<Props>(), {
  columnsPerRow:6
})


const emit = defineEmits(['update:records', 'change'])

const tableData = ref<Record<string, any>[]>([])
const isFullscreen = ref(false)

// 初始化数据
watch(() => props.records, (newRecords) => {
  tableData.value = JSON.parse(JSON.stringify(newRecords))
}, { immediate: true, deep: true })

// 将列分成每行固定数量
const columnChunks = computed(() => {
  const chunks = []
  const fieldsCopy = [...props.fields]
  
  // 将字段分成每组 columnsPerRow 个
  while (fieldsCopy.length > 0) {
    chunks.push(fieldsCopy.splice(0, curColnum.value))
  }
  
  return chunks
})

// 获取每个表格块应该显示的列配置
const getColumnsForChunk = (chunk: FieldInfo[], chunkIndex: number) => {
  return chunk.map(field => ({
    itemid:field.itemid,
    field: field.code,
    title: field.title,
    minWidth: 150,
    editRender: getEditConfig(field),
    formatter: ({ cellValue }: any) => formatCellValue(cellValue, field.formTp)
  }))
}

// 获取编辑配置
const getEditConfig = (field: FieldInfo) => {
  return {
    autoselect: true,
    immediate: true
  }
}


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

// 安全添加新记录
const safeAddNewRecord = async () => {
  try {
    const newRecord: Record<string, any> = {}
    props.fields.forEach(field => {
      newRecord[field.code] = field.formTp === 'checkbox' ? [] : ''
    })
    tableData.value.unshift(newRecord)

    //emit('update:records', tableData.value)
    //emit('change')
    
    await nextTick()
  } catch (error) {
    console.error('添加记录出错:', error)
    VxeUI.modal.message({ content: '添加记录失败', status: 'error' })
  }
}

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

  try {
    tableData.value.splice(index, 1)
    emit('update:records', tableData.value)
    emit('change')
    
    await nextTick()
  } catch (error) {
    console.error('删除记录出错:', error)
    VxeUI.modal.message({ content: '删除记录失败', status: 'error' })
  }
}

// 切换全屏
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
  document.body.classList.toggle('fullscreen-table-mode', isFullscreen.value)
}

const getFormData = async () => {
  for (const key in tableData.value) {  
    tableData.value[key] = removeEmptyValues(tableData.value[key]);  
  }

  console.log(tableData.value);
  return tableData.value;
}

const removeEmptyValues = (obj) => {
  return Object.fromEntries(
    Object.entries(obj)
      .filter(([key, value]) => {
        return value !== "" && value !== "undefined" && value !== "null";
      })
      .map(([key, value]) => {
        if (Array.isArray(value)) {
          return [key, value.join(',')];
        }
        return [key, value];
      })
  );
};

defineExpose({
    getFormData,
});

// 组件卸载时恢复body样式
onMounted(() => {
  return () => {
    document.body.classList.remove('fullscreen-table-mode')
  }
})
</script>

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

.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background-color: #fafafa;
  border-bottom: 1px solid #e8e8e8;
  position: sticky;
  top: 0;
  z-index: 10;
}

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

.multi-table-wrapper {
  margin-bottom: 20px;
}

.multi-table-wrapper:last-child {
  margin-bottom: 0;
}

.vxe-table {
  width: 100%;
  margin-bottom: 0;
}

.vxe-button.type--text {
  padding: 0 5px;
}

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

.vxe-radio .vxe-radio--label,
.vxe-checkbox .vxe-checkbox--label {
  margin-left: 5px;
}

/* 全屏模式样式 */
.fullscreen-table-mode .sub-table-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  background: white;
  margin: 0;
  padding: 20px;
  overflow: auto;
}

.fullscreen-table-mode .table-header {
  position: static;
}

.fullscreen-table-mode .multi-table-wrapper {
  margin-bottom: 30px;
}
</style>

<style>
/* 全局全屏样式 */
.fullscreen-table-mode {
  overflow: hidden;
}
</style>