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

    <MyVxeTable
      :title="tableFormData.project"
      :data="tableFormData.data"
      :columns="tableFormData.columns"
      :pcode="tableFormData.code"
      :showFooter="tableFormData.showFooter"
      :rowHeight="100"
      style="margin:0px;padding:0px;height:100%"
      ref="refMyVxeTable"
    />

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

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

<script lang="ts" setup>
import MyVxeTable from '../tableComponents/MyVxeTable.vue'
import HistoryFillCheck from './check/historyFillCheck.vue'
import ValidationDrawer from './check/ValidationDrawer.vue'
import { tableFormData } from '../../data/tb4.data';
import { ref, reactive, nextTick, onMounted, toRaw, computed } from 'vue'
import { VxeUI } from 'vxe-table'
import { batchSaveOrUpdateBeforeDelete, queryRecord } 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 refMyVxeTable = ref();
const validationDrawerRef = ref();
const tplItemMap = ref({});
const historyFillCheckRef = ref<any>(null);
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,
    })
  } 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 => {
  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 getVxeTableFormData();

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

const getVxeTableFormData  = async () => {
  const formData = await refMyVxeTable.value.getFormData()
  let rind = 0
  let pcode = tableFormData.code;
  for(const obj of formData.datas) {
    rind++
    Object.keys(obj).forEach(code => {  
      setFormValues(pcode,code,obj[code],rind)
    });
  }
  
}


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

    loading.value = true
    const taskId = queryParam.value.taskId
    const tplid = queryParam.value.tplId
    Object.keys(formData).forEach(key => delete formData[key])
    await setTplItemMap();
    const recordData = await queryRecord({taskid: taskId, tplid: tplid})
    let valueObj = {}
    
    for(let data of recordData) {
      valueObj[data.itempid+"_" + data.itemid+"_"+ data.rind] = data["content"]
    }

    const rowsMap = {};
    for (const strKey of Object.keys(tplItemMap.value)) {
      const tmpData = tplItemMap.value[strKey];
      if (!tmpData) continue;
      
      const { pid, itemid, code } = tmpData;
      const valKeys = Object.keys(valueObj).filter(k => 
        k.startsWith(`${pid}_${itemid}_`)
      );
      
      for (const valKey of valKeys) {
        const parts = valKey.split('_');
        const rind = parts[2];
        
        if (!rowsMap[rind]) {
          rowsMap[rind] = {};
        }
        
        rowsMap[rind][code] = valueObj[valKey];
      }
    }

    const tableDatas = Object.values(rowsMap);
    refMyVxeTable.value.setFormData(tableDatas);
    
    } catch (error) {
      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,
    })

    tplItem.forEach(item => {
      let strKey = item.pcode + "_" + item.xmlcode;
      tplItemMap.value[strKey] = {pid:item.pid, itemid:item.id, formTp:item.formTp, code:item.xmlcode};
    })
  } catch (error) {
    VxeUI.modal.message({ content: `加载数据失败: ${error.message}`, status: 'error' })
  }
}

const refreshHelpIcons = () => {
  console.log('刷新帮助图标...');
  tableFormData.columns.forEach((column: any) => {
    if (column.field) {
      const key = getFieldKey(tableFormData.code, column.field);
      const hasRight = userAllocItems.value.includes(key);
      
      if (hasRight) {
        const formulaResult = findEarliestFormulaForField(validFormula.value, column.field);
        column.hasValidFormula = !!formulaResult.formula;
        column.matchedFormula = formulaResult.formula || null;
      } else {
        column.hasValidFormula = false;
        column.matchedFormula = null;
      }
    }
  });
  
  nextTick(() => {
    console.log('帮助图标刷新完成');
  });
};

const setFormItemRight = () => {
  tableFormData.columns.forEach((column: any) => {
    if (column.field) {
      const key = getFieldKey(tableFormData.code, column.field);
      column.hasRight = userAllocItems.value.includes(key);
      
      if (column.hasRight) {
        const { formula } = findEarliestFormulaForField(validFormula.value, column.field);
        column.hasValidFormula = !!formula;
        column.matchedFormula = formula;
      }
    }
  });
};

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

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

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

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

.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: 80px;
  margin: 0 2px;
}

.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;
  line-height: 50px;
}

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

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

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px 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>