<template>
  <div class="bank-report-table" style="height:80vh" @click="closeTooltip">
    <!-- 加载遮罩层 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner">
        <div class="spinner"></div>
        <div class="loading-text">加载中...</div>
      </div>
    </div>

    <vxe-toolbar>
      <template #buttons>
        <div style="margin:10px">
          <span style="font-weight: bold"> 填报任务：{{ queryParam?.taskName }} </span>
          <span style="font-weight: bold;margin-left:20px"> 表格：{{ queryParam?.tplCode }} {{ queryParam?.tplName }}</span>
        </div>
      </template>
      <template #tools>
        <vxe-button status="primary" icon="vxe-icon-edit" @click="handleOpenHistoryDrawer()" :disabled="loading">近5年数据填报</vxe-button>
        <vxe-button status="primary"  icon="vxe-icon-save" @click="checkData()">校验</vxe-button>
        <vxe-button status="primary"  icon="vxe-icon-save" @click="saveBatch()">保存</vxe-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      border
      ref="tableRef"
      height="auto"
      show-header-overflow
      :data="tableFormData"
      :column-config="{ resizable: true }"
      :row-config="{ resizable: true }"
      class="custom-table"
    >
      <vxe-column field="serialNumber" title="序号" width="50"></vxe-column>
      <vxe-column field="project" title="项目" width="100">
        <template #default="{ row }">
          <span style="font-weight: bold;size:20px">{{ row.project }}</span>
        </template>
      </vxe-column>
      <vxe-column field="content" title="内容" row-resize>
        <template #default="{ row }"> 
          
          <div class="content-cell">
            <template v-if="row.type === 'MultiColumnTable'">
              <MultiColumnTable
                :title="row.project"
                :records="[]"
                :fields="row.content"
                :ref="(el) => setMultiColumnTableRef(el, row.code)"
                style="margin:0px;padding:0px"
              />
            </template>
            <template v-else-if="row.type === 'AttachTable'">
              <AttachTable
                :title="row.project"
                :records="row.datas"
                :fields="row.content"
                :pcode="row.code"
                :calcSum="row.calcSum"
                :showFooter="row.showFooter"
                :ref="(el) => setAttachTableRef(el, row.code)"
                :disabled="!row.hasRight"
                style="margin:0px;padding:0px"
              />
            </template>
            <template v-else-if="row.type === 'VxeTable'">
              <MyVxeTable1
                :title="row.project"
                :data="row.data"
                :columns="row.columns"
                :pcode="row.code"
                :footerData="row.footerData"
                :showFooter="row.showFooter"
                :ref="(el) => setMyVxeTableRef(el, row.code)"
                :disabled="!row.hasRight"
                style="margin:0px;padding:0px"
              />
            </template>
            <template v-else>
              <template v-for="(item, index) in row.content" :key="index">
                <span v-if="item.type === 'text'" v-html="item.value"></span>
                <span v-else-if="item.type === 'br'"><br></span>
                <span v-else-if="item.type === 'brspace'">
                  <br>
                  <template v-for="i in item.value||1" :key="i">
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  </template>
                </span>
                
                <span v-else-if="item.type === 'radio-group'" class="radio-group">
                  <vxe-radio-group v-model="formData[row.code +'_'+ item.field]"
                    :disabled="!item.hasRight || (item.relatedFiled&&formData[row.code +'_'+ item.relatedFiled]!='是')"
                  >
                    <vxe-radio
                      v-for="(opt, optIndex) in item.options"
                      :key="optIndex"
                      :label="opt"
                      >{{ opt }}</vxe-radio
                    >
                  </vxe-radio-group>
                </span>
                <div v-else-if="item.type === 'checkbox-group'">
                  <span class="checkbox-group" >
                      <vxe-checkbox-group v-model="formData[row.code+'_'+item.field]" :disabled="!item.hasRight">
                        <vxe-checkbox v-for="(opt, optIndex) in item.options" :key="optIndex" :label="opt">
                          {{ opt }}
                          </vxe-checkbox>
                          <template  v-if="item.otherField">
                            <div style="width:100%">
                              <vxe-checkbox label="其他" :disabled="!item.hasRight">
                                其他：
                              </vxe-checkbox>
                              <vxe-input v-model="formData[row.code + '_'+ item.otherField]"  
                                :disabled="!(formData[row.code+'_'+item.field]?.indexOf('其他')>-1) || !item.hasRight"
                                style="width: 50%"
                              >
                              </vxe-input>
                            </div>
                            </template>
                      </vxe-checkbox-group>
                    </span> 
                </div>

                <div v-else-if="item.type === 'checkboxAndInput'">
                  <span style="margin-left:20px">
                      <vxe-checkbox-group v-model="formData[row.code+'_'+item.field]" :disabled="!item.hasRight">
                        <vxe-checkbox v-for="(opt, optIndex) in item.options" :key="optIndex" :label="opt" :disabled="!item.hasRight" style="margin-left: 0px;display: block;">
                          {{ opt }}
                          <vxe-input type="number" v-model="formData[row.code + '_'+ item.optionItemField[optIndex]]" :disabled="!item.hasRight"  style="width: 100px;margin: 0px;">
                          </vxe-input>
                          <span class="unit"> {{ item.optionItemUint }}</span>
                        </vxe-checkbox>
                      </vxe-checkbox-group>
                    </span> 
                </div>
                <template v-else>
                  <div class="input-wrapper">
                    <vxe-input
                      :disabled="!item.hasRight || (item.relatedFiled&&formData[row.code +'_'+ item.relatedFiled]!='是')"
                      :type="item.type"
                      v-model="formData[row.code +'_'+ item.field]"
                      size="mini"
                      class="table-input"
                      :style="item.style"
                      :status="getInputStatus(row.code, item.field)"
                      @input="handleInputChange(row.code, item.field)"
                    >
                    </vxe-input>
                    <span class="unit"> {{ item.unit }}</span>
                    <span v-if="item.hasValidFormula" class="help-icon" @click.stop="toggleTooltip(row.code, item.field)">?</span>
                    <div v-if="getInputStatus(row.code, item.field) === 'error'" class="error-tip">
                      {{ getErrorMessage(row.code, item.field) }}
                    </div>
                    <div v-if="showTooltip && hoveredKey === row.code +'_'+ item.field" class="tooltip" @click.stop>
                      {{ getValidationRule(row.code, item.field) }}
                    </div>
                  </div>
                </template>
              </template>
            </template>
          </div>
        </template>
      </vxe-column>
      <vxe-column field="remarks" title="备注" width="60">
        <template #default="{ row }"> 
            <vxe-textarea :rows="row.remarks.rows" v-model="formData[row.code+'_'+row.remarks.field]">
            </vxe-textarea>
        </template>
      </vxe-column>
    </vxe-table>

    <!-- 校验结果抽屉 -->
    <vxe-drawer
      v-model="drawerVisible"
      placement="right"
      @show="handleValidationDrawerShow"
      title="校验结果"
      width="40%"
      :footer="{ show: true }"
    >
      <template #default>
        <div class="validation-results">
          <div class="result-summary">
            <div class="summary-item">
              <span class="summary-label">校验字段数：</span>
              <span class="summary-value">{{ validationResultsList.length }}</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">通过：</span>
              <span class="summary-value success">{{ validationResultsList.filter(item => item.isValid).length }}</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">失败：</span>
              <span class="summary-value error">{{ validationResultsList.filter(item => !item.isValid).length }}</span>
            </div>
          </div>

          <div class="result-list">
            <div
              v-for="(item, index) in validationResultsList"
              :key="index"
              class="result-item"
              :class="{ success: item.isValid, error: !item.isValid }"
            >
              <div class="result-item-header">
                <span class="result-item-name">{{ item.fieldTitle }}【{{item.fieldName }}】</span>
                <span class="result-item-status" :class="{ success: item.isValid, error: !item.isValid }">
                  {{ item.isValid ? '通过' : '失败' }}
                </span>
              </div>
              <div class="result-item-content">
                <div class="result-item-formula">
                  <span class="formula-label">验证公式：</span>
                  <span class="formula-value">{{ item.formula }}</span>
                </div>
                <div class="result-item-result">
                  <span class="result-label">验证结果：</span>
                  <span class="result-value">{{ item.resultMessage }}</span>
                </div>
                <div class="result-item-values" v-if="item.fieldValues">
                  <span class="values-label">字段值：</span>
                  <pre class="values-value">{{ formatJSON(item.fieldValues) }}</pre>
                </div>
                <div class="result-item-process" v-if="item.process">
                  <span class="process-label">校验过程：</span>
                  <div class="process-content">
                    <div v-for="(step, stepIndex) in item.process" :key="stepIndex" class="process-step">
                      <span class="step-number">{{ stepIndex + 1 }}</span>
                      <span class="step-text">{{ step }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
    </vxe-drawer>
    <HistoryFillCheck ref="historyFillCheckRef" v-model="historyDrawerVisible" @closeDrawer="closeHistoryDrawer"/>
  </div>
</template>

<script lang="ts" setup>
import MultiColumnTable from '../tableComponents/MultiColumnTable.vue'
import AttachTable from '../tableComponents/AttachTable.vue'
import MyVxeTable1 from '../tableComponents/MyVxeTable.vue'
import HistoryFillCheck from './check/HistoryFillCheck.vue'

import { tableFormData } from '../../data/tb1.data';
import { ref, reactive,nextTick,onMounted,toRaw } from 'vue'
import { VxeUI,VxeToolbarInstance,VxeToolbarPropTypes } from 'vxe-table'
import { batchSaveOrUpdate, queryRecord,batchSaveOrUpdateBeforeDelete } from '../../record/BaosongTaskRecord.api'
import { queryAllTplItemForUser, findUserRightForTplItem } from '../../alloc/BaosongTaskAlloc.api'
import { allTplItems } from '../../tpl/BaosongTplItem.api'
import { getTblvalidFormula } from '../../tpl/BaosongDataValid.api'

import { useRoute } from 'vue-router';

const historyFillCheckRef = ref();
const historyDrawerVisible = ref(false);

const route = useRoute();
const tableRef = ref();
const tplItemMap = ref({});
const userAllocItems = ref([])
const validFormula = ref([])
const validationResults = ref<Record<string, string>>({})
const validationMessages = ref<Record<string, string>>({})

const formData = reactive({});
const formValues = ref<FormData[]>([])
const showTooltip = ref(false)
const hoveredKey = ref('')

// 校验结果抽屉相关
const drawerVisible = ref(false)
const validationResultsList = ref<any[]>([])

interface ValidationResult {
  fieldTitle: string
  fieldName: string
  formula: string
  isValid: boolean
  resultMessage: string
  process?: string[]
}

const queryParam = ref({
  taskId:-1,
  taskName:'',
  tplId:-1,
  tplName:'',
  tplCode:''
})

interface FormData {
  id: number | null
  taskid: number
  tplid: number
  itemid?: number
  itempid?:number
  content: string
  tplcode:string
  rind:number
}

// 初始化loading状态
const loading = ref(true)

onMounted(async ()=>{
  if (route.query.taskId) {  
    queryParam.value.taskId = Number(route.query.taskId); 
  }  
  if (route.query.taskName) {  
    queryParam.value.taskName = String(route.query.taskName);
  } 
  if (route.query.tplId) {  
  queryParam.value.tplId = Number(route.query.tplId);  
  }  
  if (route.query.tplName) {  
  queryParam.value.tplName = String(route.query.tplName); 
  } 
  if (route.query.tplCode) {  
  queryParam.value.tplCode = String(route.query.tplCode); 
  } 

  try {
    userAllocItems.value = await findUserRightForTplItem({
      tplid:queryParam.value.tplId,
      taskid:queryParam.value.taskId
    });

    validFormula.value = await getTblvalidFormula({
      tplid:queryParam.value.tplId,
    });
    
    await setFormItemRight();
    await setTplItemMap()
    await setData();
  } catch (error) {
    VxeUI.modal.message({ 
      content: `初始化页面失败: ${error.message}`, 
      status: 'error' 
    });
  } finally {
    loading.value = false
  }
})

const setFormItemRight = async () => {
    tableFormData.forEach(row => {
      if (row.content && Array.isArray(row.content)) {
          row.content.forEach(item => {
              if (item.field) {
                  let tmpKey = `${row.code}_${item.field}`;
                  item["hasRight"] = userAllocItems.value.indexOf(tmpKey)>-1
                  item["hasValidFormula"] = validFormula.value?.length > 0 && 
                    validFormula.value.some((f: any) => {
                      const formulaText = (f.formula || '').toString()
                      return formulaText.includes(item.field)
                    })
              }
          });
      }
    });
}

const saveBatch = async () => {
  try {
    const saveLoading = ref(true)
    formValues.value = []

    for (const strKey in formData) {
      const valData = formData[strKey]
      if (valData) {
        let tmpAry = strKey.split("_")
        await setFormValues(tmpAry[0],tmpAry[1],valData,1)    
      }
    }
    await getAttachTableFormData();
    await getAllMultiTableFormData()
    if (formValues.value.length > 0) {
      await batchSaveOrUpdateBeforeDelete(formValues.value)
      VxeUI.modal.message({ content: '保存成功', status: 'success' })
    } else {
      VxeUI.modal.message({ content: '没有需要保存的数据', status: 'warning' })
    }
  } catch (error) {
    VxeUI.modal.message({ content: `保存失败: ${error.message}`, status: 'error' })
  } finally {
    loading.value = false
  }
}

const handleOpenHistoryDrawer = () => {
  historyFillCheckRef.value.onDrawerShow(queryParam.value.tplId);
  historyDrawerVisible.value = true;
}

const closeHistoryDrawer = () => {
  historyDrawerVisible.value = false;
}

const checkData = async () => {
  validationResultsList.value = []
  drawerVisible.value = true
}

const handleValidationDrawerShow = () => {
  performValidation()
}

const performValidation = () => {
  validationResultsList.value = []
  const process: string[] = []
  process.push('开始校验')
  process.push(`找到 ${validFormula.value.length} 个验证公式`)

  validFormula.value.forEach((formulaItem: any) => {
    process.push(`开始校验公式: ${formulaItem.des}`)
    const result = evaluateFormula(formulaItem.formula, formulaItem.des, process)
    if (result) {
      validationResultsList.value.push(result)
    }
  })
  process.push('校验完成')
}

const evaluateFormula = (formula: string, formulaDes: string, process: string[]): ValidationResult | null => {
  const fieldRegex = /COL\d+/g
  const fields = [...new Set(formula.match(fieldRegex) || [])]
  process.push(`公式包含字段: ${fields.join(', ')}`)

  const fieldValues: Record<string, any> = {}
  let hasEmptyField = false
  
  for (const field of fields) {
    const value = getFieldValue(field)
    fieldValues[field] = value
    if (value === '' || value === null || value === undefined) {
      hasEmptyField = true
      process.push(`字段 ${field} 值为空，跳过此公式校验`)
    }
  }

  if (hasEmptyField) {
    return {
      fieldTitle: formulaDes,
      fieldName: fields.join(', '),
      formula,
      isValid: true,
      resultMessage: '跳过校验 (有字段值为空)',
      process: [...process]
    }
  }

  process.push('所有字段值都已获取，开始计算')
  process.push(`字段值: ${JSON.stringify(fieldValues)}`)

  try {
    const sanitizedFormula = sanitizeAndEvaluate(formula, fieldValues, process)
    process.push(`计算公式: ${sanitizedFormula}`)
    
    const result = evaluateString(sanitizedFormula)
    process.push(`计算结果: ${result}`)

    if (result) {
      return {
        fieldTitle: formulaDes,
        fieldName: fields.join(', '),
        formula,
        isValid: true,
        resultMessage: '校验通过',
        fieldValues,
        process: [...process]
      }
    } else {
      return {
        fieldTitle: formulaDes,
        fieldName: fields.join(', '),
        formula,
        isValid: false,
        resultMessage: '校验失败 - 验证公式返回 false',
        fieldValues,
        process: [...process]
      }
    }
  } catch (error) {
    process.push(`计算出错: ${error instanceof Error ? error.message : '未知错误'}`)
    return {
      fieldTitle: formulaDes,
      fieldName: fields.join(', '),
      formula,
      isValid: false,
      resultMessage: `校验出错: ${error instanceof Error ? error.message : '未知错误'}`,
      fieldValues,
      process: [...process]
    }
  }
}

const getFieldValue = (field: string): any => {
  for (const row of tableFormData) {
    if (row.content && Array.isArray(row.content)) {
      for (const item of row.content) {
        if (item.field === field) {
          return formData[`${row.code}_${field}`]
        }
      }
    }
  }
  return null
}

const sanitizeAndEvaluate = (formula: string, fieldValues: Record<string, any>, process: string[]): string => {
  let sanitizedFormula = formula
  
  const wordBoundaryRegex = /COL\d+/g
  sanitizedFormula = sanitizedFormula.replace(wordBoundaryRegex, (match) => {
    const value = fieldValues[match]
    process.push(`替换 ${match} = ${value}`)
    return value !== '' && value !== null && value !== undefined ? String(value) : 'null'
  })

  sanitizedFormula = sanitizedFormula.replace(/==/g, '===')
  sanitizedFormula = sanitizedFormula.replace(/!==/g, '!==')

  return sanitizedFormula
}

const evaluateString = (str: string): any => {
  try {
    const func = new Function('return ' + str)
    return func()
  } catch (error) {
    throw new Error(`公式计算错误: ${str}`)
  }
}

const getInputStatus = (rowCode: string, field: string): 'success' | 'error' | '' => {
  const key = `${rowCode}_${field}`
  return validationResults.value[key] === 'error' ? 'error' : ''
}

const getErrorMessage = (rowCode: string, field: string): string => {
  const key = `${rowCode}_${field}`
  return validationMessages.value[key] || ''
}

const handleInputChange = (rowCode: string, field: string) => {
  validateField(rowCode, field)
}

const validateField = (rowCode: string, field: string) => {
  const key = `${rowCode}_${field}`
  validationResults.value[key] = ''
  validationMessages.value[key] = ''

  const relevantFormulas = validFormula.value.filter((f: any) => 
    f.formula.includes(field)
  )

  if (relevantFormulas.length > 0) {
    const formula = relevantFormulas[0]
    const fieldValues: Record<string, any> = {}
    const fieldRegex = /COL\d+/g
    const fields = [...new Set(formula.formula.match(fieldRegex) || [])]

    let hasEmptyField = false
    for (const fld of fields) {
      const value = getFieldValue(fld)
      fieldValues[fld] = value
      if (value === '' || value === null || value === undefined) {
        hasEmptyField = true
      }
    }

    if (!hasEmptyField) {
      try {
        const sanitizedFormula = sanitizeAndEvaluate(formula.formula, fieldValues, [])
        const result = evaluateString(sanitizedFormula)
        if (!result) {
          validationResults.value[key] = 'error'
          validationMessages.value[key] = `校验失败: ${formula.des}`
        }
      } catch (error) {
        validationResults.value[key] = 'error'
        validationMessages.value[key] = `校验错误: ${error instanceof Error ? error.message : '未知错误'}`
      }
    }
  }
}

const toggleTooltip = (rowCode: string, field: string) => {
  const key = `${rowCode}_${field}`
  if (hoveredKey.value === key) {
    showTooltip.value = false
    hoveredKey.value = ''
  } else {
    showTooltip.value = true
    hoveredKey.value = key
  }
}

const closeTooltip = () => {
  showTooltip.value = false
  hoveredKey.value = ''
}

const getValidationRule = (rowCode: string, field: string): string => {
  const relevantFormulas = validFormula.value.filter((f: any) => 
    f.formula.includes(field)
  )
  if (relevantFormulas.length > 0) {
    return `${relevantFormulas[0].des}\n公式: ${relevantFormulas[0].formula}`
  }
  return '暂无校验规则'
}

const formatJSON = (obj: any): string => {
  return JSON.stringify(obj, null, 2)
}

const getFillDatas = async() => {

  try {
    formValues.value = []

    for (const strKey in formData) {
      const valData = formData[strKey]
      if (valData!==undefined&&valData!=="") {
        let tmpAry = strKey.split("_")
        await setFormValues(tmpAry[0],tmpAry[1],valData,1)    
      }
    }
    await getAttachTableFormData();
    await getAllMultiTableFormData()
    await getVxeTableFormData()

  } catch (error) {
    console.log(error)
  } finally {
 
  }
}


const childMultiTableRefs = ref({})
const setMultiColumnTableRef = (el: any, index: string) => {
  if (el) {
    childMultiTableRefs.value[index] = el;
  }
};


const getAllMultiTableFormData = async () => {
  for (const pcode in childMultiTableRefs.value) {
      const child = childMultiTableRefs.value[pcode];
      if (child) {
          const datas = await child.getFormData()
          let rind = 0
          for(const obj of datas) {
            rind++
            Object.keys(obj).forEach(code => {  
              setFormValues(pcode,code,obj[code],rind)
            });
          }
      }
  }
};


const childAttachTableRefs = ref({})
const setAttachTableRef = (el: any, index: string) => {
  if (el) {
    childAttachTableRefs.value[index] = el; // 保存子组件实例
  }
};

const childMyVexTableRefs = ref({})
const setMyVxeTableRef = (el: any, index: string) => {
  if (el) {
    childMyVexTableRefs.value[index] = el; // 保存子组件实例
  }
};

const getAttachTableFormData  = async () => {
  for (const pcode in childAttachTableRefs.value) {
      const child = childAttachTableRefs.value[pcode];
      if (child) {
          const datas = await child.getFormData()
          for(const code in datas) {
            await setFormValues(pcode,code,datas[code],1)
          }
      }
  }
};

const getVxeTableFormData  = async () => {
  for (const pcode in childMyVexTableRefs.value) {
      const child = childMyVexTableRefs.value[pcode];
      if (child) {
          const formData = await child.getFormData()
          console.log("formData",formData)
          let rind = 0
          for(const obj of formData.datas) {
            rind++
            Object.keys(obj).forEach(code => {  
              setFormValues(pcode,code,obj[code],rind)
            });
          }
          if(formData.footer) {
            Object.keys(formData.footer).forEach(code => {  
              setFormValues(pcode,code,formData.footer[code],1)
            });
          }
      }
  }

};

const setFormValues = async (pcode,code,valData,rind) => {
  if(!valData) return;
  let vals = Array.isArray(valData) ? valData.join(',') : valData 
  let strKey = pcode+"_"+code
  const item = tplItemMap.value[strKey];  
  const { pid, itemid } = item ?? {}; 
  
  let tempForm: FormData = {
    id: null,
    rind:rind,
    taskid: queryParam.value.taskId,
    tplid: queryParam.value.tplId,
    tplcode: code,
    itemid: itemid,
    itempid: pid,
    content:vals
  };
  formValues.value.push(tempForm)
}

async function setData() {
  try {
    loading.value = true;
    const taskId = queryParam.value.taskId;
    const tplid = queryParam.value.tplId;
    
    Object.keys(formData).forEach(key => delete formData[key]);
    
    await setTplItemMap();
    const recordData = await queryRecord({ taskid: taskId, tplid: tplid });
    const valueObj = {};
    for (const data of recordData) {
      const key = `${data.itempid}_${data.itemid}_${data.rind}`;
      valueObj[key] = data.content;
    }
    for (const row of tableFormData) {
      if(!row.type&&row.content) {
        for (const cdata of row.content) {
          if(cdata.field&&cdata.field.length>0) {
            
            const strKey = `${row.code}_${cdata.field}`;           
            const item = tplItemMap.value[strKey];
            if (!item) continue;
            const { pid, itemid, formTp } = item;
            const dataVal = valueObj[`${pid}_${itemid}_1`];
            if (!dataVal) continue;
            if (formTp === 'checkbox') {
              formData[strKey] = dataVal?.split(",") || [];
            } else {
              formData[strKey] = dataVal || "";
            }

            if(cdata.type&&cdata.type=="checkboxAndInput") {
              for (const itemField of cdata.optionItemField) {
                const strItemKey = `${row.code}_${itemField}`;   
                const item2 = tplItemMap.value[strItemKey];
                if (!item2) continue;
                const { pid:pid2, itemid:itemid2 } = item2;
                const dataVal2 = valueObj[`${pid2}_${itemid2}_1`];
                formData[strItemKey] = dataVal2 || "";
              }
            }
            
            if(cdata.otherField){
              const strItemKey3 = `${row.code}_${cdata.otherField}`;   
              const item3 = tplItemMap.value[strItemKey3];
              if (!item3) continue;
              const { pid:pid3, itemid:itemid3 } = item3;
              const dataVal3 = valueObj[`${pid3}_${itemid3}_1`];
              formData[strItemKey3] = dataVal3 || ""
            }

          }
        }
      } else if(row.type=="AttachTable"&& row.datas) {
        const curAttachTable = childAttachTableRefs.value[row.code];
        const attachTableData = {};
        for (const cdata of row.datas) {
          Object.keys(cdata).forEach(key => {
            if(cdata[key]["field"]){
              const strKey = `${row.code}_${cdata[key]["field"]}`;           
              const item = tplItemMap.value[strKey];
              if (item) {
                const { pid, itemid, formTp, code } = item;
                const dataVal = valueObj[`${pid}_${itemid}_1`];
                if (dataVal) {
                  if (formTp === 'checkbox') {
                    attachTableData[code] = dataVal?.split(",") || [];
                  } else {
                    attachTableData[code] = dataVal || "";
                  }
                }
              }
            }
          });
        }
        
        curAttachTable.setFormData(attachTableData);
      } else if(row.type=="MultiColumnTable"&& row.content) {
          const curMultiTable = childMultiTableRefs.value[row.code];
 
          const rowsMap = {};
          for (const cdata of row.content) {
            if(cdata.field&&cdata.field.length>0) {
              const strKey = `${row.code}_${cdata.field}`;    
              const tmpData = tplItemMap.value[strKey];
              if (!tmpData) continue;
              const { pid, itemid, code } = tmpData;
              const valKeys = Object.keys(valueObj).filter(k => 
                k.startsWith(`${pid}_${itemid}_`)
              );

              for (const valKey of valKeys) {
                const parts = valKey.split('_');
                const rind = parts[2];
                if (!rowsMap[rind]) {
                  rowsMap[rind] = {};
                }
                rowsMap[rind][code] = valueObj[valKey];
              }
            }
          }
          
          const tableDatas = Object.values(rowsMap);
          curMultiTable.setFormData(tableDatas);
        } else if(row.type=="VxeTable"&& row.columns) {
          debugger;
          const curVexTable = childMyVexTableRefs.value[row.code];
          const rowsMap = {};
          for (const cdata of row.columns) {
            if(cdata.field&&cdata.field.length>0) {
              const strKey = `${row.code}_${cdata.field}`;
              const tmpData = tplItemMap.value[strKey];
            
              if (!tmpData || Object.keys(tmpData).length === 0) continue;
              const { pid, itemid, code } = tmpData;
              
              console.log("tmpData",tmpData)

              console.log("valueObj",valueObj)
            
              const valKeys = Object.keys(valueObj).filter(k => 
                k.startsWith(`${pid}_${itemid}_`)
              );

              console.log("valKeys",valKeys)

             
              for (const valKey of valKeys) {
                const parts = valKey.split('_');
                const rind = parts[2];
                if (!rowsMap[rind]) {
                  rowsMap[rind] = {};
                }

                rowsMap[rind][code] = valueObj[valKey];
              }

            }
          }
          const tableDatas = Object.values(rowsMap);
          curVexTable.setFormData(tableDatas);
      }
    }
  } catch (error) {
    console.log(error)
    VxeUI.modal.message({ 
      content: `加载数据失败:`, 
      status: 'error' 
    });
  } finally {
    loading.value = false;
  }

}
  
async function setTplItemMap() {
  try {
    const tplid =  queryParam.value.tplId
    const tplItem = await allTplItems({
      tplid: tplid
    })

    tplItemMap.value = {}
    tplItem.forEach(item => {
      let strKey = item.pcode + "_" + item.xmlcode;
      tplItemMap.value[strKey] = {pid:item.pid,itemid:item.id,formTp:item.formTp,code:item.xmlcode};
    })

  } catch (error) {
    VxeUI.modal.message({ content: `加载数据失败: ${error.message}`, status: 'error' })
  } finally {
   
  }
}

</script>

<style lang="less" scoped>
// Base table styles
.bank-report-table {
  font-family: "SimSun", "宋体", serif;
  font-size: 12px;
  color: #000;
  margin: 5px auto;
  width: 90%;
  
  // Shared table styles
  .custom-table, .attachment-table {
    width: 100%;
    border: 1px solid #000;
    
    .vxe-header--column,
    .vxe-body--column {
      border-right: 1px solid #000;
      border-bottom: 1px solid #000;
      padding: 5px;
    }
  }
}

// Cell styles
.content-cell {
  line-height: 1.8;
}

.radio-group, .checkbox-group {
  display: inline-block;
  margin-left: 10px;
  .vxe-radio, .vxe-checkbox {
    margin-left: 0px;
    white-space: nowrap;
    line-height: 30px;
    padding: 0px 10px;
    &--label {
      font-size: 12px;
      overflow: display;
    }
    &--icon {
      font-size: 12px;
    }
  }
}


.checkbox-group {

}


// VXE specific overrides
.vxe {
  &-radio-group, &-checkbox-group {
    display: inline-block;
  }
  
  &-cell {
    padding: 5px;
  }
}

.vxe-input {
  border-bottom: 1px solid #333;
  text-align: center;
  margin: 5px 3px;
  padding: 0;
  border-top: none;
  border-left: none;
  border-right: none;
  background: transparent;
}

.input-wrapper {
  position: relative;
  display: inline-block;
}

.unit {
  margin-left: 5px;
  font-size: 12px;
}

.help-icon {
  margin-left: 5px;
  cursor: pointer;
  color: #1890ff;
  font-weight: bold;
  font-size: 14px;
  display: inline-block;
  width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  background: #e6f7ff;
  border-radius: 50%;
}

.error-tip {
  position: absolute;
  bottom: -20px;
  left: 0;
  color: #f5222d;
  font-size: 12px;
}

.tooltip {
  position: absolute;
  top: 100%;
  left: 0;
  margin-top: 5px;
  padding: 10px;
  background: #333;
  color: #fff;
  font-size: 12px;
  border-radius: 4px;
  z-index: 1000;
  white-space: pre-wrap;
  max-width: 300px;
}

.tooltip::before {
  content: '';
  position: absolute;
  bottom: 100%;
  left: 10px;
  border-width: 5px;
  border-style: solid;
  border-color: transparent transparent #333 transparent;
}

.validation-results {
  max-height: calc(100vh - 200px);
  overflow-y: auto;
}

.result-summary {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding: 10px;
  background: #f5f5f5;
  border-radius: 4px;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.summary-value {
  font-weight: bold;
  font-size: 16px;
}

.summary-value.success {
  color: #52c41a;
}

.summary-value.error {
  color: #f5222d;
}

.result-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.result-item {
  padding: 10px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}

.result-item.success {
  border-left: 4px solid #52c41a;
}

.result-item.error {
  border-left: 4px solid #f5222d;
}

.result-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #f0f0f0;
}

.result-item-name {
  font-weight: bold;
  font-size: 14px;
}

.result-item-status {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.result-item-status.success {
  background: #f6ffed;
  color: #52c41a;
}

.result-item-status.error {
  background: #fff2f0;
  color: #f5222d;
}

.result-item-content {
  font-size: 13px;
}

.result-item-formula,
.result-item-result,
.result-item-values,
.result-item-process {
  margin-bottom: 8px;
}

.result-item-values {
  margin-bottom: 15px;
}

.values-label,
.formula-label,
.result-label,
.process-label {
  font-weight: bold;
  margin-right: 5px;
}

.values-value {
  white-space: pre-wrap;
  background: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
  font-size: 12px;
  font-family: monospace;
  margin-top: 5px;
}

.process-content {
  margin-top: 5px;
  background: #fafafa;
  padding: 8px;
  border-radius: 4px;
}

.process-step {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-bottom: 4px;
  font-size: 12px;
}

.step-number {
  display: inline-block;
  width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  background: #e8e8e8;
  border-radius: 50%;
  font-size: 10px;
  font-weight: bold;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.loading-spinner {
  text-align: center;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 14px;
  color: #666;
}
</style>
