<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>
        <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>

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

    <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'">
              <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" style="margin-right: 10px"></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; </template>
                </span>

                <template v-else-if="item.type === 'MultiColumnTable'">
                  <MultiColumnTable
                    :title="item.project"
                    :records="[]"
                    :fields="item.content"
                    :ref="(el) => setMultiColumnTableRef(el, item.code)"
                    style="margin: 0px; padding: 0px"
                  />
                </template>

                <template v-else-if="item.type === 'AttachTable'">
                  <AttachTable
                    :title="item.project"
                    :records="item.datas"
                    :fields="item.content"
                    :pcode="item.code"
                    :calcSum="item.calcSum"
                    :showFooter="item.showFooter"
                    :ref="(el) => setAttachTableRef(el, item.code)"
                    style="margin: 0px; padding: 0px"
                  />
                </template>

                <span v-else-if="item.type === 'radio-group'" class="radio-group">
                  <vxe-radio-group v-model="formData[row.code + '_' + item.field]">
                    <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 === 'radio-group-extraFields'" class="radio-group">
                  <vxe-radio-group v-model="formData[row.code + '_' + item.field]">
                    <vxe-radio v-for="(opt, optIndex) in item.options" :key="optIndex" :label="opt.value">{{ opt.label }}</vxe-radio>
                  </vxe-radio-group>
                  <div v-if="formData[row.code + '_' + item.field]" class="extra-fields">
                    <template v-for="(option, optIndex) in item.options" :key="optIndex">
                      <template v-if="option.value === formData[row.code + '_' + item.field] && option.extraFields">
                        <template v-for="(ccopt, ccind) in option.extraFields" :key="ccind">
                          <span>{{ ccopt.label }}: </span>
                          <template v-if="ccopt.formType === 'number'">
                            <vxe-input v-model="formData[row.code + '_' + ccopt.field]" type="number" style="width: 80px"></vxe-input>
                          </template>
                          <template v-else-if="ccopt.formType === 'input'">
                            <vxe-input v-model="formData[row.code + '_' + ccopt.field]" style="width: 250px"></vxe-input>
                          </template>
                          <template v-else>
                            <vxe-input v-model="formData[row.code + '_' + ccopt.field]" :type="ccopt.formType" style="width: 100px"></vxe-input>
                          </template>
                          <span class="unit"> {{ ccopt.unit }}</span>
                        </template>
                      </template>
                    </template>
                  </div>
                </div>
                <div v-else-if="item.type === 'checkbox-group'" class="checkbox-group">
                  <span class="checkbox-group" style="max-width: 800px; margin-left: 20px">
                    <vxe-checkbox-group v-model="formData[row.code + '_' + item.field]">
                      <vxe-checkbox v-for="(opt, optIndex) in item.options" :key="optIndex" :label="opt" style="line-height: 30px; margin-left: 0px">
                        {{ opt }}
                      </vxe-checkbox>
                      <template v-if="item.otherOption">
                        <vxe-checkbox label="其他" style="margin: 0px"> 其他： </vxe-checkbox>
                        <vxe-input
                          v-model="formData[row.code + '_' + item.otherField]"
                          :disabled="!(formData[row.code + '_' + item.field]?.indexOf('其他') > -1)"
                          style="width: 300px"
                        >
                        </vxe-input>
                      </template>
                    </vxe-checkbox-group>
                  </span>
                </div>

                <div v-else-if="item.type === 'checkboxAndInput'">
                  <span class="checkbox-group">
                    <vxe-checkbox-group v-model="formData[row.code + '_' + item.field]">
                      <vxe-checkbox v-for="(opt, optIndex) in item.options" :key="optIndex" :label="opt" style="display: block; margin: 0px 0px">
                        {{ opt }}
                        <vxe-input
                          type="number"
                          v-model="formData[row.code + '_' + item.optionItemField[optIndex]]"
                          style="width: 100px; margin: 0px"
                        >
                        </vxe-input>
                        <span class="unit"> {{ item.optionItemUint }}</span>
                      </vxe-checkbox>
                    </vxe-checkbox-group>
                  </span>
                </div>
                <div v-else-if="item.type === 'yesno'" class="yesno-group">
                  <vxe-radio-group v-model="formData[row.code + '_' + item.field]">
                    <vxe-radio label="是">是</vxe-radio>
                    <vxe-radio label="否">否</vxe-radio>
                  </vxe-radio-group>
                  <div v-if="formData[row.code + '_' + item.field] === '是'" class="extra-fields">
                    <!-- 处理单个extraField的情况 -->
                    <template v-if="item.extraField">
                      <div style="margin-top: 5px">
                        <span>{{ item.extraLabel || '' }}: </span>
                        <vxe-input v-model="formData[row.code + '_' + item.extraField]" style="width: 100px"></vxe-input>
                        <span v-if="item.unit" class="unit"> {{ item.unit }}</span>
                      </div>
                    </template>
                    <!-- 处理extraFields数组的情况 -->
                    <template v-else-if="item.extraFields">
                      <template v-for="(ccopt, ccind) in item.extraFields" :key="ccind">
                        <div style="margin-top: 5px">
                          <span>{{ ccopt.label }}: </span>
                          <template v-if="ccopt.formType === 'input'">
                            <vxe-input v-model="formData[row.code + '_' + ccopt.field]" style="width: 250px"></vxe-input>
                          </template>
                          <template v-else-if="ccopt.formType === 'checkbox'">
                            <vxe-checkbox-group v-model="formData[row.code + '_' + ccopt.field]">
                              <vxe-checkbox v-for="(opt, optIndex) in ccopt.options" :key="optIndex" :label="opt">{{ opt }}</vxe-checkbox>
                            </vxe-checkbox-group>
                            <template v-if="ccopt.otherOption">
                              <div style="margin-top: 5px; margin-left: 20px">
                                其他：<vxe-input
                                  v-model="formData[row.code + '_' + ccopt.otherField]"
                                  :disabled="
                                    !(
                                      Array.isArray(formData[row.code + '_' + ccopt.field]) &&
                                      formData[row.code + '_' + ccopt.field].indexOf('其他') > -1
                                    )
                                  "
                                  style="width: 200px"
                                >
                                </vxe-input>
                              </div>
                            </template>
                          </template>
                          <template v-else-if="ccopt.formType === 'radio'">
                            <vxe-radio-group v-model="formData[row.code + '_' + ccopt.field]">
                              <vxe-radio v-for="(opt, optIndex) in ccopt.options" :key="optIndex" :label="opt">{{ opt }}</vxe-radio>
                            </vxe-radio-group>
                            <template v-if="ccopt.otherOption && formData[row.code + '_' + ccopt.field] === '其他'">
                              <div style="margin-top: 5px; margin-left: 20px">
                                其他：<vxe-input v-model="formData[row.code + '_' + ccopt.otherField]" style="width: 200px"></vxe-input>
                              </div>
                            </template>
                          </template>
                        </div>
                      </template>
                    </template>
                  </div>
                </div>
                <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="item.style"
                      @blur="handleInputBlur(row.code, item.field, item.matchedFormula?.formula)"
                    />
                    <span 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="点击查看错误详情"
                    >
                      <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) && item.matchedFormula" 
                      class="tooltip" 
                      @click.stop
                    >
                      {{ item.matchedFormula?.des || '暂无校验规则' }}
                    </div>
                  </div>
                </template>
              </template>
            </template>
          </div>
        </template>
      </vxe-column>
    </vxe-table>

    <!-- 历史填报检查组件 -->
    <HistoryFillCheck ref="historyFillCheckRef" v-model="historyDrawerVisible" @close-drawer="closeHistoryDrawer" />
    <!-- 原有检查组件 -->
    <CheckTbData ref="refCheckTbData"></CheckTbData>
  </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 CheckTbData from './CheckTbData.vue';
  import HistoryFillCheck from './check/historyFillCheck.vue';
  import ValidationDrawer from './check/ValidationDrawer.vue';
  import { tableFormData } from '../../data/tb6.data';
  import { ref, reactive, nextTick, onMounted, toRaw, computed, watch } 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 refCheckTbData = ref();
  const historyFillCheckRef = ref<any>(null);
  const validationDrawerRef = ref();

  const route = useRoute();
  const tableRef = ref();
  const tplItemMap = ref({});
  const queryParam = ref({
    taskId: -1,
    taskName: '',
    tplId: -1,
    tplName: '',
    tplCode: '',
  });

  // 权限相关状态
  const userAllocItems = ref<string[]>([]);
  const validFormula = ref<any[]>([]);
  const drawerVisible = ref(false);
  const historyDrawerVisible = ref(false);
  const showTooltip = ref(false);
  const hoveredKey = ref('');
  const showErrorTooltip = ref(false);
  const hoveredErrorKey = ref('');
  const isInitialized = ref(false);

  interface FormData {
    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 InputError {
    message: string;
    formula: string;
    error?: string;
  }

  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,
      });
      
      console.log('获取到的权限:', userAllocItems.value.length);
      console.log('获取到的公式:', validFormula.value.length);
    } catch (error) {
      console.error('获取权限或验证公式失败:', error);
    }

    await setTplItemMap();
    await setFormItemRight();
    await setData();
    
    // 标记初始化完成
    isInitialized.value = true;
    
    // 延迟刷新一次，确保问号图标显示
    setTimeout(() => {
      refreshHelpIcons();
    }, 300);
  });

  const loading = ref(false);
  const formData = reactive({});
  const formValues = ref<FormData[]>([]);
  const inputErrors = ref<Record<string, InputError>>({});

  const fieldKeys = computed(() => Object.keys(formData));

  const getFieldKey = (rowCode: string, field: string): string => {
    return `${rowCode}_${field}`;
  };

  // 添加帮助图标显示条件计算
  const showHelpIcon = (rowCode: string, field: string, item: any): boolean => {
    // 如果已经有 hasValidFormula 属性，直接使用
    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 saveBatch = async () => {
    try {
      formValues.value = [];
      await getFillDatas();
      if (formValues.value.length > 0) {
        await batchSaveOrUpdateBeforeDelete(formValues.value);
        VxeUI.modal.message({ content: '保存成功', status: 'success' });
      } else {
        VxeUI.modal.message({ content: '没有需要保存的数据', status: 'warning' });
      }
    } catch (error: any) {
      VxeUI.modal.message({ content: `保存失败: ${error.message}`, status: 'error' });
    } finally {
      loading.value = false;
    }
  };

  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);
  };

  // 校验数据
  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) {
        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 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 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 handleValidationResultClick = (result: any) => {
    const message = `字段 ${result.field} 的校验结果: ${result.isValid ? '通过' : '失败'}`;
    const status = result.isValid ? 'success' : 'error';
    
    VxeUI.modal.message({ content: message, status });
  };

  // 打开历史填报抽屉
  const handleOpenHistoryDrawer = () => {
    historyDrawerVisible.value = true;
  };

  // 关闭历史填报抽屉
  const closeHistoryDrawer = () => {
    historyDrawerVisible.value = false;
  };

  // 添加刷新帮助图标的方法
  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('帮助图标刷新完成');
    });
  };

  // 原有检查方法
  async function checkDataOrig() {
    let tplName = queryParam.value.tplName;
    await getFillDatas();
    if (formValues.value.length > 0) {
      refCheckTbData.value.setIniData(tplName, formValues.value);
    }
  }

  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;
      }
      const shouldSkip = (key) => {
        const refsToCheck = [childMultiTableRefs.value, childAttachTableRefs.value];

        for (const refs of refsToCheck) {
          for (const pcode of Object.keys(refs)) {
            if (key.startsWith(pcode + '_')) {
              return true;
            }
          }
        }
        return false;
      };

      for (const strKey of Object.keys(tplItemMap.value)) {
        if (shouldSkip(strKey)) {
          continue;
        }

        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 || '';
        }
      }

      for (const pcode of Object.keys(childAttachTableRefs.value)) {
        const child = childAttachTableRefs.value[pcode];
        const matchingKeys = Object.keys(tplItemMap.value).filter((key) => key.startsWith(pcode + '_'));

        const attachTableData = {};
        for (const key of matchingKeys) {
          const tmpData = tplItemMap.value[key];
          if (!tmpData) continue;

          const { pid, itemid, formTp, code } = tmpData;
          const valueKey = `${pid}_${itemid}_1`;

          if (formTp === 'checkbox') {
            attachTableData[code] = valueObj[valueKey]?.split(',') || [];
          } else {
            attachTableData[code] = valueObj[valueKey] || '';
          }
        }

        child.setFormData(attachTableData);
      }

      for (const pcode of Object.keys(childMultiTableRefs.value)) {
        const child = childMultiTableRefs.value[pcode];
        const matchingKeys = Object.keys(tplItemMap.value).filter((key) => key.startsWith(pcode + '_'));

        const rowsMap = {};
        for (const key of matchingKeys) {
          const tmpData = tplItemMap.value[key];
          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);
        nextTick();
        child.setFormData(tableDatas);
      }
    } catch (error: any) {
      VxeUI.modal.message({
        content: `加载数据失败: ${error.message}`,
        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: any) {
      VxeUI.modal.message({ content: `加载数据失败: ${error.message}`, status: 'error' });
    } finally {
    }
  }
</script>

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

  /* 加载遮罩层样式 */
  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.8);
    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 2s linear infinite;
  }

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

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

  
  

  .custom-table {
    width: 100%;
    border: 1px solid #000;
  }

  .custom-table .vxe-header--column,
  .custom-table .vxe-body--column {
    border-right: 1px solid #000;
    border-bottom: 1px solid #000;
    padding: 5px;
  }

  .custom-table .vxe-cell {
    padding: 5px;
  }

  .content-cell {
    line-height: 1.8;
  }

  .table-input {
    width: 80px;
    margin: 0 2px;
  }

  .radio-group {
    display: inline-block;
    margin-right: 10px;
  }

  .checkbox-group {
    display: inline-block;
    margin-right: 10px;
  }

  .vxe-radio,
  .vxe-checkbox {
    margin-right: 4px;
    white-space: nowrap;
  }

  .vxe-input--inner {
    height: 24px;
    line-height: 24px;
    padding: 0 5px;
  }

  .vxe-radio--label,
  .vxe-checkbox--label {
    font-size: 12px;
  }

  .vxe-radio--icon,
  .vxe-checkbox--icon {
    font-size: 12px;
  }

  .vxe-radio-group,
  .vxe-checkbox-group {
    display: inline-block;
  }

  .bank-report-table {
    font-family: 'SimSun', '宋体', serif;
    font-size: 12px;
    color: #000;
    margin: 5px auto;
    width: 90%;
  }

  .custom-table {
    width: 100%;
    border: 1px solid #000;
  }

  .custom-table .vxe-header--column,
  .custom-table .vxe-body--column {
    border-right: 1px solid #000;
    border-bottom: 1px solid #000;
    padding: 5px;
  }

  .content-cell {
    line-height: 1.8;
  }

  .table-input {
    width: 150px;
    margin: 0 2px;
  }

  .radio-group {
    display: inline-block;
    margin-right: 10px;
  }

  .checkbox-group {
    display: inline-block;
    margin-right: 10px;
  }

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

    white-space: nowrap;
  }

  /* 附件样式 */
  .attachments {
    margin-top: 20px;
    width: 100%;
  }

  .attachments h4 {
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 10px;
  }

  .attachment-table {
    width: 100%;
    border: 1px solid #000;
  }

  .attachment-table .vxe-header--column,
  .attachment-table .vxe-body--column {
    border-right: 1px solid #000;
    border-bottom: 1px solid #000;
    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;
  }

  blockquote {
    padding: 0px 5px;
    color: black;
    cursor: pointer;
  }

  // 输入框包装器
  .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;
    opacity: 0;
    animation: fadeIn 0.5s forwards;
    animation-delay: 0.3s;
    
    &:hover {
      background: #bae7ff;
      transform: scale(1.1);
    }
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: scale(0.8);
    }
    to {
      opacity: 1;
      transform: scale(1);
    }
  }

  // 错误图标
  .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;
    }
  }
</style>