<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 #button>
        <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="validateData()">校验</vxe-button>
        <vxe-button status="primary" icon="vxe-icon-save" @click="saveBatch()">保存</vxe-button>
      </template>
    </vxe-toolbar>
    
    <vxe-table
      border
      ref="tableRef"
      show-header-overflow
      :data="tableFormData"
      :column-config="{ resizable: true }"
      :row-config="{ resizable: true }"
      class="custom-table"
      height="auto"
      :merge-cells="mergeCells"
    >
      <vxe-column field="serialNumber" title="序号" width="80"></vxe-column>
      <vxe-column field="project" title="项目" width="200">
        <template #default="{ row }">
          <span style="font-weight: bold; font-size: 14px">{{ 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 === 'AttachTable'">
              <AttachTable
                :title="row.project"
                :records="row.datas"
                :fields="row.content"
                :pcode="row.code"
                :ref="(el) => setAttachTableRef(el, row.code)"
                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>

                <!-- 是/否选项 -->
                <template v-else-if="item.type === 'yesno'">
                  <vxe-radio-group v-model="formData[getFieldKey(row.code, item.field)]">
                    <vxe-radio label="是" content="是"></vxe-radio>
                    <vxe-radio label="否" content="否"></vxe-radio>
                  </vxe-radio-group>
                  <template v-if="item.extraField || item.extraFields">
                    <div v-if="formData[getFieldKey(row.code, item.field)] === '是'" style="margin-left:40px">
                      如是，
                      <template v-if="item.extraField">
                        {{ item.extraLabel }}：
                        <vxe-input 
                          v-model="formData[getFieldKey(row.code, item.extraField)]"  
                          style="width: 300px;"
                        ></vxe-input>
                        <span class="unit"> {{ item.unit }}</span>
                      </template>
                      <template v-else-if="item.extraFields">
                        <template v-for="(ccopt, ccind) in item.extraFields" :key="ccind">
                          <span>{{ ccopt.label }}: </span>
                          <template v-if="ccopt.formType === 'input'">
                            <vxe-input 
                              v-model="formData[getFieldKey(row.code, ccopt.field)]" 
                              style="width:250px"
                            ></vxe-input>
                          </template>
                          <template v-else-if="ccopt.formType === 'number'">
                            <vxe-input 
                              v-model="formData[getFieldKey(row.code, ccopt.field)]" 
                              type="number" 
                              style="width:250px"
                            ></vxe-input>
                            <span class="unit"> {{ ccopt.unit }}</span>
                          </template>
                          <template v-else-if="ccopt.formType === 'checkbox'">
                            <vxe-checkbox-group v-model="formData[getFieldKey(row.code, ccopt.field)]">
                              <vxe-checkbox 
                                v-for="(opt, optIndex) in ccopt.options" 
                                :key="optIndex" 
                                :label="opt" 
                                :content="opt"
                              ></vxe-checkbox>
                            </vxe-checkbox-group>
                          </template>
                          <template v-else-if="ccopt.formType === 'radio'">
                            <vxe-radio-group v-model="formData[getFieldKey(row.code, ccopt.field)]">
                              <vxe-radio 
                                v-for="(opt, optIndex) in ccopt.options" 
                                :key="optIndex" 
                                :label="opt" 
                                :content="opt"
                              ></vxe-radio>
                            </vxe-radio-group>
                          </template>
                          <template v-else>
                            <vxe-input 
                              v-model="formData[getFieldKey(row.code, ccopt.field)]" 
                              :type="ccopt.formType" 
                              style="width:100px"
                            ></vxe-input>
                          </template>
                          <br>
                          <template v-if="ccopt.otherOption">
                            其他：<vxe-input 
                              v-model="formData[getFieldKey(row.code, ccopt.otherField)]"  
                              style="width: 300px;"
                            ></vxe-input>
                          </template>
                          <br>
                        </template>
                      </template>
                    </div>
                  </template>
                </template>

                <!-- 单选组 -->
                <span v-else-if="item.type === 'radio-group'" class="radio-group">
                  <vxe-radio-group v-model="formData[getFieldKey(row.code, item.field)]">
                    <vxe-radio 
                      v-for="(opt, optIndex) in item.options" 
                      :key="optIndex" 
                      :label="opt"
                    >{{ opt }}</vxe-radio>
                  </vxe-radio-group>
                </span>

                <!-- 带额外字段的单选组 -->
                <span v-else-if="item.type === 'radio-group-extraFields'" class="radio-group" style="width:100%">
                  <vxe-radio-group v-model="formData[getFieldKey(row.code, item.field)]">
                    <vxe-radio 
                      v-for="(opt, optIndex) in item.options" 
                      :key="optIndex" 
                      :label="opt.label"
                    >
                      {{ opt.label }}
                      <template v-if="opt.extraField && formData[getFieldKey(row.code, item.field)] === opt.label">
                        <span>{{ opt.extraField }}</span>
                        <vxe-input 
                          v-model="formData[getFieldKey(row.code, opt.otereField)]"  
                          style="width: 200px;"
                        ></vxe-input>  
                      </template>
                      <template v-if="opt.extraFields && formData[getFieldKey(row.code, item.field)] === opt.label">
                        <template v-for="(ccopt, ccind) in opt.extraFields" :key="ccind">
                          <span>{{ ccopt.label }}: </span>
                          <vxe-input 
                            v-model="formData[getFieldKey(row.code, ccopt.field)]"  
                            style="width: 200px;"
                          ></vxe-input>  
                        </template>
                      </template>
                    </vxe-radio>
                  </vxe-radio-group>
                </span>

                <!-- 多选组 -->
                <div v-else-if="item.type === 'checkbox-group'" class="checkbox-group">
                  <vxe-checkbox-group v-model="formData[getFieldKey(row.code, item.field)]">
                    <vxe-checkbox 
                      v-for="(opt, optIndex) in item.options" 
                      :key="optIndex" 
                      :label="opt"
                    >
                      {{ opt }}
                    </vxe-checkbox>
                    <template v-if="item.otherField">
                      <vxe-checkbox label="其他">
                        其他：
                        <vxe-input 
                          v-model="formData[getFieldKey(row.code, item.otherField)]"  
                          :disabled="!formData[getFieldKey(row.code, item.field)]?.includes('其他')"
                          style="width: 200px;"
                        ></vxe-input>
                      </vxe-checkbox>
                    </template>
                  </vxe-checkbox-group>
                </div>   

                <!-- 文本域 -->
                <template v-else-if="item.type === 'textarea'">
                  <vxe-textarea 
                    v-model="formData[getFieldKey(row.code, item.field)]" 
                    :rows="item.rows" 
                    :style="{ width: item.width }"
                  ></vxe-textarea>
                </template> 

                <!-- 其他输入类型 -->
                <template v-else>
                  <div class="input-wrapper">
                    <vxe-input 
                      :type="item.type" 
                      v-model="formData[getFieldKey(row.code, item.field)]"  
                      size="mini" 
                      class="table-input"
                      :style="{ width: item.width }"
                      :disabled="!item.hasRight"
                      @blur="handleInputBlur(row.code, item.field, item.matchedFormula?.formula)"
                    />
                    <span v-if="item.unit" class="unit"> {{ item.unit }}</span>
                    
                    <!-- 帮助图标 -->
                    <span
                      v-if="showHelpIcon(row.code, item.field, item)"
                      class="help-icon"
                      @click.stop="toggleTooltip(row.code, item.field)"
                      title="点击查看校验规则"
                    >
                      ?
                    </span>
                    
                    <!-- 错误图标 -->
                    <span
                      v-if="inputErrors[getFieldKey(row.code, item.field)]"
                      class="error-icon"
                      @click.stop="toggleErrorTooltip(row.code, item.field)"
                      title="点击查看错误详情"
                    >
                      ✗
                    </span>
                    
                    <!-- 帮助提示 -->
                    <div
                      v-if="showTooltip && hoveredKey === getFieldKey(row.code, item.field)"
                      class="tooltip"
                      @click.stop
                    >
                      {{ item.matchedFormula?.des || '暂无校验规则' }}
                    </div>
                    
                    <!-- 错误提示 -->
                    <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>
                </template>
              </template>
            </template>
          </div>
        </template>
      </vxe-column>
      
      <vxe-column field="remarks" title="备注" width="200">
        <template #default="{ row }"> 
          <vxe-textarea 
            :rows="row.remarks.rows" 
            v-model="formData[getFieldKey(row.code, row.remarks.field)]"
          ></vxe-textarea>
        </template>
      </vxe-column>
    </vxe-table>

    <!-- 历史填报检查组件 -->
    <HistoryFillCheck 
      ref="historyFillCheckRef" 
      v-model="historyDrawerVisible" 
      @closeDrawer="closeHistoryDrawer"
    />

    <!-- 校验结果抽屉 -->
    <ValidationDrawer 
      ref="validationDrawerRef" 
      v-model="drawerVisible" 
      :tableFormData="tableFormData" 
      @validationResultClick="handleValidationResultClick"
    />

    <!-- 验证公式帮助提示 -->
    <div
      v-if="validationTooltipVisible"
      class="validation-tooltip"
      :style="{ left: validationTooltipPosition.left + 'px', top: validationTooltipPosition.top + 'px' }"
    >
      <pre class="tooltip-content">{{ validationTooltipContent }}</pre>
    </div>
  </div>
</template>

<script lang="ts" setup>
import AttachTable from '../tableComponents/AttachTable.vue'
import HistoryFillCheck from './check/historyFillCheck.vue'
import ValidationDrawer from './check/ValidationDrawer.vue'

import { tableFormData } from '../../data/tb7.data'
import { ref, reactive, computed, nextTick, onMounted } from 'vue'
import { VxeUI } from 'vxe-table'
import { 
  queryRecord, 
  batchSaveOrUpdateBeforeDelete 
} from '../../record/BaosongTaskRecord.api'
import { findUserRightForTplItem } from '../../alloc/BaosongTaskAlloc.api'
import { allTplItems } from '../../tpl/BaosongTplItem.api'
import { getTblvalidFormula } from '../../tpl/BaosongDataValid.api'
import { useRoute } from 'vue-router'

// 路由相关
const route = useRoute()

// 组件引用
const tableRef = ref()
const historyFillCheckRef = ref<any>(null)
const validationDrawerRef = ref<any>(null)

// 查询参数
const queryParam = ref({
  taskId: -1,
  taskName: '',
  tplId: -1,
  tplName: '',
  tplCode: ''
})

// 状态变量
const loading = ref(false)
const formData = reactive<Record<string, any>>({})
const formValues = ref<FormData[]>([])
const tplItemMap = ref<Record<string, TplItemInfo>>({})
const childAttachTableRefs = ref<Record<string, any>>({})

// 工具提示状态
const showTooltip = ref(false)
const hoveredKey = ref('')
const showErrorTooltip = ref(false)
const hoveredErrorKey = ref('')
const inputErrors = ref<Record<string, InputError>>({})
const isInitialized = ref(false)

// 权限和验证相关
const userAllocItems = ref<string[]>([])
const validFormula = ref<FormulaItem[]>([])
const drawerVisible = ref(false)
const historyDrawerVisible = ref(false)

// 验证公式提示
const validationTooltipVisible = ref(false)
const validationTooltipPosition = ref({ left: 0, top: 0 })
const validationTooltipContent = ref('')

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

// 接口定义
interface FormulaItem {
  formula: string
  des: string
  [key: string]: any
}

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

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

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

// 生命周期钩子
onMounted(async () => {
  await initializePage()
})

// 初始化页面
const initializePage = async () => {
  try {
    loading.value = true
    await setQueryParams()
    
    // 并行获取权限和验证公式
    await Promise.all([
      fetchUserRights(),
      fetchValidationFormulas()
    ])
    
    console.log('获取到的权限:', userAllocItems.value.length)
    console.log('获取到的公式:', validFormula.value.length)
    
    await setTplItemMap()
    setFormItemRight()
    await setData()
    
    isInitialized.value = true
    
    // 延迟刷新帮助图标，确保DOM已渲染
    setTimeout(() => {
      refreshHelpIcons()
    }, 300)
  } catch (error) {
    console.error('初始化页面失败:', error)
    showErrorMessage('初始化页面失败', error)
  } finally {
    loading.value = false
  }
}

// 设置查询参数
const setQueryParams = () => {
  const params = route.query
  if (params.taskId) queryParam.value.taskId = Number(params.taskId)
  if (params.taskName) queryParam.value.taskName = String(params.taskName)
  if (params.tplId) queryParam.value.tplId = Number(params.tplId)
  if (params.tplName) queryParam.value.tplName = String(params.tplName)
  if (params.tplCode) queryParam.value.tplCode = String(params.tplCode)
}

// 获取用户权限
const fetchUserRights = async () => {
  userAllocItems.value = await findUserRightForTplItem({
    tplid: queryParam.value.tplId,
    taskid: queryParam.value.taskId
  })
}

// 获取验证公式
const fetchValidationFormulas = async () => {
  validFormula.value = await getTblvalidFormula({
    tplid: queryParam.value.tplId,
  })
}

// 保存批量数据
const saveBatch = async () => {
  try {
    loading.value = true
    formValues.value = []

    // 收集主表单数据
    for (const strKey in formData) {
      const valData = formData[strKey]
      if (valData) {
        const [pcode, field] = strKey.split('_')
        await setFormValues(pcode, field, valData, 1)
      }
    }

    // 收集附件表格数据
    await getAttachTableFormData()

    // 保存数据
    if (formValues.value.length > 0) {
      await batchSaveOrUpdateBeforeDelete(formValues.value)
      VxeUI.modal.message({ content: '保存成功', status: 'success' })
    } else {
      VxeUI.modal.message({ content: '没有需要保存的数据', status: 'warning' })
    }
  } catch (error) {
    showErrorMessage('保存失败', error)
  } finally {
    loading.value = false
  }
}

// 设置附件表格引用
const setAttachTableRef = (el: any, code: string) => {
  if (el) {
    childAttachTableRefs.value[code] = el
  }
}

// 获取附件表格表单数据
const getAttachTableFormData = async () => {
  for (const pcode in childAttachTableRefs.value) {
    const child = childAttachTableRefs.value[pcode]
    if (child) {
      const datas = child.getFormData()
      for (const code in datas) {
        await setFormValues(pcode, code, datas[code], 1)
      }
    }
  }
}

// 设置表单值
const setFormValues = async (pcode: string, code: string, valData: any, rind: number) => {
  if (!valData) return
  
  const strKey = `${pcode}_${code}`
  const item = tplItemMap.value[strKey]
  
  if (!item) {
    console.warn(`未找到对应的模板项: ${strKey}`)
    return
  }
  
  const vals = Array.isArray(valData) ? valData.join(',') : String(valData)
  
  const tempForm: FormData = {
    id: null,
    rind,
    taskid: queryParam.value.taskId,
    tplid: queryParam.value.tplId,
    tplcode: code,
    itemid: item.itemid,
    itempid: item.pid,
    content: vals
  }
  
  formValues.value.push(tempForm)
}

// 加载数据
const setData = async () => {
  try {
    loading.value = true
    
    // 清空表单数据
    Object.keys(formData).forEach(key => delete formData[key])
    
    await setTplItemMap()
    
    // 查询记录数据
    const recordData = await queryRecord({
      taskid: queryParam.value.taskId,
      tplid: queryParam.value.tplId
    })
    
    // 构建数据映射
    const valueMap: Record<string, string> = {}
    recordData.forEach((data: any) => {
      const key = `${data.itempid}_${data.itemid}_${data.rind}`
      valueMap[key] = data.content
    })
    
    // 设置主表单数据
    Object.keys(tplItemMap.value).forEach(strKey => {
      const item = tplItemMap.value[strKey]
      const dataKey = `${item.pid}_${item.itemid}_1`
      const dataVal = valueMap[dataKey]
      
      if (item.formTp === 'checkbox') {
        formData[strKey] = dataVal?.split(',') || []
      } else {
        formData[strKey] = dataVal || ''
      }
    })
    
    // 设置附件表格数据
    Object.keys(childAttachTableRefs.value).forEach(pcode => {
      const child = childAttachTableRefs.value[pcode]
      const matchingKeys = Object.keys(tplItemMap.value).filter(key => key.startsWith(pcode + '_'))
      const matchingObjects = matchingKeys.map(key => tplItemMap.value[key])
      
      const attachTableData: Record<string, any> = {}
      matchingObjects.forEach(tmpData => {
        const dataKey = `${tmpData.pid}_${tmpData.itemid}_1`
        const dataVal = valueMap[dataKey]
        
        if (tmpData.formTp === 'checkbox') {
          attachTableData[tmpData.code] = dataVal?.split(',') || []
        } else {
          attachTableData[tmpData.code] = dataVal || ''
        }
      })
      
      child.setFormData(attachTableData)
    })
  } catch (error) {
    showErrorMessage('加载数据失败', error)
  } finally {
    loading.value = false
  }
}

// 设置模板项映射
const setTplItemMap = async () => {
  try {
    const tplItems = await allTplItems({
      tplid: queryParam.value.tplId,
    })
    
    const map: Record<string, TplItemInfo> = {}
    tplItems.forEach(item => {
      const strKey = `${item.pcode}_${item.xmlcode}`
      map[strKey] = {
        pid: item.pid,
        itemid: item.id,
        formTp: item.formTp,
        code: item.xmlcode
      }
    })
    
    tplItemMap.value = map
  } catch (error) {
    showErrorMessage('加载模板项失败', error)
  }
}

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

// 验证数据
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 reservedWords = ['and', 'or', 'not', 'equal', 'less', 'greater', 'if', 'else', 'true', 'false']
  
  // 提取字段名
  const fieldNames = formula.match(/\b[A-Za-z][A-Za-z0-9_]*\b/g) || []
  const uniqueFields = [...new Set(fieldNames.filter(f => 
    !reservedWords.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 && value !== '') {
      expression = expression.replace(
        new RegExp(`\\b${fieldName}\\b`, 'g'), 
        `Number(${value})`
      )
    }
  }
  
  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 findEarliestFormulaForField = (
  formulas: FormulaItem[], 
  field: string
): { formula: FormulaItem | null, index: number } => {
  let result = { formula: null, index: Infinity }
  
  formulas?.forEach((f: FormulaItem, idx: number) => {
    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 refreshHelpIcons = () => {
  console.log('刷新帮助图标...')
  
  tableFormData.forEach((row: any) => {
    if (row.content && Array.isArray(row.content)) {
      row.content.forEach((item: any) => {
        if (item.field) {
          const key = getFieldKey(row.code, item.field)
          const hasRight = userAllocItems.value.includes(key)
          
          if (hasRight) {
            const formulaResult = findEarliestFormulaForField(validFormula.value, item.field)
            item.hasValidFormula = !!formulaResult.formula
            item.matchedFormula = formulaResult.formula || null
          } else {
            item.hasValidFormula = false
            item.matchedFormula = null
          }
        }
      })
    }
  })
  
  nextTick(() => {
    console.log('帮助图标刷新完成')
  })
}

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

// 显示帮助图标
const showHelpIcon = (rowCode: string, field: string, item: any): boolean => {
  if (item.hasValidFormula !== undefined) {
    return item.hasValidFormula === true
  }
  
  const key = getFieldKey(rowCode, field)
  const hasRight = userAllocItems.value.includes(key)
  
  if (!hasRight) return false
  
  const formulaResult = findEarliestFormulaForField(validFormula.value, field)
  return !!formulaResult.formula
}

// 设置表单项权限
const setFormItemRight = () => {
  console.log('开始设置表单权限...')
  console.log('userAllocItems 数量:', userAllocItems.value.length)
  console.log('validFormula 数量:', validFormula.value.length)
  
  tableFormData.forEach((row: any) => {
    if (row.content && Array.isArray(row.content)) {
      row.content.forEach((item: any) => {
        if (item.field) {
          const key = getFieldKey(row.code, item.field)
          item.hasRight = userAllocItems.value.includes(key)
          
          console.log(`字段 ${key}: hasRight = ${item.hasRight}`)
          
          if (item.hasRight) {
            const formulaResult = findEarliestFormulaForField(validFormula.value, item.field)
            item.hasValidFormula = !!formulaResult.formula
            item.matchedFormula = formulaResult.formula || null
            console.log(`字段 ${key}: hasValidFormula = ${item.hasValidFormula}`)
          } else {
            item.hasValidFormula = false
            item.matchedFormula = null
          }
        }
      })
    }
  })
  
  console.log('表单权限设置完成')
}

// 历史数据填报
const handleOpenHistoryDrawer = () => {
  historyDrawerVisible.value = true
}

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

// 错误消息显示
const showErrorMessage = (title: string, error: any) => {
  const message = error instanceof Error ? error.message : String(error)
  VxeUI.modal.message({ 
    content: `${title}: ${message}`, 
    status: 'error' 
  })
}

// 合并单元格配置
const mergeCells = ref([
  { row: 7, col: 2, rowspan: 1, colspan: 2 }
])
</script>

<style lang="less" scoped>
.bank-report-table {
  font-family: "SimSun", "宋体", serif;
  font-size: 12px;
  color: #000;
  margin: 5px auto;
  width: 90%;
  position: relative;
}

/* 表格样式 */
.custom-table {
  width: 100%;
  border: 1px solid #000;
  border-collapse: collapse;
  
  .vxe-header--column,
  .vxe-body--column {
    border-right: 1px solid #000;
    border-bottom: 1px solid #000;
    padding: 5px;
  }
}

/* 加载遮罩层 */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
}

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

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

.loading-text {
  margin-top: 10px;
  color: #666;
  font-size: 14px;
}

/* 内容单元格 */
.content-cell {
  line-height: 1.8;
  min-height: 30px;
}

/* 输入框样式 */
.table-input,
.vxe-input {
  height: 24px;
  line-height: 24px;
  min-width: 150px;
  margin: 0 2px;
  padding: 0 5px;
  border: 1px solid #d9d9d9;
  border-radius: 2px;
  background: #fff;
  text-align: left;
  
  &:disabled {
    background-color: #f5f5f5;
    cursor: not-allowed;
  }
}

/* 表单组件样式 */
.vxe-radio-group,
.vxe-checkbox-group {
  display: inline-flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-right: 5px;
  max-width: 100%;
}

.vxe-radio,
.vxe-checkbox {
  margin: 2px 5px;
  white-space: nowrap;
}

.radio-group,
.checkbox-group {
  display: inline-block;
  margin-right: 5px;
  max-width: 99%;
}

/* 单位样式 */
.unit {
  margin-left: 4px;
  color: #666;
  font-size: 12px;
}

/* 图标样式 */
.input-wrapper {
  display: inline-flex;
  align-items: center;
  position: relative;
  gap: 4px;
}

.help-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  background-color: #1890ff;
  color: white;
  border-radius: 50%;
  font-size: 11px;
  cursor: pointer;
  user-select: none;
  
  &:hover {
    background-color: #40a9ff;
  }
}

.error-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  background-color: #ff4d4f;
  color: white;
  border-radius: 50%;
  font-size: 11px;
  cursor: pointer;
  user-select: none;
  
  &:hover {
    background-color: #ff7875;
  }
}

/* 工具提示样式 */
.tooltip {
  position: absolute;
  top: 100%;
  left: 0;
  margin-top: 4px;
  background-color: #333;
  color: #fff;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  z-index: 1000;
  white-space: normal;
  max-width: 300px;
  word-wrap: break-word;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  
  &::before {
    content: '';
    position: absolute;
    top: -4px;
    left: 10px;
    border-left: 4px solid transparent;
    border-right: 4px solid transparent;
    border-bottom: 4px solid #333;
  }
}

.error-tooltip {
  position: absolute;
  top: 100%;
  left: 0;
  margin-top: 4px;
  background-color: #fff2f0;
  color: #ff4d4f;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  z-index: 1000;
  white-space: normal;
  max-width: 300px;
  word-wrap: break-word;
  border: 1px solid #ffccc7;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  
  &::before {
    content: '';
    position: absolute;
    top: -4px;
    left: 10px;
    border-left: 4px solid transparent;
    border-right: 4px solid transparent;
    border-bottom: 4px solid #ffccc7;
  }
}

/* 验证公式提示 */
.validation-tooltip {
  position: fixed;
  background-color: #333;
  color: #fff;
  padding: 12px;
  border-radius: 4px;
  font-size: 12px;
  z-index: 1001;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  max-width: 400px;
  
  .tooltip-content {
    margin: 0;
    white-space: pre-wrap;
    word-break: break-word;
  }
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .bank-report-table {
    width: 95%;
  }
  
  .table-input,
  .vxe-input {
    min-width: 120px;
  }
}
</style>