<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-form inline>
        <el-row :span="24">
          <el-col :span="5">
            <el-form-item label="物料名称" prop="">
              <el-select v-model="query.leibiemc" placeholder="请选择物料名称" filterable clearable style="width: 180px;">
                <el-option v-for="item in typeList" :key="item.itemCd" :label="item.itemNm"
                           :value="item.itemNm"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="物理编号" prop="">
              <el-input placeholder="请输入物理编号" v-model="query.wulizybh" style="width: 180px;"
                        clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="是否审核" prop="">
              <el-select v-model="query.shenhe" placeholder="请选择" clearable style="width: 200px;">
                <!-- <el-option v-for="item in smpTypeList" :key="item.bm" :label="item.wtmc"
                    :value="item.bm"></el-option> -->
                <el-option label="未审核" value="0"></el-option>
                <el-option label="已审核" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>


          <el-col :span="5">
            <el-form-item label="生产时间" prop="">
              <el-date-picker
                  v-model="query.shengchanTime"
                  type="date"
                  placeholder="请选择日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="show" link>高级查询
              <el-icon v-if="showA">
                <ArrowUp/>
              </el-icon>
              <el-icon v-else>
                <ArrowDown/>
              </el-icon>
            </el-button>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="reset" link>重置</el-button>
          </el-col>
        </el-row>
        <el-row :span="24" v-if="showA">
          <el-col :span="8">
            <el-form-item label="物理提交时间" prop="">
              <el-date-picker v-model="query.wuliPdsj" type="datetimerange" align="right" unlink-panels
                              range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
                              style="width: 400px;" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>


    <ButtonBar area="top" @search="handleSearch" @save="handleSave" @commit="handleCommit" @export="handleExport">
    </ButtonBar>
    <el-card :body-style="cardBodyStyle">
      <el-table @row-click="handleRowClick1" :data="tableData" border highlight-current-row height="250"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" fixed></el-table-column>
        <!--        <el-table-column type="index" label="序号" align="center" width="60" fixed>-->
        <!--          <template #default="scope">-->
        <!--            <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column prop="委托编号" label="委托编号" align="center" width="180" fixed>
        </el-table-column>
        <el-table-column prop="物料名称" label="物料名称" align="center" width="120" fixed>
        </el-table-column>
        <el-table-column v-if="true" prop="生产时间" label="生产时间" width="120" header-align="center"
                         align="center"
                         show-overflow-tooltip
                         :formatter="formatDate"
                         >
        </el-table-column>
        <el-table-column v-if="true" prop="班次" label="班次" width="60" header-align="center"
                         align="center"
                         show-overflow-tooltip >
        </el-table-column>

        <el-table-column v-for="item in listKey.filter(key => key)" :prop="item" :label="item" width="80"
                         header-align="center"
                         align="center" show-overflow-tooltip></el-table-column>


        <el-table-column prop="委托状态" label="委托状态" align="center" width="130">
        </el-table-column>

        <el-table-column prop="委托类型" label="委托类型" align="center" width="120">
        </el-table-column>
        <el-table-column prop="物理站审核人" label="物理站审核人" align="center" width="120">
        </el-table-column>
        <el-table-column prop="物理站提交时间" label="物理站提交时间" align="center" width="190">
        </el-table-column>
        <el-table-column prop="物理站审核时间" label="物理站审核时间" align="center" width="190">
        </el-table-column>
        <el-table-column prop="物理制样编号" label="物理制样编号" align="center" width="180">
        </el-table-column>
        <el-table-column prop="取样时间" label="取样时间" width="180" header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>

      </el-table>
      <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes" :total="totalRows"
                     background="background" layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>
  </div>
  <div>

    <el-card :body-style="cardBodyStyle">
      <el-tabs type="border-card">
        <el-tab-pane label="物理数据">
          <el-table :data="tableData_WL" border highlight-current-row height="250"
                    @selection-change="handleSelectionChange" @cell-click="handleCellDblClick">
            <!-- <el-table-column type="selection" fixed></el-table-column> -->
<!--            <el-table-column type="index" label="序号" align="center" width="60">-->
<!--              <template #default="scope">-->
<!--                <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>-->
<!--              </template>-->
<!--            </el-table-column>-->
            <el-table-column prop="xiangmuMc" label="项目名称" width="200" header-align="center" align="center"
                             show-overflow-tooltip>
            </el-table-column>
            <el-table-column prop="xiangmuZhi" label="检验结果" width="200" header-align="center" align="center"
                             show-overflow-tooltip>
              <template #default="{ row, column }">
                <el-input v-if="tableRowEditId === row.id && tableColumnEditIndex === column.id"
                          @blur="blurValueInput(row, column)" @keyup.enter="blurValueInput(row, column)"
                          v-model="row.xiangmuZhi"
                          @input="validateInput(row)"
                          ref="inputXiangMuZhi"/>
                <span v-else>{{ row.xiangmuZhi }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="xiangmuXyz" label="修约值" width="200" header-align="center" align="center"
                             show-overflow-tooltip>
              <!-- <template #default="{ row, column }">
                  <el-input v-if="tableRowEditId === row.id && tableColumnEditIndex === column.id"
                      @blur="blurValueInput(row, column)" @keyup.enter="blurValueInput(row, column)"
                      v-model="row.xiangmuXyz" ref="inputXiangMZuXyz" />
                  <span v-else>{{ row.xiangmuXyz }}</span>
              </template> -->
            </el-table-column>
            <el-table-column prop="luruRen" label="录入人" width="200" header-align="center" align="center"
                             show-overflow-tooltip>
              <!--              <template #default="{ row, column }">-->
              <!--                <el-input v-if="tableRowEditId === row.id && tableColumnEditIndex === column.id"-->
              <!--                          @blur="blurValueInput(row, column)" @keyup.enter="blurValueInput(row, column)"-->
              <!--                          v-model="row.luruRen" ref="inputLuruRen"/>-->
              <!--                <span v-else>{{ row.luruRen }}</span>-->
              <!--              </template>-->
            </el-table-column>
            <el-table-column prop="luruSj" label="录入时间" width="200" header-align="center" align="center"
            >
              <!--              <template #default="{ row, column }">-->
              <!--                <el-date-picker v-if="tableRowEditId === row.id && tableColumnEditIndex === column.id"-->
              <!--                                @blur="blurValueInput(row, column)" @keyup.enter="blurValueInput(row, column)"-->
              <!--                                v-model="row.luruSj" type="datetime" unlink-panels range-separator="至"-->
              <!--                                start-placeholder="开始时间" end-placeholder="结束时间" style="width: 200px;"-->
              <!--                                value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" ref="timeLuruSj"/>-->
              <!--                <span v-else>{{ row.luruSj }}</span>-->
              <!--              </template>-->
            </el-table-column>
            <el-table-column prop="flagSjly" label="数据来源" width="200" header-align="center" align="center"
                             show-overflow-tooltip>
              <!--              <template #default="{ row, column }">-->
              <!--                <el-input v-if="tableRowEditId === row.id && tableColumnEditIndex === column.id"-->
              <!--                          @blur="blurValueInput(row, column)" @keyup.enter="blurValueInput(row, column)"-->
              <!--                          v-model="row.flagSjly" ref="inputFlagSjly"/>-->
              <!--                <span v-else>{{ row.flagSjly }}</span>-->
              <!--              </template>-->
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes"
                      :total="totalRows" background="background" layout="total, sizes, prev, pager, next, jumper"
                      @size-change="handleSizeChange" @current-change="handleCurrentChange">
      </el-pagination> -->
    </el-card>
  </div>
</template>

<script setup>
import SearchBox from '@/components/SearchBox.vue'
import ButtonBar from '@/components/ButtonBar.vue'
import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance,
  nextTick
} from 'vue'
import style from '@/tools/style'
import {ElMessage, ElMessageBox} from "element-plus";


onMounted(() => {
  queryWTLXType()
  queryType()
  handleSearch()
})

const {proxy} = getCurrentInstance()
const cardBodyStyle = ref(style.card)
const dialogVisible = ref(false)
const form = ref({
  xiangmuMc: '',
  xiangmuXyz: '',
  luruRen: '',
  luruSj: '',
  flagSjly: ''
})

const query = ref({
  leibiemc: '',
  weituoztMc: '',
  isAll: '',
  smpType: 'G',
  wulizybh: '',
  wuliPdsj: '',
  shengchanTime:'',
  shenhe:'0'

})

// 格式化日期的函数
const formatDate = (row, column, cellValue) => {
  if (cellValue) {
    const date = new Date(cellValue);
    return date.toLocaleDateString(); // 只显示日期部分
  }
  return '';
};
//单元格校验规则
const validateInput = (row) => {
  // 保留数字和小数点，过滤非数字和非法小数点字符
  let value = row.xiangmuZhi?.trim(); // 获取输入值并去除两端空格

  if (!value) {
    // 当值为 null 或空字符串时直接返回，不提示
    return;
  }
  value = value.replace(/[^0-9.]/g, '');

  // 自动去除数字前多余的 0，例如 03 -> 3
  if (/^0[0-9]+/.test(value)) {
    value = parseFloat(value).toString();
  }

  // 检查最大值和格式合法性
  const numericValue = parseFloat(value); // 转为浮点数
  if (!isNaN(numericValue) && numericValue <= 100) {
    row.xiangmuZhi = value; // 保留合法输入
  } else if (isNaN(numericValue)) {
    ElMessage.error('输入格式不正确,请输入数字');
    row.xiangmuZhi = ''; // 清空输入
  } else if (numericValue > 100 && value != '') {
    ElMessage.error('最大值为100');
    row.xiangmuZhi = 100;
  }

  const MAX_LENGTH = 10;
  if (row.xiangmuZhi && row.xiangmuZhi.length > MAX_LENGTH) {
    ElMessage.error(`输入长度不能超过 ${MAX_LENGTH} 个字符`);
    row.xiangmuZhi = row.xiangmuZhi.slice(0, MAX_LENGTH); // 保留前 10 个字符
  }

  // 检查是否有多个小数点
  const dotCount = (value.match(/\./g) || []).length;
  if (dotCount > 1) {
    ElMessage.error('输入格式不正确，不能包含多个小数点');
    row.xiangmuZhi = ''; // 清空输入
    return;
  }
};

// 存储最新的数据
const updatedData = ref([]);
// 存储当前编辑行和列
const tableRowEditId = ref(null);
const tableColumnEditIndex = ref(null);

const blurValueInput = (row, column) => {
  // 获取修约规则和小数位数
  const xiuyuegz = row.xiuyuegz; // 通过 row 获取 xiuyuegz
  const xiaoshuwei = row.xiaoshuwei; // 通过 row 获取小数位数，默认为 2

  // 更新修约值
  row.xiangmuXyz = isNaN(updateXiangmuXyz(parseFloat(row.xiangmuZhi), xiuyuegz, xiaoshuwei)) ? null : updateXiangmuXyz(parseFloat(row.xiangmuZhi), xiuyuegz, xiaoshuwei);

  // 更新最新数据
  const updatedRow = {
    id: row.id,
    xiangmuZhi: row.xiangmuZhi,
    xiangmuXyz: row.xiangmuXyz,
    luruRen: row.luruRen,
    luruSj: row.luruSj,
    flagSjly: row.flagSjly,
  };

  const originalRow = updatedData.value.find(item => item.id === row.id);
  const hasChanges = !originalRow ||
      originalRow.xiangmuZhi !== updatedRow.xiangmuZhi ||
      originalRow.xiangmuXyz !== updatedRow.xiangmuXyz ||
      originalRow.luruRen !== updatedRow.luruRen ||
      originalRow.luruSj !== updatedRow.luruSj ||
      originalRow.flagSjly !== updatedRow.flagSjly;

  if (hasChanges) {
    // 更新数据
    updatedData.value = updatedData.value.map(item =>
        item.id === row.id ? updatedRow : item
    );

    // 如果没有找到旧的数据，就添加新的数据
    if (!updatedData.value.find(item => item.id === row.id)) {
      updatedData.value.push(updatedRow);
    }
  } else {
    // 如果没有变化，则删除该行数据
    updatedData.value = updatedData.value.filter(item => item.id !== row.id);
  }

  // // 使用 map 更新数据，确保只保留新的数据
  // updatedData.value = updatedData.value.map(item =>
  //     item.id === row.id ? updatedRow : item
  // );

  // // 如果没有找到旧的数据，就添加新的数据
  // if (!updatedData.value.find(item => item.id === row.id)) {
  //     updatedData.value.push(updatedRow);
  // }

  // 清除编辑状态
  tableRowEditId.value = null;
  tableColumnEditIndex.value = null;
};
const inputLuruRen = ref(null)
const inputFlagSjly = ref(null)
const inputXiangMuZhi = ref(null)
const inputXiangMZuXyz = ref(null)
const timeLuruSj = ref(null)
// 双击进入编辑
const handleCellDblClick = (row, column, cell, event) => {
  if (top_row.value.委托状态 == '审核完成') {
    ElMessage({
      type: 'error',
      message: '已审核完成，无法修改!!'

    })
    return
  }
  tableRowEditId.value = row.id; // 确定点击的单元格在哪行
  tableColumnEditIndex.value = column.id; // 确定点击的单元格在哪列
  nextTick(() => {
    if (column.property == 'luruRen') {
      inputLuruRen.value.focus()
    }
    if (column.property == 'flagSjly') {
      inputFlagSjly.value.focus()
    }
    if (column.property == 'xiangmuZhi') {
      inputXiangMuZhi.value.focus()
    }
    if (column.property == 'xiangmuXyz') {
      inputXiangMZuXyz.value.focus()
    }
    if (column.property == 'luruSj') {
      timeLuruSj.value.focus()
    }
  })
};

// 四舍五入的实现
const round = (value, decimalPlaces) => {
  const numericValue = parseFloat(value);
  const factor = Math.pow(10, decimalPlaces);
  const roundedValue = Math.round(numericValue * factor) / factor;
  return roundedValue.toFixed(decimalPlaces); // 确保返回固定小数位数
};

// 四舍六入的实现
const roundWithSixFiveEven = (value, decimalPlaces) => {
  const factor = Math.pow(10, decimalPlaces); // 用于处理小数点后的位数
  const valueWithFactor = value * factor;
  let intPart = Math.floor(valueWithFactor); // 整数部分
  const decimalPart = valueWithFactor - intPart; // 小数部分

  // 获取要舍弃的首位数字
  const lastDigit = Math.floor(decimalPart * 10); // 舍弃部分的首位数字

  if (lastDigit === 5) {
    // 检查5后面是否全为0
    const remainingPart = valueWithFactor * 10 - Math.floor(valueWithFactor * 10);
    if (remainingPart === 0) {
      // 如果5后面全为0，查看5前一位数字是奇数还是偶数
      if (intPart % 2 === 0) {
        // 5前面是偶数，舍去
        return (intPart / factor).toFixed(decimalPlaces);
      } else {
        // 5前面是奇数，进位
        intPart += 1;
      }
    } else {
      // 5后面有非零数字，直接进位
      intPart += 1;
    }
  } else if (lastDigit >= 6) {
    // 如果舍去的数字大于等于6，进位
    intPart += 1;
  }

  // 返回最终四舍五入的结果
  return (intPart / factor).toFixed(decimalPlaces);
};

// 根据修约规则和小数位数更新修约值
const updateXiangmuXyz = (value, xiuyuegz, xiaoshuwei) => {
  if (xiuyuegz === '四舍五入') {
    return round(value, xiaoshuwei); // 使用四舍五入
  } else if (xiuyuegz === '四舍六入') {
    return roundWithSixFiveEven(value, xiaoshuwei); // 使用四舍六入
  }
  return value; // 如果没有修约规则，返回原值
};


const smpTypeList = ref([])
// 查询委托类型
const queryWTLXType = () => {
  var url = 'sci/Weituogl/query_YLType'
  var param = {}
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      smpTypeList.value = response.data.data
      // console.log(smpTypeList.value)
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
/**
 * 重置查询条件
 */
const showA = ref(false)
const show = () => {
  showA.value = !showA.value
}
/**
 * 重置查询条件
 */
const reset = () => {
  Object.keys(query.value).map(key => {
    query.value[key] = ''
  })

}

// 查询 物料名称
const typeList = ref([])
const queryType = () => {
  var url = 'sci/platform/queryType'
  var param = {}
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      typeList.value = response.data.data
      console.log(response.data.data)
      console.log(typeList.value)
      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
// ==========按钮功能===========

// 保存下方数据修改
var userName = localStorage.getItem('userDesc')
const handleSave = () => {
  if (!rows.value) {
    ElMessage({
      type: 'warning',
      message: '请选择要保存哪一行的数据!'
    })
    return
  }
  if (updatedData.value.length == 0) {
    ElMessage.warning('没有修改数据哦~~')
    return
  }
  // // 计算所有 xiangmuZhi 的总和
  // const totalXiangmuZhi = ref(0); // 定义总和的响应式变量
  // const totalXinangmuXyz =  ref(0)
  // tableData_WL.value.forEach(detail => {
  //   let found = false; // 用于标记是否找到了相等的项
  //
  //   updatedData.value.forEach(item => {
  //     if (item.xiangmuMc === detail.xiangmuMc) {
  //       // 如果名称相等，则加上 updatedData 的 xiangmuZhi
  //       totalXiangmuZhi.value += parseFloat(item.xiangmuZhi) || 0;
  //       totalXinangmuXyz.value += parseFloat(item.xiangmuXyz) || 0
  //       found = true;
  //     }
  //   });
  //
  //   if (!found) {
  //     // 如果没有找到相等的项，则加上 detailData 的 xiangmuZhi
  //     totalXiangmuZhi.value += parseFloat(detail.xiangmuZhi) || 0;
  //     totalXinangmuXyz.value += parseFloat(detail.xiangmuXyz) || 0
  //   }
  // });
  // tableData_HX.value.forEach(item =>{
  //   totalXiangmuZhi.value += parseFloat(item.xiangmuZhi) || 0
  //   totalXinangmuXyz.value += parseFloat(item.xiangmuXyz) || 0
  // })
  //
  // if (totalXiangmuZhi.value > 100 || totalXinangmuXyz.value > 100) {
  //   ElMessage({
  //     message: '所有项的数值总和不能超过 100，请修改后再保存',
  //     type: 'error',
  //   })
  //   return
  // }
  var url = 'sci/resultAudit/edit'
  let dept = localStorage.getItem('dept')
  dept = JSON.parse(dept)
  let deptCode = dept[0].deptCode
  var param = {
    json: JSON.stringify(updatedData.value),
    userName: userName,
    deptCode
  }
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      form.value = response.data.data
      ElMessage({
        message: '保存成功',
        type: 'success',
      })
      getTableData()
    } else {
      ElMessage({
        message: '操作失败' + response.data.msg,
        type: 'error'
      })
    }
  })
}
// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getTableData()
  tableData_WL.value = []
}


// 审核提交
const handleCommit = () => {
  console.log('提交方法')
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要提交的数据!'
    })
    return
  }
  var ids = []
  multipleSelection.value.forEach((item, index) => {
    ids.push(item.委托编号)
  })
  let dept = localStorage.getItem('dept')
  dept = JSON.parse(dept)
  let deptCode = dept[0].deptCode
  var userName = localStorage.getItem('userDesc')
  var url = 'sci/resultAudit/commit'
  var param = {
    ids: JSON.stringify(ids),
    userName: userName,
    deptCode
  }
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0') {
      ElMessage({
        type: 'success',
        message: '操作成功!',
      });
      getTableData()
      dialogVisible.value = false
    } else {
      ElMessage({
        type: 'error',
        message: '操作失败!' + response.data.msg
      });
    }
  })
}

//上传MES
const handleMES = () => {
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要上传的数据!'
    })
    return
  }
  var ids = []
  multipleSelection.value.forEach((item, index) => {
    ids.push(item.委托编号)
  })
  let dept = localStorage.getItem('dept')
  let deptCode = dept[0].deptCode

  var url = 'sci/min/uploadMES'
  var param = {
    ids: JSON.stringify(ids),
    userName: userName,
    deptCode: deptCode
  }
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0') {
      ElMessage({
        type: 'success',
        message: '上传成功!',
      });
      query.value.songyangid = ''
      getTableData()

    } else {
      ElMessage({
        type: 'error',
        message: '上传失败!' + response.data.msg
      });
    }
  })
}

// 批量删除
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  console.log(val)
}

// 批量编辑

// 导出
const handleExport = () => {
  console.log('导出')
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请至少选择一条数据导出!'
    })
    return
  }
  var params = {
    ids: multipleSelection.value.map(item => item.委托编号)
  }
  location.href = import.meta.env.VITE_BASE_API +
      '/sci/export/exportExcel?params=' + encodeURIComponent(JSON.stringify(params))
}


// ==========查询数据===========
const tableData = ref([])
const orderedKeys = ref([]);
const listKey = ref([])
const getTableData = () => {
  var url = 'sci/resultAudit/query'
  var param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(query.value),
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      tableData.value = response.data.data.records
      console.log(tableData.value)
      const dynamicKeysSet = new Set();
      tableData.value.forEach(currentObj => {
        Object.keys(currentObj).forEach(key => {
          if (!orderedKeys.value.includes(key)) { // 如果 key 不在 orderedKeys 中，添加到 dynamicKeysSet
            dynamicKeysSet.add(key);
          }
        });
      });
      // 将 dynamicKeysSet 转换为数组
      const sortedDynamicKeys = Array.from(dynamicKeysSet).sort((a, b) => {
        // 判断是否包含中文字符，包含中文字符的会返回 true
        const isChinese = text => /[\u4e00-\u9fa5]/.test(text);
        if (a.includes('HUAXUE') && b.includes('WULI')) return -1;
        if (a.includes('WULI') && b.includes('HUAXUE')) return 1;
        return 0; // 保持原顺序
      });

      // 将排序后的数组重新转换为 Set
      dynamicKeysSet.clear();
      sortedDynamicKeys.forEach(key => {
        key = key.substring(0, key.indexOf('_'));
        console.log(key)
        dynamicKeysSet.add(key)
      });

      console.log(dynamicKeysSet)
      // 将静态字段和动态字段合并，生成最终顺序的 listKey
      listKey.value = [...orderedKeys.value, ...Array.from(dynamicKeysSet)];
      listKey.value = listKey.value.filter(x => x !== 'ROW');
      console.log(listKey.value)
      tableData.value.forEach(x => {
        let y = Object.keys(x);
        y.forEach(name => {
          if (name.includes('_')) {
            // 新的属性名为截取到下划线之前的部分
            const newName = name.substring(0, name.indexOf('_'));
            // 为 x 对象添加新属性，并赋予原属性的值
            x[newName] = x[name];
            // 删除旧的属性
            delete x[name];
          }
        });

        // 根据样品类型匹配并替换
        smpTypeList.value.forEach(y => {
          if (x.样品类型 == y.bm) {
            x.样品类型 = y.wtmc;
          }
        });

        console.log(x);
      });

      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
};

// ==========查询物理数据===========
const tableData_WL = ref([])
const getTableData_WL = (id) => {
  var url = 'sci/resultAudit/query_WL'
  var param = {
    id: id,
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      tableData_WL.value = response.data.data
      // console.log(response.data.data)
      // console.log(tableData_WL.value)
      // totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
};

//查询化学数据
const tableData_HX = ref([])
const getTableData_HX = (id) => {
  var url = 'sci/resultAudit/query_HX'
  var param = {
    id: id,
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      tableData_HX.value = response.data.data

    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
};

/**
 * 分页
 */
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([10, 20, 30, 40])
const pageSize = ref(10)
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
  tableData_WL.value = []
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
  tableData_WL.value = []
}
/**
 * 分页
 */

// 点击行时执行的操作
const top_row = ref({})
const rows = ref()
const handleRowClick1 = (row) => {
  console.log(row.委托编号)
  top_row.value = row
  rows.value = row
  updatedData.value = []
  getTableData_WL(row.委托编号)
  getTableData_HX(row.委托编号)
};


</script>

<style></style>