<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 class="toolbar-info">
          <span class="info-label">填报任务：{{ queryParam?.taskName }}</span>
          <span class="info-label">表格：{{ 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"
      show-header-overflow
      :data="tableFormData"
      :column-config="{ resizable: true }"
      :row-config="{ resizable: true }"
      height="auto"
      class="custom-table"
    >
      <vxe-column field="serialNumber" title="序号" width="80"></vxe-column>
      <vxe-column field="project" title="项目" width="100">
        <template #default="{ row }">
          <span class="project-title">{{ row.project }}</span>
        </template>
      </vxe-column>
      <vxe-column field="content" title="内容" row-resize>
        <template #default="{ row }">
          <div class="content-cell">
            <template v-if="row.type === 'MultiColumnTable'">
              <MultiColumnTable
                :title="row.project"
                :columnsPerRow="1"
                :records="[]"
                :fields="row.content"
                :ref="(el) => setMultiColumnTableRef(el, row.code)"
                class="embedded-table"
              />
            </template>
            <template v-else>
              <template v-for="(item, index) in row.content" :key="index">
                <span v-if="item.type === 'text'">
                  {{item.value}}：
                </span>
                <span v-else-if="item.type === 'br'"><br></span>
                
                <span v-else-if="item.type === 'radio-group-extraFields'" class="radio-group">
                  <vxe-radio-group v-model="formData[getFieldKey(row.code, item.field)]">
                    <vxe-radio 
                      v-for="(opt, optIndex) in item.options" 
                      :key="`opt-${optIndex}`" 
                      :label="opt.label" 
                      class="radio-option"
                    >
                      <div class="option-content">
                        <div class="main-label">{{ opt.label }}</div>
                        <template v-if="shouldShowExtraFields(opt, row.code, item.field)">
  
                          <template v-if="opt.extraField">
                            <span >
                              <span >{{ opt.extraLabel }}</span>
                              <component  style="margin:10px;padding:0px;width: 300px;"
                                :is="getExtraFieldComponent(opt.extraFormType)"
                                v-model="formData[getFieldKey(row.code, opt.extraField)]"
                                :options="opt.extraOptions"
                                
                              />
                              <span v-if="opt.extraUnit" class="unit">{{ opt.extraUnit }}</span>
                            </span>
                          </template>
                          
                        </template>
                      </div>
                    </vxe-radio>
                  </vxe-radio-group>
                </span>
                <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"
                      :status="getInputStatus(row.code, item.field)"
                      @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="getInputStatus(row.code, item.field) === 'error'"
                      class="error-icon"
                      @click.stop="toggleErrorTooltip(row.code, item.field)"
                    >
                      <i class="vxe-icon-error">✗</i>
                    </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
                    >
                      {{ getErrorMessage(row.code, item.field) }}
                      <br>
                      <span style="color: #ffcccc;">
                        公式: {{ item.matchedFormula?.formula }}
                      </span>
                    </div>
                  </div>
                </template>
              </template>
            </template>
          </div>
        </template>
      </vxe-column>
    </vxe-table>

    <!-- 历史填报检查组件 -->
    <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 MultiColumnTable from '../tableComponents/MultiColumnTable.vue'
import HistoryFillCheck from './check/historyFillCheck.vue'
import ValidationDrawer from './check/ValidationDrawer.vue'

import { tableFormData } from '../../data/tb2.data'
import { ref, reactive, nextTick, onMounted,computed} from 'vue'
import { VxeUI } from 'vxe-table'
import { batchSaveOrUpdateBeforeDelete, queryRecord } 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'


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

const route = useRoute()
const tableRef = ref()
const tplItemMap = ref<Record<string, any>>({})
const loading = ref(false)
const formData = reactive<Record<string, any>>({})
const formValues = ref<FormData[]>([])
const childMultiTableRefs = ref<Record<string, any>>({})

const validationDrawerRef = ref<any>(null)

const showTooltip = ref(false)
const hoveredKey = ref('')
const showErrorTooltip = ref(false)
const hoveredErrorKey = ref('')
const inputErrors = ref<Record<string, any>>({})

const isInitialized = ref(false)

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

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

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

// 权限相关状态
const userAllocItems = ref<string[]>([])
const validFormula = ref<any[]>([])
const drawerVisible = ref(false)
const historyDrawerVisible = ref(false)
const historyFillCheckRef = ref<any>(null)

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

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)
  }
  if (route.query.comfrom) {
    queryParam.value.comfrom = String(route.query.comfrom)
  }

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

    validFormula.value = await getTblvalidFormula({
      tplid: queryParam.value.tplId,
    })
    
    await setTplItemMap()
    setFormItemRight()
    await setData()
    
    isInitialized.value = true
    
    setTimeout(() => {
      refreshHelpIcons()
    }, 300)
  } catch (error) {
    console.error('获取权限或验证公式失败:', error)
    VxeUI.modal.message({ 
      content: `初始化页面失败: ${error instanceof Error ? error.message : String(error)}`, 
      status: 'error' 
    });
  } finally {
    loading.value = false
  }
})

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

const saveBatch = async () => {
  try {
    formValues.value = []
    loading.value = true
    await nextTick()
    for (const strKey in formData) {
      const valData = formData[strKey]
      if (valData) {
        const [pcode, code] = strKey.split('_')
        await setFormValues(pcode, code, valData, 1)
      }
    }
   
    await getAllMultiTableFormData()

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

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


const setFormValues = async (pcode: string, code: string, valData: any, rind: number) => {
  if (!valData) return

  if(Array.isArray(valData)&& valData.length==0) return
    
  const vals = Array.isArray(valData) ? valData.join(',') : valData
  const strKey = `${pcode}_${code}`
  const item = tplItemMap.value[strKey]
  const { pid, itemid } = item ?? {}

  const tempForm: FormData = {
    id: null,
    rind: rind,
    taskid: queryParam.value.taskId,
    tplid: queryParam.value.tplId,
    tplcode: code,
    itemid: itemid,
    itempid: pid,
    content: vals
  }

  formValues.value.push(tempForm)
}

async function setData() {
  try {
    loading.value = true;
    const taskId = queryParam.value.taskId;
    const tplid = queryParam.value.tplId;
    
    Object.keys(formData).forEach(key => delete formData[key]);
    
    await setTplItemMap();
    const recordData = await queryRecord({ taskid: taskId, tplid: tplid });
    
    const valueMap = recordData.reduce((acc, data) => {
      const key = `${data.itempid}_${data.itemid}_${data.rind}_${data.tplcode}`;
      acc[key] = data.content;
      return acc;
    }, {});
    
    await fillTableData(valueMap);
  } catch (error) {
    console.error('加载数据失败:', error);
    VxeUI.modal.message({ 
      content: `加载数据失败: ${error instanceof Error ? error.message : String(error)}`, 
      status: 'error' 
    });
  } finally {
    loading.value = false;
  }
}

async function fillTableData(valueMap) {
  for (const row of tableFormData) {
    if (!row.type && row.content) {
      await fillSimpleFields(row, valueMap);
    } else if (row.type === 'MultiColumnTable' && row.content) {
      await fillMultiColumnTable(row, valueMap);
    }
  }
}

async function fillSimpleFields(row, valueMap) {
  if (!row.content || !Array.isArray(row.content)) return;
  
  for (const item of row.content) {
    if (!item.field || item.field.length === 0) continue;
    
    const fieldKey = getFieldKey(row.code, item.field);
    const tplItem = tplItemMap.value[fieldKey];
    if (!tplItem) continue;
    
    const { pid, itemid, formTp, code } = tplItem;
    const dataKey = `${pid}_${itemid}_1_${code}`;
    const dataVal = valueMap[dataKey];
    
    if (!dataVal) continue;
    
    if (formTp === 'checkbox') {
      formData[fieldKey] = dataVal.split(',').filter(Boolean);
    } else {
      formData[fieldKey] = dataVal;
    }
    
    if (item.type === 'radio-group-extraFields') {
      await fillExtraFields(row, item, valueMap);
    }
  }
}

async function fillExtraFields(row, item, valueMap) {
  const options = item.options || [];
  for (const opt of options) {
    if (!opt.extraField || opt.extraField.length === 0) continue;
    
    const fieldKey = getFieldKey(row.code, opt.extraField);
    const tplItem = tplItemMap.value[fieldKey];
    if (!tplItem) continue;
    
    const { pid, itemid, code } = tplItem;
    const dataKey = `${pid}_${itemid}_1_${code}`;
    formData[fieldKey] = valueMap[dataKey] || '';
  }
}

async function fillMultiColumnTable(row, valueMap) {
  const child = childMultiTableRefs.value[row.code];
  if (!child || !Array.isArray(row.content)) return;
  
  const rowsMap = {};
  const allFields = collectAllFields(row.content);
  
  for (const fieldInfo of allFields) {
    const fieldKey = getFieldKey(row.code, fieldInfo.field);
    const tplItem = tplItemMap.value[fieldKey];
    if (!tplItem) continue;
    
    const { pid, itemid, code, formTp } = tplItem;
    const valueKeys = Object.keys(valueMap).filter(k => 
      k.startsWith(`${pid}_${itemid}_`)
    );
    
    for (const valueKey of valueKeys) {
      const parts = valueKey.split('_');
      const rind = parts[2];
      
      if (!rowsMap[rind]) {
        rowsMap[rind] = {};
      }
      
      let value = valueMap[valueKey];
      if (formTp === 'checkbox' && value) {
        value = value.split(',').filter(Boolean);
      }
      
      rowsMap[rind][code] = value;
    }
  }
  
  const tableDatas = Object.values(rowsMap);
  if (child && tableDatas.length > 0) {
    child.setFormData(tableDatas);
  }
}

function collectAllFields(content, fields = []) {
  for (const item of content) {
    if (item.field) {
      fields.push({ field: item.field, formType: item.formType });
    }
    
    if (item.otherField) {
      fields.push({ field: item.otherField, formType: 'input' });
    }
    
    if (item.formType === 'combinaform' && item.childs) {
      collectAllFields(item.childs, fields);
    }
    
    if (item.formType === 'select' && item.options) {
      for (const opt of item.options) {
        if (opt.extraFields) {
          collectAllFields(opt.extraFields, fields);
        }
        if (opt.otherOption && opt.extraField) {
          fields.push({ field: opt.extraField, formType: 'input' });
        }
      }
    }
    
    if (item.formType === 'radio-group-extraFields' && item.extraFields) {
      for (const key in item.extraFields) {
        collectAllFields(item.extraFields[key], fields);
      }
    }
    
    if (item.formType === 'AttachTable' && item.gridOptions && item.gridOptions.datas) {
      for (const data of item.gridOptions.datas) {
        for (const key in data) {
          if (data[key] && typeof data[key] === 'object' && data[key].field) {
            fields.push({ field: data[key].field, formType: data[key].formType });
            if (data[key].otherField) {
              fields.push({ field: data[key].otherField, formType: 'input' });
            }
          }
        }
      }
    }
  }
  
  return fields;
}

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

    tplItemMap.value = tplItem.reduce((acc, item) => {
      const strKey = `${item.pcode}_${item.xmlcode}`
      acc[strKey] = {
        pid: item.pid,
        itemid: item.id,
        formTp: item.formTp,
        code: item.xmlcode
      }
      return acc
    }, {} as Record<string, any>)
  } catch (error) {
    console.error('加载数据失败:', error)
    VxeUI.modal.message({ content: `加载数据失败: ${error instanceof Error ? error.message : String(error)}`, status: 'error' })
  }
}

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

const 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 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 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 getInputStatus = (rowCode: string, itemField: string): 'default' | 'error' => {
  const key = getFieldKey(rowCode, itemField)
  return inputErrors.value[key] ? 'error' : ''
}

const getErrorMessage = (rowCode: string, itemField: string): string => {
  const key = getFieldKey(rowCode, itemField)
  return inputErrors.value[key]?.message || ''
}

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

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


 function shouldShowExtraFields(opt, rowCode, itemField) {
    return formData[getFieldKey(rowCode, itemField)] === opt.label && 
          (opt.extraField || opt.extraFields)
  }
  

  function getExtraFieldComponent(type) {
    switch(type) {
      case 'radio': return 'vxe-radio-group'
      case 'checkbox': return 'vxe-checkbox-group'
      case 'date': return 'vxe-input'
      case 'number': return 'vxe-input'
      default: return 'vxe-input'
    }
  }


</script>

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

.toolbar-info {
  margin: 10px;
  
  .info-label {
    font-weight: bold;
    margin-left: 20px;
    
    &:first-child {
      margin-left: 0;
    }
  }
}

.custom-table {
  width: 100%;
  border: 1px solid #000;
  border-collapse: collapse;
  
  :deep(.vxe-header--column),
  :deep(.vxe-body--column) {
    border-right: 1px solid #000;
    border-bottom: 1px solid #000;
    padding: 5px;
  }
}

.content-cell {
  line-height: 1.8;
  padding: 5px;
}

.project-title {
  font-weight: bold;
  font-size: 14px;
}

.table-input,
.vxe-input {
  height: 24px;
  line-height: 24px;
  min-width: 150px;
  margin: 0 2px;
  padding: 0 5px;
  border: none;
  border-bottom: 1px solid #333;
  background: transparent;
  text-align: left;
}

.extra-input {
  width: 100%;
  margin-left: 5px;
}

.extra-fields-container {
  margin-left: 0px;
  margin-top: 5px;
}

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

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

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

.unit {
  margin-left: 3px;
  color: #666;
}

.embedded-table {
  margin: 0;
  padding: 0;
  border: none;
}

.radio-option {
  display: block;
  margin-bottom: 1px;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.radio-option:hover {
  background-color: #f5f5f5;
}

/* 选项内容布局 */
.option-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.main-label {
  font-weight: 500;
}

/* 额外字段样式 */
.extra-field {
  display: flex;
  align-items: left;
  gap: 8px;
  margin-left: 4px;
  padding: 4px 0;
}

.extra-label {
  color: #666;
  min-width: 80px;
}

.extra-input {
  width: 300px;
}

.unit {
  color: #999;
  margin-left: 4px;
}

/* 单选组内部间距 */
.vxe-radio-group {
  flex-direction: column;
  gap: 8px;
}

/* 加载遮罩层 */
.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;
}

/* 校验结果 */
.validation-results {
  padding: 20px;
}

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

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

.summary-label {
  font-weight: 500;
  color: #666;
}

.summary-value {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

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

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

.results-list {
  max-height: 500px;
  overflow-y: auto;
}

.result-item {
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.result-item:hover {
  transform: translateX(5px);
}

.result-item.success {
  background: #f6ffed;
  border: 1px solid #b7eb8f;
}

.result-item.error {
  background: #fff2f0;
  border: 1px solid #ffccc7;
}

.result-field {
  font-weight: bold;
  margin-bottom: 4px;
}

.result-desc {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.result-value {
  font-size: 12px;
  color: #888;
}

.result-error {
  font-size: 12px;
  color: #ff4d4f;
  margin-top: 4px;
}

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

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

</style>
