<!-- 高差边长方向值工具组件 -->
<template>
  <div class="ele-dif-side-land-dir-tool">
    <!-- 操作按钮区 -->
    <div class="tool-header">
      <div class="card-header-buttons">
        <el-button type="primary" @click="handleImport" size="small" icon="el-icon-upload">导入Excel</el-button>
        <el-button type="success" @click="handlePreview" size="small" :disabled="!hasImportedData" icon="el-icon-view">预览数据</el-button>
        <el-button type="warning" @click="handleCalculate" size="small" :disabled="!hasImportedData || calculating" :loading="calculating" icon="el-icon-caret-right">{{ calculating ? '计算中...' : '执行计算' }}</el-button>
        <el-button type="danger" @click="clearAll" size="small" :disabled="(!hasImportedData) && calculationResults.length === 0" plain icon="el-icon-delete">清空全部</el-button>
      </div>
    </div>

    <!-- 导入数据展示区 -->
    <div v-if="hasImportedData" class="result-section">
      <div class="section-header">
        <span class="section-title"><i class="el-icon-document"></i>导入数据</span>
        <span class="section-info">共 {{ totalImportedDataCount }} 条数据，{{ importedSheets.length }} 个工作表</span>
      </div>
      <el-tabs v-model="activeSheet" type="card">
        <el-tab-pane v-for="sheet in importedSheets" :key="sheet.name" :label="`${sheet.name} (${sheet.data.length}条)`">
          <el-table :data="sheet.data" style="width: 100%" border stripe max-height="500">
            <el-table-column prop="pointNumber" label="点号" width="100" align="center"></el-table-column>
            <el-table-column prop="pointName" label="点名" width="120" align="center"></el-table-column>
            <el-table-column prop="cpX" label="X坐标(m)" width="140" align="center">
              <template slot-scope="scope"><span class="result-value">{{ formatNumber(scope.row.cpX, 4) }}</span></template>
            </el-table-column>
            <el-table-column prop="cpY" label="Y坐标(m)" width="140" align="center">
              <template slot-scope="scope"><span class="result-value">{{ formatNumber(scope.row.cpY, 4) }}</span></template>
            </el-table-column>
            <el-table-column prop="cpZ" label="Z坐标(m)" width="140" align="center">
              <template slot-scope="scope"><span class="result-value">{{ formatNumber(scope.row.cpZ, 4) }}</span></template>
            </el-table-column>
            <el-table-column prop="stationPN" label="测站序号" width="100" align="center"></el-table-column>
            <el-table-column prop="directionPN" label="方向序号" width="100" align="center"></el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 计算结果展示区 -->
    <div v-if="calculationResults.length > 0" class="result-section">
      <div class="section-header">
        <span class="section-title"><i class="el-icon-tickets"></i>计算结果</span>
        <span class="section-info">共 {{ calculationResults.length }} 条计算结果</span>
        <el-button type="text" size="small" @click="handleExport" icon="el-icon-download">导出结果</el-button>
      </div>
      <el-table :data="calculationResults" style="width: 100%" border stripe>
        <el-table-column prop="stationPN" label="测站序号" width="100" align="center"></el-table-column>
        <el-table-column prop="directionPN" label="方向序号" width="100" align="center"></el-table-column>
        <el-table-column prop="stationPointName" label="测站点名" width="120" align="center"></el-table-column>
        <el-table-column prop="directionPointName" label="方向点名" width="120" align="center"></el-table-column>
        <el-table-column prop="spX" label="测站X(m)" width="140" align="center">
          <template slot-scope="scope"><span class="result-value">{{ formatNumber(scope.row.spX, 4) }}</span></template>
        </el-table-column>
        <el-table-column prop="spY" label="测站Y(m)" width="140" align="center">
          <template slot-scope="scope"><span class="result-value">{{ formatNumber(scope.row.spY, 4) }}</span></template>
        </el-table-column>
        <el-table-column prop="spZ" label="测站Z(m)" width="140" align="center">
          <template slot-scope="scope"><span class="result-value">{{ formatNumber(scope.row.spZ, 4) }}</span></template>
        </el-table-column>
        <el-table-column prop="dpX" label="方向X(m)" width="140" align="center">
          <template slot-scope="scope"><span class="result-value">{{ formatNumber(scope.row.dpX, 4) }}</span></template>
        </el-table-column>
        <el-table-column prop="dpY" label="方向Y(m)" width="140" align="center">
          <template slot-scope="scope"><span class="result-value">{{ formatNumber(scope.row.dpY, 4) }}</span></template>
        </el-table-column>
        <el-table-column prop="dpZ" label="方向Z(m)" width="140" align="center">
          <template slot-scope="scope"><span class="result-value">{{ formatNumber(scope.row.dpZ, 4) }}</span></template>
        </el-table-column>
        <el-table-column prop="azimuthAngle" label="方位角(°)" width="140" align="center">
          <template slot-scope="scope"><span class="result-value">{{ formatNumber(scope.row.azimuthAngle, 6) }}</span></template>
        </el-table-column>
        <el-table-column prop="angleDifference" label="角度差(°)" width="140" align="center">
          <template slot-scope="scope"><span class="result-value">{{ formatNumber(scope.row.angleDifference, 6) }}</span></template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 空状态 -->
    <div v-else class="empty-state">
      <i class="el-icon-document"></i>
      <p>暂无计算结果</p>
      <p class="empty-tip">请先导入Excel数据，然后点击"执行计算"</p>
    </div>
    
    <!-- 导入Excel对话框 -->
    <el-dialog title="导入Excel" :visible.sync="importDialogVisible" width="600px" @close="resetImport">
      <div class="import-tips">
        <el-alert title="Excel模板格式说明" type="info" :closable="false" show-icon>
          <div class="template-info">
            <p>请确保Excel文件包含以下列（第一行为表头）：</p>
            <ul>
              <li><strong>ipointNumber</strong> - 点号（控制点编号）</li>
              <li><strong>pointName</strong> - 点名</li>
              <li><strong>cpX</strong> - 控制点X坐标 (m)</li>
              <li><strong>cpY</strong> - 控制点Y坐标 (m)</li>
              <li><strong>cpZ</strong> - 控制点Z坐标 (m)</li>
              <li><strong>stationPN</strong> - 测站序号</li>
              <li><strong>directionPN</strong> - 方向序号</li>
            </ul>
            <p style="margin-top: 10px; color: #606266;">
              <strong>数据分组说明：</strong><br>
              - 第一组（点信息）：填写 ipointNumber、pointName、cpX、cpY、cpZ<br>
              - 第二组（方向信息）：填写 stationPN、directionPN（对应控制点的序号）
            </p>
          </div>
        </el-alert>
        <div class="template-download-wrapper">
          <el-button type="primary" plain size="small" @click="handleDownloadTemplate" icon="el-icon-download">下载Excel模板</el-button>
        </div>
      </div>
      <div style="text-align: center;">
        <el-upload class="upload-area" :action="''" :auto-upload="false" :on-change="handleFileChange" :show-file-list="true" accept=".xlsx,.xls" drag ref="upload">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将Excel文件拖到此处，或<em>点击选择</em></div>
          <div class="el-upload__tip" slot="tip">支持.xlsx和.xls格式文件，可包含多个工作表</div>
        </el-upload>
      </div>
      <div v-if="sheetNames.length > 0" class="sheet-selection">
        <div class="selection-header"><span>选择工作表（可多选）</span></div>
        <el-checkbox-group v-model="selectedSheets" class="sheet-checkboxes">
          <el-checkbox v-for="sheet in sheetNames" :key="sheet" :label="sheet">{{ sheet }}</el-checkbox>
        </el-checkbox-group>
        <div class="selection-actions">
          <el-button type="text" size="small" @click="selectAllSheets">全选</el-button>
          <el-button type="text" size="small" @click="clearSheetSelection">清空</el-button>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitImport" :loading="importLoading" :disabled="!importFile">确认导入</el-button>
      </span>
    </el-dialog>
    
    <!-- 预览数据对话框 - 分表格展示 -->
    <el-dialog title="导入数据预览" :visible.sync="previewDialogVisible" width="90%">
      <!-- 全局字段映射配置（核心配置区域） -->
      <div class="field-mapping-section">
        <div class="selection-header">
          <span class="selection-title"><i class="el-icon-link"></i>字段映射配置</span>
          <span class="selection-tip">为每个输入字段选择来自哪张表的哪个列</span>
        </div>
        
        <!-- 点信息组 -->
        <div class="mapping-group">
          <div class="group-title">
            <i class="el-icon-map-marker"></i>点信息（控制点坐标）
          </div>
          <div class="field-mapping-table">
            <table>
              <thead>
                <tr>
                  <th>字段名称</th>
                  <th>选择工作表</th>
                  <th>选择列</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="col in columnDefinitions.filter(c => c.group === 'point')" :key="col.key">
                  <td>{{ col.label }}</td>
                  <td>
                    <el-select 
                      v-model="getFieldMapping(col.key).sheet" 
                      class="field-mapping-select"
                      @change="handleFieldSheetChange(col.key, $event)"
                    >
                      <el-option label="无" value=""></el-option>
                      <el-option 
                        v-for="sheet in importedSheets" 
                        :key="sheet.name" 
                        :label="sheet.name" 
                        :value="sheet.name"
                      ></el-option>
                    </el-select>
                  </td>
                  <td>
                    <el-select 
                      v-model="getFieldMapping(col.key).column" 
                      class="field-mapping-select"
                      :disabled="!getFieldMapping(col.key).sheet"
                      @change="handleFieldColumnChange(col.key, $event)"
                    >
                      <el-option label="无" value="-1"></el-option>
                      <el-option 
                        v-for="opt in columnOptions.slice(1)" 
                        :key="opt.value" 
                        :label="opt.label" 
                        :value="opt.value"
                        :disabled="isFieldColumnUsed(col.key, opt.value)"
                      ></el-option>
                    </el-select>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        
        <!-- 方向信息组 -->
        <div class="mapping-group">
          <div class="group-title">
            <i class="el-icon-arrow-right"></i>方向信息（测站与方向）
          </div>
          <div class="field-mapping-table">
            <table>
              <thead>
                <tr>
                  <th>字段名称</th>
                  <th>选择工作表</th>
                  <th>选择列</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="col in columnDefinitions.filter(c => c.group === 'direction')" :key="col.key">
                  <td>{{ col.label }}</td>
                  <td>
                    <el-select 
                      v-model="getFieldMapping(col.key).sheet" 
                      class="field-mapping-select"
                      @change="handleFieldSheetChange(col.key, $event)"
                    >
                      <el-option label="无" value=""></el-option>
                      <el-option 
                        v-for="sheet in importedSheets" 
                        :key="sheet.name" 
                        :label="sheet.name" 
                        :value="sheet.name"
                      ></el-option>
                    </el-select>
                  </td>
                  <td>
                    <el-select 
                      v-model="getFieldMapping(col.key).column" 
                      class="field-mapping-select"
                      :disabled="!getFieldMapping(col.key).sheet"
                      @change="handleFieldColumnChange(col.key, $event)"
                    >
                      <el-option label="无" value="-1"></el-option>
                      <el-option 
                        v-for="opt in columnOptions.slice(1)" 
                        :key="opt.value" 
                        :label="opt.label" 
                        :value="opt.value"
                        :disabled="isFieldColumnUsed(col.key, opt.value)"
                      ></el-option>
                    </el-select>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
        
        <div class="selection-actions">
          <el-button type="text" size="small" @click="resetFieldMappings">重置映射</el-button>
          <el-button type="text" size="small" @click="autoDetectMappings">自动检测</el-button>
        </div>
      </div>
      
      
      
      <div class="preview-info">
        <span>共 {{ totalRawDataCount }} 条数据</span>
        <span style="margin-left: 20px;">共 {{ importedSheets.length }} 个工作表</span>
      </div>
      <el-tabs v-model="activeSheet" type="card" closable>
        <el-tab-pane v-for="sheet in importedSheets" :key="sheet.name" :label="`${sheet.name} (${(sheet.rawData || []).length}条)`">
          <!-- 数据表 -->
          <el-table :data="sheet.rawData" border stripe max-height="400">
            <el-table-column 
              v-for="(header, index) in (sheet.headers || [])" 
              :key="index"
              :label="`${String.fromCharCode(65 + index)}列: ${header}`"
              :width="120"
              align="center">
              <template slot-scope="scope">
                {{ scope.row[index] || '--' }}
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmImport">确定导入</el-button>
        <el-button @click="previewDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { calculate, importExcel, exportExcel, downloadTemplate, getSheetNames } from '@/api/calculate/eledifsidelanddir'

export default {
  name: 'EleDifSideLandDirTool',
  data() {
    return {
      importedSheets: [],
      calculationResults: [],
      importDialogVisible: false,
      importLoading: false,
      importFile: null,
      calculating: false,
      previewDialogVisible: false,
      sheetNames: [],
      selectedSheets: [],
      // 全局字段映射配置（字段名 -> { sheet: 工作表名, column: 列索引 }）
      fieldMappings: {},
      activeSheet: '',
      // 列定义
      columnDefinitions: [
        { key: 'pointNumber', label: '点号', group: 'point' },
        { key: 'pointName', label: '点名', group: 'point' },
        { key: 'cpX', label: 'X坐标', group: 'point' },
        { key: 'cpY', label: 'Y坐标', group: 'point' },
        { key: 'cpZ', label: 'Z坐标', group: 'point' },
        { key: 'stationPN', label: '测站序号', group: 'direction' },
        { key: 'directionPN', label: '方向序号', group: 'direction' }
      ],
      // 列选项（用于下拉选择）- 支持Excel的A-Z列
      columnOptions: [
        { label: '无', value: -1 },
        { label: 'A列', value: 0 },
        { label: 'B列', value: 1 },
        { label: 'C列', value: 2 },
        { label: 'D列', value: 3 },
        { label: 'E列', value: 4 },
        { label: 'F列', value: 5 },
        { label: 'G列', value: 6 },
        { label: 'H列', value: 7 },
        { label: 'I列', value: 8 },
        { label: 'J列', value: 9 },
        { label: 'K列', value: 10 },
        { label: 'L列', value: 11 },
        { label: 'M列', value: 12 },
        { label: 'N列', value: 13 },
        { label: 'O列', value: 14 },
        { label: 'P列', value: 15 },
        { label: 'Q列', value: 16 },
        { label: 'R列', value: 17 },
        { label: 'S列', value: 18 },
        { label: 'T列', value: 19 },
        { label: 'U列', value: 20 },
        { label: 'V列', value: 21 },
        { label: 'W列', value: 22 },
        { label: 'X列', value: 23 },
        { label: 'Y列', value: 24 },
        { label: 'Z列', value: 25 }
      ]
    }
  },
  computed: {
    hasImportedData() {
      return this.importedSheets.some(sheet => sheet.data && sheet.data.length > 0)
    },
    totalImportedDataCount() {
      return this.importedSheets.reduce((sum, sheet) => sum + (sheet.data ? sheet.data.length : 0), 0)
    },
    totalRawDataCount() {
      return this.importedSheets.reduce((sum, sheet) => sum + (sheet.rawData ? sheet.rawData.length : 0), 0)
    },
    importedData() {
      return this.importedSheets.flatMap(sheet => sheet.data || [])
    }
  },
  methods: {
    handleImport() { this.importDialogVisible = true },
    async handleFileChange(file) {
      this.importFile = file.raw
      if (this.importFile) {
        const formData = new FormData()
        formData.append('file', this.importFile)
        const response = await getSheetNames(formData)
        if (response.code === 200) {
          this.sheetNames = response.data || []
          this.selectedSheets = [...this.sheetNames]
        }
      }
    },
    selectAllSheets() { this.selectedSheets = [...this.sheetNames] },
    clearSheetSelection() { this.selectedSheets = [] },
    // 获取字段映射配置（用于模板中安全访问）
    getFieldMapping(fieldKey) {
      if (!this.fieldMappings[fieldKey]) {
        this.fieldMappings[fieldKey] = { sheet: '', column: -1 }
      }
      return this.fieldMappings[fieldKey]
    },
    // 初始化字段映射
    initFieldMappings() {
      this.columnDefinitions.forEach(col => {
        this.getFieldMapping(col.key)
      })
    },
    // 处理字段工作表变更
    handleFieldSheetChange(fieldKey, sheetName) {
      if (!sheetName) {
        this.$set(this.fieldMappings, fieldKey, { sheet: '', column: -1 })
      } else {
        // 初始化列选择
        if (!this.fieldMappings[fieldKey]) {
          this.$set(this.fieldMappings, fieldKey, { sheet: sheetName, column: -1 })
        } else {
          this.$set(this.fieldMappings[fieldKey], 'sheet', sheetName)
          // 检查当前选择的列是否在新工作表中已被使用
          const currentCol = this.fieldMappings[fieldKey].column
          if (currentCol !== -1 && this.isFieldColumnUsed(fieldKey, currentCol)) {
            this.$set(this.fieldMappings[fieldKey], 'column', -1)
          }
        }
      }
      // 强制更新视图
      this.$forceUpdate()
    },
    // 确定导入：根据字段映射配置读取对应列的数据
    confirmImport() {
      // 验证是否至少配置了一个字段
      const configuredFields = Object.values(this.fieldMappings).filter(m => m.sheet && m.column !== -1)
      if (configuredFields.length === 0) {
        this.$message.warning('请至少配置一个字段的映射')
        return
      }
      
      // 根据字段映射配置重新构建数据
      const newImportedSheets = []
      
      this.importedSheets.forEach(sheet => {
        // 获取该工作表的原始数据
        const rawData = sheet.rawData || []
        
        // 找出配置到该工作表的字段
        const sheetFields = Object.entries(this.fieldMappings)
          .filter(([key, mapping]) => mapping.sheet === sheet.name && mapping.column !== -1)
        
        // 重新构建数据（保留原有数据结构，只更新映射的字段）
        const mappedData = rawData.map(rowData => {
          // 创建一个完整的空数据项
          const item = {
            pointNumber: null,
            pointName: null,
            cpX: null,
            cpY: null,
            cpZ: null,
            stationPN: null,
            directionPN: null,
            calculated: false
          }
          
          // 填充映射的字段
          sheetFields.forEach(([fieldKey, mapping]) => {
            const columnIndex = mapping.column
            const value = rowData[columnIndex]
            
            // 对 stationPN 和 directionPN 进行整数转换
            if (fieldKey === 'stationPN' || fieldKey === 'directionPN') {
              if (value !== null && value !== undefined && value !== '') {
                const numValue = parseFloat(value)
                if (!isNaN(numValue)) {
                  item[fieldKey] = parseInt(numValue)
                } else {
                  item[fieldKey] = null
                }
              } else {
                item[fieldKey] = null
              }
            } else if (fieldKey === 'cpX' || fieldKey === 'cpY' || fieldKey === 'cpZ') {
              // 对坐标字段进行浮点数转换
              if (value !== null && value !== undefined && value !== '') {
                const numValue = parseFloat(value)
                item[fieldKey] = isNaN(numValue) ? null : numValue
              } else {
                item[fieldKey] = null
              }
            } else {
              item[fieldKey] = value
            }
          })
          
          return item
        })
        
        newImportedSheets.push({
          name: sheet.name,
          headers: sheet.headers,
          rawData: sheet.rawData,
          data: mappedData
        })
      })
      
      // 更新导入数据（这将反映到主页的数据展示区域）
      this.importedSheets = newImportedSheets
      
      // 关闭预览对话框
      this.previewDialogVisible = false
      
      // 提示用户
      const totalCount = newImportedSheets.reduce((sum, s) => sum + (s.data?.length || 0), 0)
      this.$message.success(`导入成功！共 ${totalCount} 条数据`)
    },
    // 处理字段列变更
    handleFieldColumnChange(fieldKey, columnIndex) {
      // 如果选择了"无"，不需要处理
      if (columnIndex === -1) return
      
      // 检查是否有其他字段使用了同一工作表的同一列
      const currentMapping = this.fieldMappings[fieldKey]
      if (!currentMapping || !currentMapping.sheet) return
      
      // 找到使用同一工作表同一列的其他字段并取消选择
      for (const [field, mapping] of Object.entries(this.fieldMappings)) {
        if (field !== fieldKey && mapping.sheet === currentMapping.sheet && mapping.column === columnIndex) {
          // 取消其他字段的选择
          this.$set(this.fieldMappings[field], 'column', -1)
          // 提示用户
          const fieldLabel = this.columnDefinitions.find(c => c.key === field)?.label || field
          const columnLabel = this.columnOptions.find(o => o.value === columnIndex)?.label || `列${columnIndex}`
          this.$message.warning(`${fieldLabel} 已取消映射，因为 ${currentMapping.sheet} 的 ${columnLabel} 已被其他字段使用`)
        }
      }
      // 强制更新视图
      this.$forceUpdate()
    },
    // 检查指定列是否已被其他字段使用（仅检查同一工作表内的重复）
    isFieldColumnUsed(excludeField, columnIndex) {
      if (columnIndex === -1) return false
      // 获取当前字段所在的工作表
      const currentSheet = this.fieldMappings[excludeField]?.sheet
      if (!currentSheet) return false
      
      // 只检查同一工作表内是否有其他字段使用了同一列
      for (const [field, mapping] of Object.entries(this.fieldMappings)) {
        if (field !== excludeField && 
            mapping.column === columnIndex && 
            mapping.sheet === currentSheet) {
          return true
        }
      }
      return false
    },
    // 重置字段映射
    resetFieldMappings() {
      this.columnDefinitions.forEach(col => {
        this.$set(this.fieldMappings, col.key, { sheet: '', column: -1 })
      })
      // 强制更新视图
      this.$forceUpdate()
    },
    // 自动检测映射（按顺序映射到第一个工作表）
    autoDetectMappings() {
      if (this.importedSheets.length === 0) {
        this.$message.warning('请先导入数据')
        return
      }
      
      const firstSheet = this.importedSheets[0].name
      let colIndex = 0
      this.columnDefinitions.forEach(col => {
        this.$set(this.fieldMappings, col.key, { sheet: firstSheet, column: colIndex++ })
      })
      // 强制更新视图
      this.$forceUpdate()
    },
    // 全选当前工作表的列
    selectAllSheetColumns(sheetName) {
      this.sheetColumnSelections[sheetName] = ['pointNumber', 'pointName', 'cpX', 'cpY', 'cpZ', 'stationPN', 'directionPN']
    },
    // 清空当前工作表的列选择
    clearSheetColumnSelection(sheetName) {
      this.sheetColumnSelections[sheetName] = []
    },
    // 将全局选择应用到当前工作表
    applyGlobalToSheet(sheetName) {
      this.sheetColumnSelections[sheetName] = [...this.globalSelectedColumns]
    },
    // 获取默认列映射
    getDefaultMapping(sheetIndex) {
      const mapping = {}
      // 第一个工作表默认映射点信息列（A-E列）
      if (sheetIndex === 0) {
        mapping.pointNumber = 0
        mapping.pointName = 1
        mapping.cpX = 2
        mapping.cpY = 3
        mapping.cpZ = 4
        mapping.stationPN = -1
        mapping.directionPN = -1
      } else if (sheetIndex === 1) {
        // 第二个工作表默认映射方向信息列（A-B列）
        mapping.pointNumber = -1
        mapping.pointName = -1
        mapping.cpX = -1
        mapping.cpY = -1
        mapping.cpZ = -1
        mapping.stationPN = 0
        mapping.directionPN = 1
      } else {
        // 其他工作表默认不映射
        this.columnDefinitions.forEach(col => {
          mapping[col.key] = -1
        })
      }
      return mapping
    },
    async submitImport() {
      if (!this.importFile) { this.$message.warning('请选择文件'); return }
      this.importLoading = true
      const formData = new FormData()
      formData.append('file', this.importFile)
      this.selectedSheets.forEach(sheet => formData.append('sheetNames', sheet))
      const response = await importExcel(formData)
      if (response.code === 200) {
        const result = response.data
        this.importedSheets = []
        
        // 优先使用按工作表分组的数据
        if (result.sheetData && result.sheetData.length > 0) {
          result.sheetData.forEach(sheetInfo => {
            this.importedSheets.push({
              name: sheetInfo.sheetName,
              headers: sheetInfo.headers || [],
              rawData: sheetInfo.rawData || [],
              data: (sheetInfo.data || []).map(item => ({
                pointNumber: item.pointNumber,
                pointName: item.pointName,
                cpX: item.cpX,
                cpY: item.cpY,
                cpZ: item.cpZ,
                stationPN: item.stationPN !== null && item.stationPN !== undefined && item.stationPN !== '' ? parseInt(parseFloat(item.stationPN)) : null,
                directionPN: item.directionPN !== null && item.directionPN !== undefined && item.directionPN !== '' ? parseInt(parseFloat(item.directionPN)) : null,
                calculated: false
              }))
            })
          })
        } else {
          // 兼容旧格式：按数据类型分组
          if (result.pointData && result.pointData.length > 0) {
            this.importedSheets.push({
              name: '控制点信息',
              data: (result.pointData || []).map(item => ({
                pointNumber: item.pointNumber,
                pointName: item.pointName,
                cpX: item.cpX,
                cpY: item.cpY,
                cpZ: item.cpZ,
                stationPN: null,
                directionPN: null,
                calculated: false
              }))
            })
          }
          if (result.directionData && result.directionData.length > 0) {
            this.importedSheets.push({
              name: '方向信息',
              data: result.directionData.map(item => ({
                pointNumber: item.pointNumber,
                pointName: null,
                cpX: null,
                cpY: null,
                cpZ: null,
                stationPN: item.stationPN !== null && item.stationPN !== undefined && item.stationPN !== '' ? parseInt(parseFloat(item.stationPN)) : null,
                directionPN: item.directionPN !== null && item.directionPN !== undefined && item.directionPN !== '' ? parseInt(parseFloat(item.directionPN)) : null,
                calculated: false
              }))
            })
          }
        }
        
        if (this.importedSheets.length > 0) {
          this.activeSheet = this.importedSheets[0].name
        }
        this.calculationResults = []
        this.$message.success(`${response.msg}`)
        this.importDialogVisible = false
        this.importLoading = false
      } else {
        this.$message.error(response.msg)
      }
    },
    handlePreview() {
      if (!this.hasImportedData) { this.$message.warning('没有可预览的数据'); return }
      // 初始化字段映射
      this.initFieldMappings()
      this.previewDialogVisible = true
      if (this.importedSheets.length > 0) {
        this.activeSheet = this.importedSheets[0].name
      }
    },
    handleDownloadTemplate() { this.download('/calculate/eleDifSideLandDir/template', {}, '高差边长方向值模板.xlsx') },
    async handleCalculate() {
      if (!this.hasImportedData) { this.$message.warning('没有数据可计算'); return }
      this.calculating = true
      const requestData = {
        data: this.importedData.map(item => ({
          pointNumber: item.pointNumber,
          pointName: item.pointName,
          cpX: item.cpX,
          cpY: item.cpY,
          cpZ: item.cpZ,
          stationPN: item.stationPN !== null && item.stationPN !== undefined && item.stationPN !== '' ? parseInt(parseFloat(item.stationPN)) : null,
          directionPN: item.directionPN !== null && item.directionPN !== undefined && item.directionPN !== '' ? parseInt(parseFloat(item.directionPN)) : null
        }))
      }
      const response = await calculate(requestData)
      if (response.code === 200) {
        const results = response.data || []
        this.calculationResults = results.map(item => ({
          stationPN: item.stationPN,
          directionPN: item.directionPN,
          stationPointName: item.stationPointName,
          directionPointName: item.directionPointName,
          spX: item.spX,
          spY: item.spY,
          spZ: item.spZ,
          dpX: item.dpX,
          dpY: item.dpY,
          dpZ: item.dpZ,
          azimuthAngle: item.azimuthAngle,
          angleDifference: item.angleDifference
        }))
        this.$message.success(`计算完成，共 ${results.length} 条结果`)
        this.calculating = false
      } else {
        this.$message.error(response.msg)
      }
    },
    async handleExport() {
      if (this.calculationResults.length === 0) { this.$message.warning('没有结果可导出'); return }
      const response = await exportExcel(this.calculationResults)
      const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `高差边长方向值结果_${new Date().getTime()}.xlsx`
      link.click()
      window.URL.revokeObjectURL(url)
    },
    clearAll() {
      if (!this.hasImportedData && this.calculationResults.length === 0) return
      this.$confirm('确定清空所有数据吗？此操作不可恢复！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.importedSheets = []
        this.calculationResults = []
        this.$message.success('已清空所有数据')
      }).catch(() => {})
    },
    resetImport() {
      this.importFile = null
      this.sheetNames = []
      this.selectedSheets = []
      if (this.$refs.upload) this.$refs.upload.clearFiles()
    },
    formatNumber(value, decimals) {
      if (value === null || value === undefined) return '--'
      return Number(value).toFixed(decimals)
    },
  }
}
</script>

<style scoped>
.ele-dif-side-land-dir-tool { width: 100%; }
.tool-header { margin-bottom: 20px; }
.card-header-buttons { display: flex; gap: 10px; flex-wrap: wrap; }
.column-selection { background: #f5f7fa; border-radius: 8px; padding: 12px 20px; margin-bottom: 20px; border: 1px solid #e4e7ed; }
.selection-header { margin-bottom: 12px; }
.selection-title { font-size: 14px; font-weight: bold; color: #303133; }
.selection-title i { margin-right: 8px; color: #11a983; }
.selection-content { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; }
.column-checkboxes { display: flex; gap: 15px; flex-wrap: wrap; }
.sheet-checkboxes { display: flex; gap: 15px; flex-wrap: wrap; }
.selection-actions { display: flex; gap: 10px; }
.result-section { margin-top: 10px; }
.section-header { padding: 12px 16px; background: #f5f7fa; border-radius: 8px 8px 0 0; border: 1px solid #e4e7ed; border-bottom: none; display: flex; justify-content: space-between; align-items: center; }
.section-title { font-size: 14px; font-weight: bold; color: #303133; }
.section-title i { margin-right: 8px; color: #11a983; }
.section-info { font-size: 12px; color: #909399; }
.result-value { color: #409eff; font-family: monospace; font-weight: 500; }
.empty-state { text-align: center; padding: 60px 20px; background: #fff; border-radius: 8px; border: 1px solid #e4e7ed; color: #909399; }
.empty-state i { font-size: 64px; margin-bottom: 16px; }
.empty-tip { font-size: 12px; margin-top: 12px; color: #c0c4cc; }
.import-tips { margin-bottom: 20px; }
.template-info { margin-top: 12px; }
.template-info ul { margin: 8px 0; padding-left: 20px; }
.template-info li { margin: 4px 0; font-size: 13px; }
.upload-area { margin-top: 10px; }
.preview-info { margin-bottom: 15px; padding: 10px; background: #f5f7fa; border-radius: 4px; font-size: 14px; color: #606266; }
.dialog-footer { width: 100%; display: flex; justify-content: flex-end; gap: 10px; }
.template-download-wrapper { margin-top: 12px; display: flex; align-items: center; justify-content: flex-end; gap: 10px; padding-top: 12px; border-top: 1px dashed #e4e7ed; }
.sheet-selection { margin-top: 15px; padding: 15px; background: #f9f9f9; border-radius: 4px; border: 1px solid #e4e7ed; }
.sheet-selection .el-checkbox { margin-right: 15px; margin-bottom: 10px; }
.sheet-selection .el-button { margin-left: 10px; }

/* 预览对话框中的全局列选择 */
.preview-global-columns {
  margin-bottom: 15px;
  padding: 15px;
  background: #e8f5e9;
  border-radius: 4px;
  border: 1px solid #a5d6a7;
}

.preview-global-columns .selection-header {
  margin-bottom: 10px;
}

.preview-global-columns .selection-title {
  font-size: 14px;
  font-weight: bold;
  color: #2e7d32;
}

.preview-global-columns .selection-title i {
  margin-right: 8px;
  color: #4caf50;
}

/* 工作表独立列选择 */
.sheet-column-selection {
  margin-bottom: 15px;
  padding: 12px;
  background: #fff3e0;
  border-radius: 4px;
  border: 1px solid #ffcc80;
}

.sheet-column-selection .selection-header {
  margin-bottom: 8px;
}

.sheet-column-selection .selection-title {
  font-size: 13px;
  font-weight: bold;
  color: #e65100;
}

.sheet-column-selection .selection-title i {
  margin-right: 6px;
  color: #ff9800;
}

.sheet-column-selection .column-checkboxes {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.sheet-column-selection .selection-actions {
  margin-top: 8px;
  display: flex;
  gap: 10px;
}

/* 选择提示 */
.selection-tip {
  margin-left: 15px;
  font-size: 12px;
  color: #909399;
  font-weight: normal;
}

/* 字段映射配置区域 */
.field-mapping-section {
  margin-bottom: 15px;
  padding: 15px;
  background: #fff3e0;
  border-radius: 4px;
  border: 1px solid #ffb74d;
}

.field-mapping-section .selection-header {
  margin-bottom: 12px;
}

.field-mapping-section .selection-title {
  font-size: 14px;
  font-weight: bold;
  color: #e65100;
}

.field-mapping-section .selection-title i {
  margin-right: 8px;
  color: #ff9800;
}

/* 字段映射表格 */
.field-mapping-table {
  overflow-x: auto;
}

.field-mapping-table table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 10px;
}

.field-mapping-table th,
.field-mapping-table td {
  border: 1px solid #e0e0e0;
  padding: 8px 12px;
  text-align: center;
}

.field-mapping-table th {
  background: #fff8e1;
  font-weight: bold;
  color: #546e7a;
}

.field-mapping-table td:first-child {
  font-weight: 500;
  color: #37474f;
}

.field-mapping-select {
  width: 150px;
}

/* 列映射配置区域 */
.column-mapping-section {
  margin-bottom: 15px;
  padding: 15px;
  background: #e3f2fd;
  border-radius: 4px;
  border: 1px solid #90caf9;
}

.column-mapping-section .selection-header {
  margin-bottom: 12px;
}

.column-mapping-section .selection-title {
  font-size: 14px;
  font-weight: bold;
  color: #1565c0;
}

.column-mapping-section .selection-title i {
  margin-right: 8px;
  color: #2196f3;
}

/* 映射分组 */
.mapping-group {
  margin-bottom: 15px;
  padding: 12px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #e3f2fd;
}

.mapping-group:last-child {
  margin-bottom: 10px;
}

.group-title {
  font-size: 13px;
  font-weight: bold;
  color: #37474f;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px dashed #e0e0e0;
}

.group-title i {
  margin-right: 6px;
  color: #546e7a;
}

/* 映射行 */
.mapping-row {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

/* 映射项 */
.mapping-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 120px;
}

.mapping-label {
  font-size: 12px;
  color: #546e7a;
  font-weight: 500;
}

.mapping-select {
  width: 100%;
}

</style>