<template>
  <div 
    class="bank-report-table" 
    style="height:80vh" 
    @click="closeAllTooltips"
  >
    <!-- 加载遮罩层 -->
    <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 class="table-info-text">填报任务：{{ queryParam.taskName }}</span>
          <span class="table-info-text" style="margin-left:20px">
            表格：{{ queryParam.tplCode }} {{ queryParam.tplName }}
          </span>
        </div>
      </template>
      <template #tools v-if="!queryParam.comfrom">
        <vxe-button 
          status="primary" 
          icon="vxe-icon-edit" 
          @click="handleOpenHistoryDrawer" 
          :disabled="loading"
        >
          近5年数据填报
        </vxe-button>
        <vxe-button 
          status="primary"  
          icon="vxe-icon-save" 
          @click="validateData"
        >
          校验
        </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 class="project-name">{{ row.project }}</span>
        </template>
      </vxe-column>
      
      <vxe-column field="content" title="内容">
        <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>
            
            <!-- Vxe表格 -->
            <template v-else-if="row.type === 'VxeTable'">
              <MyVxeTable
                :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[getFieldKey(row.code, item.field)]"
                    :disabled="!item.hasRight || isRadioDisabled(row.code, item)"
                  >
                    <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[getFieldKey(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[getFieldKey(row.code, item.otherField)]"  
                            :disabled="!isOtherFieldEnabled(row.code, item) || !item.hasRight"
                            style="width: 50%"
                            @blur="handleInputBlur(row.code, item.otherField, item.matchedFormula?.formula)"
                          />
                        </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[getFieldKey(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[getFieldKey(row.code, item.optionItemField[optIndex])]" 
                          :disabled="!item.hasRight"  
                          style="width: 100px;margin: 0px;" 
                          @blur="handleInputBlur(row.code, item.optionItemField[optIndex], item.matchedFormula?.formula)"
                        />
                        <span class="unit"> {{ item.optionItemUint }}</span>
                      </vxe-checkbox>
                    </vxe-checkbox-group>
                  </span> 
                </div>
                <div v-else-if="item.type === 'VxeTable'">
                  <MyVxeTable
                    :title="item.project"
                    :data="item.data"
                    :columns="item.columns"
                    :pcode="item.code"
                    :footerData="item.footerData"
                    :showFooter="item.showFooter"
                    :ref="(el) => setMyVxeTableRef(el, item.code)"
                    :disabled="!item.hasRight"
                    style="margin:0px;padding:0px"
                  />
              </div>
                <!-- 普通输入框 -->
                <template v-else>
                  <div class="input-wrapper">
                    <vxe-input
                      :disabled="!item.hasRight || isInputDisabled(row.code, item)"
                      :type="item.type"
                      v-model="formData[getFieldKey(row.code, item.field)]"
                      size="mini"
                      class="table-input"
                      :style="item.style"
                      @blur="handleInputBlur(row.code, item.field, item.matchedFormula?.formula)"
                    />
                    <span class="unit">{{ item.unit }}</span>
                    
                    <!-- 帮助图标 -->
                    <span 
                      v-if="item.hasValidFormula" 
                      class="help-icon" 
                      @click.stop="toggleTooltip(row.code, item.field)"
                    >
                      ?
                    </span>
                    
                    <!-- 错误图标 -->
                    <span 
                      v-if="inputErrors[getFieldKey(row.code, item.field)]" 
                      class="error-icon" 
                      @click.stop="toggleErrorTooltip(row.code, item.field)"
                    >
                      <i class="vxe-icon-error">✗</i>
                    </span>
                    
                    <!-- 错误提示 -->
                    <div 
                      v-if="showErrorTooltip && hoveredErrorKey === getFieldKey(row.code, item.field)" 
                      class="error-tooltip" 
                      @click.stop
                    >
                      {{ inputErrors[getFieldKey(row.code, item.field)].message }}
                      <br>
                      <span style="color: #ffcccc;">
                        公式: {{ inputErrors[getFieldKey(row.code, item.field)].formula }}
                      </span>
                      <template v-if="inputErrors[getFieldKey(row.code, item.field)].error">
                        <br>
                        <span style="color: #ff9999; font-size: 11px;">
                          错误: {{ inputErrors[getFieldKey(row.code, item.field)].error }}
                        </span>
                      </template>
                    </div>
                    
                    <!-- 校验规则提示 -->
                    <div 
                      v-if="showTooltip && hoveredKey === getFieldKey(row.code, item.field)" 
                      class="tooltip" 
                      @click.stop
                    >
                      {{ item.matchedFormula?.des || '暂无校验规则' }}
                    </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[getFieldKey(row.code, row.remarks.field)]"
          />
        </template>
      </vxe-column>
    </vxe-table>
    
    <!-- 校验抽屉 -->
    <ValidationDrawer 
      ref="validationDrawerRef" 
      v-model="drawerVisible" 
      :tableFormData="tableFormData" 
      @validationResultClick="handleValidationResultClick"
    />

    <!-- 历史填报抽屉 -->
    <HistoryFillCheck 
      ref="historyFillCheckRef" 
      v-model="historyDrawerVisible" 
      @closeDrawer="closeHistoryDrawer"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { VxeUI, VxeTableInstance } from 'vxe-table'

import 'vxe-table/lib/style.css'
import { useRoute } from 'vue-router'
// 组件导入
import MultiColumnTable from '../tableComponents/MultiColumnTable.vue'
import AttachTable from '../tableComponents/AttachTable.vue'
import MyVxeTable from '../tableComponents/MyVxeTable.vue'
import HistoryFillCheck from './check/HistoryFillCheck.vue'
import ValidationDrawer from './check/ValidationDrawer.vue'

// 数据导入
import { tableFormData } from '../../data/tb9.data'

// API 导入
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'

// 类型定义
interface QueryParam {
  taskId: number
  taskName: string
  tplId: number
  tplName: string
  tplCode: string
  comfrom: string
}

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

interface FormulaItem {
  formula: string
  des: string
  [key: string]: any
}

interface ContentItem {
  type: string
  field: string
  value?: any
  hasRight?: boolean
  hasValidFormula?: boolean
  matchedFormula?: FormulaItem
  relatedFiled?: string
  otherField?: string
  optionItemField?: string[]
  [key: string]: any
}

interface TableRow {
  code: string
  project: string
  type?: string
  content: ContentItem[] | any
  remarks: { rows: number; field: string }
  hasRight?: boolean
  [key: string]: any
}

interface InputError {
  message: string
  formula: string
  error?: string
}

interface TplItemMapValue {
  pid: number
  itemid: number
  formTp: string
  code: string
}

// 路由和组件引用
const route = useRoute()
const tableRef = ref<VxeTableInstance>()
const historyFillCheckRef = ref()
const validationDrawerRef = ref()

// 响应式状态
const loading = ref(true)
const historyDrawerVisible = ref(false)
const drawerVisible = ref(false)
const showTooltip = ref(false)
const hoveredKey = ref('')
const showErrorTooltip = ref(false)
const hoveredErrorKey = ref('')

// 数据状态
const queryParam = ref<QueryParam>({
  taskId: -1,
  taskName: '',
  tplId: -1,
  tplName: '',
  tplCode: '',
  comfrom: ''
})

const formData = reactive<Record<string, any>>({})
const formValues = ref<FormDataItem[]>([])
const inputErrors = ref<Record<string, InputError>>({})
const userAllocItems = ref<string[]>([])
const validFormula = ref<FormulaItem[]>([])
const tplItemMap = ref<Record<string, TplItemMapValue>>({})

// 子组件引用
const childMultiTableRefs = ref<Record<string, any>>({})
const childAttachTableRefs = ref<Record<string, any>>({})
const childMyVexTableRefs = ref<Record<string, any>>({})

// 计算属性
const fieldKeys = computed(() => Object.keys(formData))

// 工具函数
const getFieldKey = (rowCode: string, field: string): string => {
  return `${rowCode}_${field}`
}

const isRadioDisabled = (rowCode: string, item: ContentItem): boolean => {
  if (!item.relatedFiled) return false
  const relatedKey = getFieldKey(rowCode, item.relatedFiled)
  return formData[relatedKey] !== '是'
}

const isInputDisabled = (rowCode: string, item: ContentItem): boolean => {
  if (!item.relatedFiled) return false
  const relatedKey = getFieldKey(rowCode, item.relatedFiled)
  return formData[relatedKey] !== '是'
}

const isOtherFieldEnabled = (rowCode: string, item: ContentItem): boolean => {
  const checkboxKey = getFieldKey(rowCode, item.field)
  const checkboxValue = formData[checkboxKey] || []
  return checkboxValue.includes('其他')
}

// 初始化
onMounted(async () => {
  await initPage()
})

const initPage = async () => {
  try {
    loading.value = true
    await initQueryParams()
    await Promise.all([
      loadUserRights(),
      loadValidationFormulas(),
      loadTemplateItems()
    ])
    await setFormItemRight()
    await loadTableData()
  } catch (error: any) {
    showErrorMessage(`初始化页面失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

const initQueryParams = () => {
  const { taskId, taskName, tplId, tplName, tplCode,comfrom } = route.query
  
  if (taskId) queryParam.value.taskId = Number(taskId)
  if (taskName) queryParam.value.taskName = String(taskName)
  if (tplId) queryParam.value.tplId = Number(tplId)
  if (tplName) queryParam.value.tplName = String(tplName)
  if (tplCode) queryParam.value.tplCode = String(tplCode)
  if (comfrom) queryParam.value.comfrom = String(comfrom)
}

const loadUserRights = async () => {
  userAllocItems.value = await findUserRightForTplItem({
    tplid: queryParam.value.tplId,
    taskid: queryParam.value.taskId
  })
}

const loadValidationFormulas = async () => {
  validFormula.value = await getTblvalidFormula({
    tplid: queryParam.value.tplId
  })
}

const loadTemplateItems = async () => {
  const items = await allTplItems({
    tplid: queryParam.value.tplId
  })
  
  tplItemMap.value = items.reduce((acc: Record<string, TplItemMapValue>, item) => {
    const key = `${item.pcode}_${item.xmlcode}`
    acc[key] = {
      pid: item.pid,
      itemid: item.id,
      formTp: item.formTp,
      code: item.xmlcode
    }
    return acc
  }, {})
}

const setFormItemRight = () => {
  tableFormData.forEach((row: TableRow) => {
    if (row.content && Array.isArray(row.content)) {
      row.content.forEach((item: ContentItem) => {
        if (item.field) {
          const key = getFieldKey(row.code, item.field)
          item.hasRight = userAllocItems.value.includes(key)
          
          if (item.hasRight) {
            const { formula } = findEarliestFormulaForField(validFormula.value, item.field)
            item.hasValidFormula = !!formula
            item.matchedFormula = formula
          }
        }
      })
    }
  })
}

// 保存相关
const saveBatch = async () => {
  try {
    if (!await validateForm()) return
    
    await prepareFormData()
    
    if (formValues.value.length === 0) {
      showWarningMessage('没有需要保存的数据')
      return
    }
    
    await batchSaveOrUpdateBeforeDelete(formValues.value)
    showSuccessMessage('保存成功')
  } catch (error: any) {
    showErrorMessage(`保存失败: ${error.message}`)
  }
}

const validateForm = async (): Promise<boolean> => {
  const $table = tableRef.value
  if (!$table) return true
  
  const checkResult = $table.validate()
  if (!checkResult) {
    showErrorMessage('表单验证失败，请检查填写内容')
    return false
  }
  return true
}

const prepareFormData = async () => {
  formValues.value = []
  // 处理主表单数据
  for (const [key, value] of Object.entries(formData)) {
    if (value !== undefined && value !== null && value !== '') {
      const [pcode, code] = key.split('_')
      await addFormValue(pcode, code, value, 1)
    }
  }
  
  // 处理子表格数据
  await Promise.all([
    collectAttachTableData(),
    //collectMultiTableData(),
    collectVxeTableData()
  ])
}

const addFormValue = async (pcode: string, code: string, value: any, rind: number) => {
  if (!value) return
  
  const stringValue = Array.isArray(value) ? value.join(',') : String(value)
  const key = getFieldKey(pcode, code)
  const item = tplItemMap.value[key]
  
  if (!item) return
  
  const formItem: FormDataItem = {
    id: null,
    rind,
    taskid: queryParam.value.taskId,
    tplid: queryParam.value.tplId,
    tplcode: code,
    itemid: item.itemid,
    itempid: item.pid,
    content: stringValue
  }
  
  formValues.value.push(formItem)
}

// 数据收集函数
const collectAttachTableData = async () => {
  for (const [pcode, child] of Object.entries(childAttachTableRefs.value)) {
    if (child) {
      const datas = await child.getFormData()
      for (const [code, value] of Object.entries(datas)) {
        await addFormValue(pcode, code, value, 1)
      }
    }
  }
}

const collectMultiTableData = async () => {
  for (const [pcode, child] of Object.entries(childMultiTableRefs.value)) {
    if (child) {
      const datas = await child.getFormData()
      let rind = 0
      for (const obj of datas) {
        rind++
        for (const [code, value] of Object.entries(obj)) {
          await addFormValue(pcode, code, value, rind)
        }
      }
    }
  }
}

const collectVxeTableData = async () => {
  for (const [pcode, child] of Object.entries(childMyVexTableRefs.value)) {
    if (child) {
      const formData = await child.getFormData()
      let rind = 0
      // 表格数据
      for (const obj of formData.datas) {
        rind++
        for (const [code, value] of Object.entries(obj)) {
          await addFormValue(pcode, code, value, rind)
        }
      }
      if (formData.footer) {
        for (const [code, value] of Object.entries(formData.footer)) {
          await addFormValue(formData.footerPcode, code, value, 1)
        }
      }
    }
  }
}

// 数据加载
const loadTableData = async () => {
  try {
    loading.value = true
    
    // 清空现有数据
    Object.keys(formData).forEach(key => delete formData[key])
    
    const recordData = await queryRecord({ 
      taskid: queryParam.value.taskId, 
      tplid: queryParam.value.tplId 
    })
    
    // 转换记录数据为便于查找的结构
    const valueMap = recordData.reduce((acc: Record<string, string>, data) => {
      const key = `${data.itempid}_${data.itemid}_${data.rind}`
      acc[key] = data.content
      return acc
    }, {})
    
    // 填充表格数据
    await fillTableData(valueMap)
  } catch (error: any) {
    showErrorMessage(`加载数据失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

const fillTableData = async (valueMap: Record<string, string>) => {
  for (const row of tableFormData) {
    if (!row.type && row.content) {
      await fillSimpleFields(row, valueMap)
    } else if (row.type === 'AttachTable' && row.datas) {
      await fillAttachTable(row, valueMap)
    } else if (row.type === 'MultiColumnTable' && row.content) {
      await fillMultiColumnTable(row, valueMap)
    } else if (row.type === 'VxeTable' && row.columns) {
      await fillVxeTable(row, valueMap)
    }
  }
}

const fillSimpleFields = async (row: TableRow, valueMap: Record<string, string>) => {
  if (!row.content || !Array.isArray(row.content)) return
  
  for (const item of row.content) {
    if (item.type === 'VxeTable' && item.code) {
      await fillVxeTable(item, valueMap)
      continue
    }
    
    if (!item.field) continue
    
    const key = getFieldKey(row.code, item.field)
    const tplItem = tplItemMap.value[key]
    if (!tplItem) continue
    
    const { pid, itemid, formTp } = tplItem
    const valueKey = `${pid}_${itemid}_1`
    const dataVal = valueMap[valueKey]
    
    if (dataVal === undefined) continue
    
    if (formTp === 'checkbox') {
      formData[key] = dataVal.split(',').filter(Boolean)
    } else {
      formData[key] = dataVal
    }
    
    if (item.type === 'checkboxAndInput' && item.optionItemField) {
      await fillCheckboxInputFields(row, item, valueMap)
    }
    
    if (item.otherField) {
      await fillOtherField(row, item, valueMap)
    }
  }
}

const fillCheckboxInputFields = async (
  row: TableRow, 
  item: ContentItem, 
  valueMap: Record<string, string>
) => {
  for (const field of item.optionItemField || []) {
    const key = getFieldKey(row.code, field)
    const tplItem = tplItemMap.value[key]
    if (!tplItem) continue
    
    const { pid, itemid } = tplItem
    const valueKey = `${pid}_${itemid}_1`
    const dataVal = valueMap[valueKey]
    
    if (dataVal !== undefined) {
      formData[key] = dataVal
    }
  }
}

const fillOtherField = async (
  row: TableRow, 
  item: ContentItem, 
  valueMap: Record<string, string>
) => {
  const key = getFieldKey(row.code, item.otherField!)
  const tplItem = tplItemMap.value[key]
  if (!tplItem) return
  
  const { pid, itemid } = tplItem
  const valueKey = `${pid}_${itemid}_1`
  const dataVal = valueMap[valueKey]
  
  if (dataVal !== undefined) {
    formData[key] = dataVal
  }
}

const fillAttachTable = async (row: TableRow, valueMap: Record<string, string>) => {
  const child = childAttachTableRefs.value[row.code]
  if (!child) return
  
  const tableData: Record<string, any> = {}
  
  for (const data of row.datas || []) {
    for (const [key, value] of Object.entries(data)) {
      if (typeof value === 'object' && value.field) {
        const fieldKey = getFieldKey(row.code, value.field)
        const tplItem = tplItemMap.value[fieldKey]
        if (!tplItem) continue
        
        const { pid, itemid, formTp, code } = tplItem
        const valueKey = `${pid}_${itemid}_1`
        const dataVal = valueMap[valueKey]
        
        if (dataVal) {
          tableData[code] = formTp === 'checkbox' ? dataVal.split(',') : dataVal
        }
      }
    }
  }
  
  child.setFormData(tableData)
}

const fillMultiColumnTable = async (row: TableRow, valueMap: Record<string, string>) => {
  const child = childMultiTableRefs.value[row.code]
  if (!child || !Array.isArray(row.content)) return
  
  const rowsMap: Record<string, Record<string, string>> = {}
  
  for (const item of row.content) {
    if (!item.field) continue
    
    const key = getFieldKey(row.code, item.field)
    const tplItem = tplItemMap.value[key]
    if (!tplItem) continue
    
    const { pid, itemid, code } = tplItem
    const valueKeys = Object.keys(valueMap).filter(k => 
      k.startsWith(`${pid}_${itemid}_`)
    )
    
    for (const valueKey of valueKeys) {
      const [, , rind] = valueKey.split('_')
      if (!rowsMap[rind]) {
        rowsMap[rind] = {}
      }
      rowsMap[rind][code] = valueMap[valueKey]
    }
  }
  
  const tableDatas = Object.values(rowsMap)
  child.setFormData(tableDatas)
}

const fillVxeTable = async (row: TableRow, valueMap: Record<string, string>) => {
  const child = childMyVexTableRefs.value[row.code]
  if (!child || !Array.isArray(row.columns)) return
  
  const rowsMap: Record<string, Record<string, string>> = {}
  
  for (const column of row.columns) {
    if (!column.field) continue
    
    const key = getFieldKey(row.code, column.field)
    const tplItem = tplItemMap.value[key]
    if (!tplItem || Object.keys(tplItem).length === 0) continue
    
    const { pid, itemid, code } = tplItem
    const valueKeys = Object.keys(valueMap).filter(k => 
      k.startsWith(`${pid}_${itemid}_`)
    )
    
    for (const valueKey of valueKeys) {
      const [, , rind] = valueKey.split('_')
      if (!rowsMap[rind]) {
        rowsMap[rind] = {}
      }
      rowsMap[rind][code] = valueMap[valueKey]
    }
  }
  
  const tableDatas = Object.values(rowsMap)
  child.setFormData(tableDatas)
}

// 校验相关
const validateData = () => {
  drawerVisible.value = true
  validationDrawerRef.value.setValidateData(validFormula.value,formData);
}

const handleInputBlur = (rowCode: string, field: string, formula?: string) => {
  if (!formula) return
  
  const key = getFieldKey(rowCode, field)
  const value = formData[key]
  
  if (!value || value === '') {
    delete inputErrors.value[key]
    return
  }
  
  validateFieldFormula(rowCode, field, formula)
}

const validateFieldFormula = (rowCode: string, field: string, formula: string) => {
  const key = getFieldKey(rowCode, field)
  
  try {
    const expression = buildExpression(formula, rowCode)
    const isValid = eval(expression)
    if (!isValid) {
      inputErrors.value[key] = {
        message: "公式校验失败，请检查填写内容",
        formula
      }
    } else {
      delete inputErrors.value[key]
    }
  } catch (error: any) {
    inputErrors.value[key] = {
      message: "公式校验失败，请检查填写内容",
      formula,
      error: error.message
    }
  }
}

const buildExpression = (formula: string, rowCode: string): string => {
  const fieldNames = formula.match(/\b[A-Za-z][A-Za-z0-9_]*\b/g) || []
  const uniqueFields = [...new Set(fieldNames.filter(f => 
    !['and', 'or', 'not', 'equal', 'less', 'greater', 'if', 'else', 'true', 'false']
      .includes(f.toLowerCase())
  ))]
  
  uniqueFields.sort((a, b) => b.length - a.length)
  
  let expression = formula
  for (const fieldName of uniqueFields) {
    const key = getFieldKey(rowCode, fieldName)
    const value = formData[key]
    
    if (value !== undefined) {
      // 检查字段类型，如果是日期类型，转换为时间戳进行比较
      const row = tableFormData.find((r: TableRow) => r.code === rowCode)
      let processedValue = value
      
      if (row && row.content && Array.isArray(row.content)) {
        const fieldItem = row.content.find((c: ContentItem) => c.field === fieldName)
        if (fieldItem && fieldItem.type === 'date') {
          // 将日期字符串转换为时间戳（毫秒）
          const date = new Date(value)
          if (!isNaN(date.getTime())) {
            processedValue = date.getTime()
          }
        }
      }
      
      expression = expression.replace(
        new RegExp(`\\b${fieldName}\\b`, 'g'), 
        `Number(${processedValue})`
      )
    }
  }
  
  return expression
}

// 提示工具相关
const toggleTooltip = (rowCode: string, field: string) => {
  const key = getFieldKey(rowCode, field)
  if (hoveredKey.value === key) {
    showTooltip.value = false
    hoveredKey.value = ''
  } else {
    showTooltip.value = true
    hoveredKey.value = key
  }
}

const toggleErrorTooltip = (rowCode: string, field: string) => {
  const key = getFieldKey(rowCode, field)
  if (hoveredErrorKey.value === key) {
    showErrorTooltip.value = false
    hoveredErrorKey.value = ''
  } else {
    showErrorTooltip.value = true
    hoveredErrorKey.value = key
  }
}

const closeAllTooltips = () => {
  showTooltip.value = false
  hoveredKey.value = ''
  showErrorTooltip.value = false
  hoveredErrorKey.value = ''
}

// 历史填报
const handleOpenHistoryDrawer = () => {
  historyFillCheckRef.value?.onDrawerShow(queryParam.value.tplId)
  historyDrawerVisible.value = true
}

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

// 校验结果处理
const handleValidationResultClick = (result: any) => {
  const message = `字段 ${result.field} 的校验结果: ${result.isValid ? '通过' : '失败'}`
  const status = result.isValid ? 'success' : 'error'
  
  VxeUI.modal.message({ content: message, status })
}

// 工具函数
const findEarliestFormulaForField = (
  formulas: FormulaItem[], 
  field: string
): { formula: FormulaItem | null, index: number } => {
  let result = { formula: null, index: Infinity }
  
  formulas?.forEach((f: FormulaItem) => {
    const text = f.formula || ''
    const escapedField = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
    const regex = new RegExp(`\\b${escapedField}\\b(?!\\w)`, 'g')
    const match = regex.exec(text)
    
    if (match && match.index < result.index) {
      result = { formula: f, index: match.index }
    }
  })
  
  return result
}

// 消息提示
const showSuccessMessage = (message: string) => {
  VxeUI.modal.message({ content: message, status: 'success' })
}

const showWarningMessage = (message: string) => {
  VxeUI.modal.message({ content: message, status: 'warning' })
}

const showErrorMessage = (message: string) => {
  VxeUI.modal.message({ content: message, status: 'error' })
}

// 子组件引用设置
const setMultiColumnTableRef = (el: any, code: string) => {
  if (el) childMultiTableRefs.value[code] = el
}

const setAttachTableRef = (el: any, code: string) => {
  if (el) childAttachTableRefs.value[code] = el
}

const setMyVxeTableRef = (el: any, code: string) => {
  if (el) childMyVexTableRefs.value[code] = el
}
</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%;
  position: relative;
  
  // 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;
    }
  }
}

// 表格信息文本
.table-info-text {
  font-weight: bold;
}

// 项目名称
.project-name {
  font-weight: bold;
  font-size: 14px;
}

// 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;
    }
    
    &--icon {
      font-size: 12px;
    }
  }
}

// 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%;
  transition: all 0.3s;
  
  &:hover {
    background: #bae7ff;
  }
}

// 错误图标
.error-icon {
  margin-left: 5px;
  cursor: pointer;
  color: #ff4d4f;
  font-size: 16px;
  display: inline-block;
  width: 20px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  transition: all 0.3s;
  
  &:hover {
    transform: scale(1.1);
  }
}

// 提示框
.tooltip, .error-tooltip {
  position: absolute;
  top: 100%;
  left: 0;
  margin-top: 5px;
  padding: 10px;
  font-size: 12px;
  border-radius: 4px;
  z-index: 1000;
  white-space: pre-wrap;
  max-width: 300px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

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

.error-tooltip {
  background: #8b0000;
  color: #fff;
  border: 1px solid #ff4d4f;
  
  &::before {
    content: '';
    position: absolute;
    bottom: 100%;
    left: 5px;
    border-width: 5px;
    border-style: solid;
    border-color: transparent transparent #8b0000 transparent;
  }
}

// 加载遮罩
.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>