<template>
  <div class="sub-table-container">
    <div class="table-header">
      <h3 style="color:">{{ 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;">
          <template v-for="i in 6" :key="i">
            <a-radio-button :value="i">{{ i }}</a-radio-button>
          </template>
          <a-radio-button :value="props.fields.length">全部</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="el => setTableRef(el, 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
         keep-source
        :header-cell-style="{ color: 'black' }"
      >
        <template #empty>
          <vxe-button mode="text" icon="vxe-icon-add" @click="safeAddNewRecord">
            <div style="font-size: 12px">添加</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.field" 
          :field="field.field" 
          :title="field.name"  
          min-width="150" 

          :showHeaderOverflow="true"
        >
          <template #default="{ row,rowIndex }">
            <template v-if="field.formType === 'yesno'">
              <vxe-radio-group v-model="row[field.field]">
                <vxe-radio label="是" content="是"></vxe-radio>
                <vxe-radio label="否" content="否"></vxe-radio>
              </vxe-radio-group>
              <template v-if="field.otherOption&&row[field.field]=='是'">
                <span>{{field.otherLabel}}：</span>
                  <vxe-input v-model="row[field.otherField]"  style="width: 400px;">
                  </vxe-input>
              </template>
            </template>
            <template v-else-if="field.formType === 'radio-group'">
              <vxe-radio-group v-model="row[field.field]">
                <vxe-radio 
                  v-for="(opt, i) in (field.options||[])" 
                  :key="i" 
                  :label="opt"
                  :content="opt"
                  style="margin: 3px;"
                ></vxe-radio>
              </vxe-radio-group>
              <template v-if="field.otherOption&&row[field.field]=='其他'">
                  <!-- <span>其他： </span> -->
                  <vxe-input v-model="row[field.otherField]" placeholder="请输入其他" style="width: 300px;">
                  </vxe-input>
              </template>
            </template>

            <template v-else-if="field.formType === 'AttachTable'">
              <AttachTable
                title=""
                :records="field.gridOptions.datas"
                :fields="field.gridOptions.columns"
                :pcode="field.field"
                :mergeCells="field.gridOptions.mergeCells"
                :showHeader="field.gridOptions.showHeader"
                :ref="el => setAttchTableRefs(el, field.field,rowIndex)"
                style="margin:0px;padding:0px"
              />
            </template>

            <template v-else-if="field.formType === 'radio-group-extraFields'">
              <vxe-radio-group v-model="row[field.field]">
                <vxe-radio 
                  v-for="(item, i) in (field.options||[])" 
                  :key="i" 
                  :label="item.label"
                  :content="item.label"
                  style="margin: 3px;"
                ></vxe-radio>
              </vxe-radio-group>
              <template v-if="field.otherOption&&row[field.field]=='其他'">
                  <!-- <span>其他： </span> -->
                  <vxe-input v-model="row[field.otherField]" placeholder="请输入其他" style="width:300px;">
                  </vxe-input>
              </template>

              <template v-if="field.extraFields">
                <template v-for="(ccopt,ccind) in field.extraFields[row[field.field]]" :key="ccind">
                      <span style="margin-left:20px">{{  ccopt.label }}: </span>
                      <component 
                        :is="getExtraFieldComponent(ccopt.formType)"
                        v-model="row[ccopt.field]" 
                        :options="ccopt.options"
                        :type="ccopt.formType"
                        class="extra-input"
                        :style="{width:ccopt.width}"
                        size="small"
                      />
                      <template
                        v-if="
                          ccopt.otherOption &&
                          (
                            (ccopt.formType === 'radio' && row[ccopt.field] === '其他') ||
                            (ccopt.formType === 'checkbox' && Array.isArray(row[ccopt.field]) && row[ccopt.field].includes('其他'))
                          )
                        "
                      >
                          <!-- <span>其他： </span> -->
                          <vxe-input v-model="row[ccopt.otherField]" placeholder="请输入其他" style="width: 300px;">
                          </vxe-input>
                      </template>
                      <span class="unit"> {{ ccopt.unit }}</span>
                </template>
              </template>
            </template>
            <template v-else-if="field.formType === 'checkbox-group'">
              <vxe-checkbox-group v-model="row[field.field]">
                <vxe-checkbox
                  v-for="(opt, i) in field.options"
                  :key="i"
                  :label="opt"
                  :value="opt"
                  :content="opt"
                ></vxe-checkbox>
              </vxe-checkbox-group>
              <template v-if="field.otherField&&row[field.field]?.includes('其他')">
                  <vxe-input v-model="row[field.otherField]" placeholder="请输入其他" style="width: 300px; margin-left: 4px;">
                  </vxe-input>
              </template>
              <template v-if="field.extraFields">
                <template v-for="(ccopts,ccind) in field.extraFields" :key="ccind">
                    <template v-for="(ccopt,ind) in ccopts" :key="ind">
                      <br/>
                      <span style="margin-left:20px">{{ ccopt.label }}: </span>
                      <component 
                        :is="getExtraFieldComponent(ccopt.formType)"
                        v-model="row[ccopt.field]" 
                        :options="ccopt.options"
                        :type="ccopt.formType"
                        class="extra-input"
                        :style="{width:ccopt.width}"
                        size="small"
                      />
                      <span class="unit"> {{ ccopt.unit }}</span>
                    </template>
                </template>
              </template>
            </template>

            <template v-else-if="field.formType === 'combinaform'">
             
                <div v-for="(item,itemInd) in field.childs" :key="itemInd">
                  <span class="extra-label">{{ item.label }}：</span>
                  <component 
                    :is="getExtraFieldComponent(item.formType)"
                    v-model="row[item.field]" 
                    :options="item.options"
                    :type="item.formType"
                    class="extra-input"
                  />
                  <template v-if="item.formType==='checkbox'|| item.formType==='radio'">
                    <template
                      v-if="
                        item.otherOption &&
                        (
                          (item.formType === 'radio' && row[item.field] === '其他') ||
                          (item.formType === 'checkbox' && Array.isArray(row[item.field]) && row[item.field].includes('其他'))
                        )
                      "
                    >
                      <span class="extra-label">{{ item.otherLabel}}： </span>
                      <vxe-input v-model="row[item.otherField]" placeholder="请输入" style="width: 300px;">
                      </vxe-input>
                    </template>
                  </template>
                  <span v-if="item.unit" class="unit">{{ item.unit }}</span>
                </div>
            </template>

            <template v-else-if="field.formType === 'select'">
                <div class="dropdown-radio-group">
                  <vxe-radio-group
                    v-model="row[field.field]"
                    clearable
                  >
                    <vxe-radio
                      v-for="(opt, i) in field.options"
                      :key="i"
                      :content="opt.label"
                      :label="opt.label"
                    ></vxe-radio>
                  </vxe-radio-group>
                  
                  <div 
                    v-if="row[field.field]" class="dropdown-content"
                  >
                    <template v-for="(opt, i) in field.options" :key="i">
                      <template v-if="opt.label === row[field.field]">
                        <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="row[extraObject.field]" 
                              :options="extraObject.options"
                              :type="extraObject.formType === 'number' ? 'number' : undefined"
                              class="extra-input"
                            />
                            <template
                              v-if="
                                extraObject.otherOption &&
                                (
                                  (extraObject.formType === 'radio' && row[extraObject.field] === '其他') ||
                                  (extraObject.formType === 'checkbox' && Array.isArray(row[extraObject.field]) && row[extraObject.field].includes('其他'))
                                )
                              "
                            >
                              <!-- <span>其他： </span> -->
                              <vxe-input
                                v-model="row[extraObject.otherField]"
                                placeholder="请输入其他"
                                style="width: 300px; margin-left: 4px;"
                              />
                            </template>
                            <span v-if="extraObject.extraUnit" class="unit">{{ extraObject.unit }}</span>
                          </div>
                        </template>
                      </template>
                    </template>
                  </div>
                </div>
              </template>

            <template v-else-if="field.formType === 'textarea'">
              <vxe-textarea 
                v-model="row[field.field]" 
                placeholder="请输入"
                :autosize="{minRows: 2, maxRows: 4}"
              ></vxe-textarea>
            </template>
            <template v-else-if="field.formType === 'number'">
              <vxe-input v-model="row[field.field]" placeholder="请输入" type="number">
                <template #suffix>
                  <span class="unit"> {{ field.unit }}</span>
                </template>
              </vxe-input>   
            </template>
            <template v-else-if="field.formType === 'date'">
              <vxe-input v-model="row[field.field]" placeholder="请输入" type="date"/>
            </template>
             <template v-else-if="field.formType === 'table'">
                <div>
                  <vxe-grid v-bind="field.gridOptions" v-on="gridEvents" :ref="el => setGridRef(el, field.field)"></vxe-grid>
                </div>
              </template>
            <template v-else-if="row.formType === 'anyField'">
                <component 
                  :is="getExtraFieldComponent(field.formType)"
                  v-model="row[field.field]"
                  :options="field.options"
                  :type="field.formType"
                  class="extra-input"
                />
               
            </template>
            <template v-else>
              <vxe-input v-model="row[field.field]" style="width:300px;">  </vxe-input>
            </template>
          </template>
          <!-- <template #default="{ row }">
            <template v-if="field.formType==='combinaform'"> 
              <div v-for="(item,itemInd) in field.childs" :key="itemInd">
                  <span class="extra-label">{{ item.label }}：</span>
                  <span>{{ row[item.field] }}</span>
                  <span v-if="item.unit" class="unit">{{ item.unit }}</span>
              </div>
            </template>
            <template v-else> 
              {{ formatCellValue(row[field.field], field.formType) }}
            </template>
          </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 { ref, computed, nextTick, watch, onMounted, defineExpose } from 'vue'
import { VxeUI,VxeGridListeners } from 'vxe-table'
import AttachTable from './AttachTable.vue'

interface FieldInfo {
  itemid: number
  itempid: number
  pcode:number
  code: string
  title: string
  formType: string
  options?: string
  tp?: string
  unit?: string
  field: string
  name?: string
}

const props = defineProps({
  title: String,
  pcode:String,
  records: {
    type: Array as () => Record<string, any>[],
    default: () => [{}]
  },
  fields: {
    type: Array as () => FieldInfo[],
    required: true
  },
  columnsPerRow: {
    type: Number,
    default: undefined
  }
})

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

const curColnum = ref(props.columnsPerRow||props.fields.length)
const tableData = ref<Record<string, any>[]>([])
const isFullscreen = ref(false)
const tableRefs = ref<any[]>([])

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

// 设置表格引用
const setTableRef = (el: any, index: number) => {
  if (el) {
    tableRefs.value[index] = el
  }
}

// 将列分成每行固定数量
const columnChunks = computed(() => {
  const chunks = []
  const fieldsCopy = props.fields.map(field => ({
    ...field,
    field: field.field,
    name: field.name,
    formType: field.formType
  }))
  
  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.field,
    title: field.title,
    minWidth: 150,
    editRender: getEditConfig(field),
    formatter: ({ cellValue }: any) => formatCellValue(cellValue, field.formType)
  }))
}

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

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


const safeAddNewRecord = async () => {
  try {
    const newRecord: Record<string, any> = {}
    props.fields.forEach(field => {
      if (field.formType === 'table') {
        newRecord[field.field] = []
      } else {
        newRecord[field.field] = field.formType === 'checkbox' ? [] : ''
      }
    })
    tableData.value.unshift(newRecord)
    
    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 removeEmptyValues = (obj: Record<string, any>) => {
  return Object.fromEntries(
    Object.entries(obj)
      .filter(([_, value]) => {
        return value !== "" && value !== "undefined" && value !== "null" && value !== null && value !== undefined
      })
      .map(([key, value]) => {
        if (Array.isArray(value)) {
          return [key, value.join(',')]
        }
        return [key, value]
      })
  )
}


const getFormData = () => {

  const cleanedData = tableData.value.map((row) => {
    const cleanedRow: Record<string, any> = {};
    copyNonEmpty(row,cleanedRow)
    props.fields.forEach(field => {
      if (field.formType === 'table') {
        const key = `${field.field}`;
        const gridInstance = gridRefs.value[key];  
        if (gridInstance && gridInstance.getTableData) {
          const fullDatas = gridInstance.getTableData().fullData
          const newData = fullDatas.map(({ _X_ROW_KEY, ...rest }) => rest);
          cleanedRow[field.field] = JSON.stringify(newData)
        } else {
          delete cleanedRow[field.field]
        }
      } else if(field.formType==="AttachTable") {
        for (const pcode in attchTableRefs.value) {
          const child = attchTableRefs.value[pcode]
          if (child) {
            const datas = child.getFormData()
            copyNonEmpty(datas,cleanedRow)
          }
        }
      }

    });
    return cleanedRow;
  }).filter(row => Object.keys(row).length > 0);
  

  return cleanedData;
}

const setFormData = (dataVale) => {

   tableData.value = dataVale.map((row, rowIndex) => {
     const newRow = { ...row }
     
     props.fields.forEach(field => {
       if ((field.formType === 'checkbox' || field.formType === 'checkbox-group') && newRow[field.field]) {
         if (!Array.isArray(newRow[field.field])) {
           newRow[field.field] = newRow[field.field].split(',').filter(Boolean)
         }
       }
     })
     
     return newRow
   })
   
   nextTick(() => {
     tableData.value.forEach((row, rowIndex) => {
       props.fields.forEach(field => {
         if(field.formType === 'table') {
           const fieldWithGrid = field as any;
           fieldWithGrid.gridOptions.data = JSON.parse(row[field.field] || '[]')
         } else if(field.formType === 'AttachTable') {
           const key = `${field.field}_${rowIndex}`;
           const child = attchTableRefs.value[key];
           if (child && child.setFormData) {
             const tableData: Record<string, any> = {};
             const fieldWithGrid = field as any;
             if (fieldWithGrid.gridOptions && fieldWithGrid.gridOptions.datas) {
               fieldWithGrid.gridOptions.datas.forEach((dataRow: any, dataRowIndex: number) => {
                 Object.values(dataRow).forEach((cellValue: any, cellIndex: number) => {
                   if (cellValue && typeof cellValue === 'object') {
                     if (cellValue.field) {
                       tableData[cellValue.field] = row[cellValue.field];
                     }
                     if (cellValue.extraField) {
                       tableData[cellValue.extraField] = row[cellValue.extraField];
                     }
                     if (cellValue.otherField) {
                       tableData[cellValue.otherField] = row[cellValue.otherField];
                     }
                   }
                 });
               });
             }
             child.setFormData(tableData);
           }
         } else if (field.formType === 'combinaform') {
           const fieldWithChilds = field as any;
           if (fieldWithChilds.childs && Array.isArray(fieldWithChilds.childs)) {
             fieldWithChilds.childs.forEach((child: any) => {
               if (child.formType === 'checkbox' && !Array.isArray(row[child.field])) {
                 if (row[child.field]) {
                   row[child.field] = row[child.field].split(',').filter(Boolean)
                 } else {
                   row[child.field] = []
                 }
               }
             })
           }
         }
       })
     })
   })
}


// 获取额外字段组件
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 gridEvents: VxeGridListeners = {
  toolbarButtonClick(params) {
    if (params.code === "add") {
      const fieldName = (params.button as any).field
      const fieldConfig = props.fields.find(field => field.field === fieldName)
      if (fieldConfig && fieldConfig.gridOptions) {
        const newRow: Record<string, any> = {}
        fieldConfig.gridOptions.columns.forEach((col: any) => {
          if (col.field) {
            newRow[col.field] = ''
          }
        })
        params.$grid.insert(newRow)
        const insertRows = params.$grid.getInsertRecords();
        if(insertRows.length>0) {
          const lasstRow = insertRows[insertRows.length-1]
          params.$grid.setEditRow(lasstRow)
        }
   
      }
    } else if(params.code==="delete"){
      params.$grid.removeCheckboxRow();
      
    } 
  }
}

const gridRefs = ref<Record<string, any>>({});
const setGridRef = (el: any, fieldName: string) => {
  if (el) {
    const key = `${fieldName}`; // 唯一标识（字段名 + 行索引）
    gridRefs.value[key] = el;
  }
};
const attchTableRefs = ref<Record<string, any>>({});
const setAttchTableRefs = (el: any, fieldName: string,rowIndex:number) => {
  if (el) {
    const key = `${fieldName}_${rowIndex}`;
    attchTableRefs.value[key] = el;
  }
};

function copyNonEmpty(source, target) {
  for (let key in source) {
    if (source.hasOwnProperty(key)) {
      let value = source[key];
      if (value !== null && value !== undefined && value !== '') {
        console.log(value,"value")
        if(value.indexOf("row_")>-1) continue;
        console.log(value,"value")
        target[key] = value;
      }
    }
  }
}

defineExpose({
  getFormData,
  setFormData,
})

onMounted(() => {
  return () => {
    document.body.classList.remove('fullscreen-table-mode')
  }
})
</script>
