<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-row>
        <el-form ref="queryFormRef" :inline="true" :model="queryForm" status-icon>
          <el-row>
            <el-col :span="5">
              <el-form-item prop="leibiemc" label="物料名称">
                <el-select v-model="queryForm.leibiemc" size="normal" filterable style="width:200px" clearable>
                  <el-option v-for="item in typeList" key="item.itemCd" :label="item.itemNm"
                             :value="item.itemNm"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item prop="wuliPdsj" label="是否提交">
                <el-select v-model="queryForm.huaxuePdsj" size="normal" style="width:200px" clearable>
                  <el-option label="已提交" value="0"/>
                  <el-option label="未提交" value="1"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="样品类型" prop="">
                <el-select v-model="queryForm.smpType" placeholder="请选择样品类型" clearable style="width: 200px;">
                  <el-option v-for="item in smpTypeList" :key="item.bm" :label="item.wtmc"
                             :value="item.bm"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item prop="" label="化学制样编号">
                <el-input v-model="queryForm.huaxuezybh" placeholder="" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="4">

              <el-button type="primary" link @click="show">
                高级查询
                <el-icon v-if="showNode">
                  <ArrowUp/>
                </el-icon>
                <el-icon v-else>
                  <ArrowDown/>
                </el-icon>
              </el-button>
              <el-button type="primary" link @click="reset">
                重置
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-row>
      <el-row v-if="showNode">

        <el-col :span="5">
          <el-form-item label="生产时间" prop="">
            <el-date-picker
                v-model="queryForm.shengchanTime"
                type="date"
                placeholder="请选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="chemRcvTime" label="化学接样时间">
            <el-date-picker v-model="queryForm.chemRcvTime" 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-card>
    <el-card :body-style="cardBodyStyle">
      <el-button type="primary" plain @click="query">条件查询</el-button>
      <el-button type="primary" plain @click="handleSave">保存成分值</el-button>
      <el-button type="success" plain @click="handleCommit">提交</el-button>
      <el-button type="danger" plain @click="handleCancel">撤销提交</el-button>
      <el-button type="success" plain @click="handleReQuery">补充检验项目</el-button>
<!--      <el-button type="info" plain @click="handleExport">导出为excel文件</el-button>-->
    </el-card>
  </div>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-table :data="tableData" height="250" border highlight-current-row @row-click="handleRowClick"
                @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 v-if="true" prop="id" label="委托编号" width="180" header-align="center" align="center"
                         show-overflow-tooltip >
        </el-table-column>
        <el-table-column v-if="true" prop="leibiemc" label="物料名称" width="120" header-align="center" align="center"
                         show-overflow-tooltip >
        </el-table-column>
        <el-table-column v-if="tableData.some(item => item.smpType == 'G'&&item.weituolx=='生产委托')" prop="shengchanTime" label="生产时间" width="120" header-align="center"
                         align="center"
                         show-overflow-tooltip
                         :formatter="formatDate"
        >
        </el-table-column>
        <el-table-column v-if="tableData.some(item => item.smpType == 'G'&&item.weituolx=='生产委托')" prop="banCi" label="班次" width="60" header-align="center"
                         align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="tableData.some(item => item.smpType !== 'G')" prop="gonghuodw" label="供货商" width="150" header-align="center" align="center"
                         show-overflow-tooltip >
        </el-table-column>
        <el-table-column v-if="tableData.some(item => item.smpType !== 'G')" prop="shouhuodw" label="收货商" width="150" header-align="center" align="center"
                         show-overflow-tooltip >
        </el-table-column>
        <el-table-column v-if="tableData.some(item => item.smpType !== 'G')" prop="startTime" label="开始时间" width="180" header-align="center" align="center"
                         show-overflow-tooltip >
        </el-table-column>
        <el-table-column v-if="tableData.some(item => item.smpType !== 'G')" prop="endTime" label="结束时间" width="180" 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 v-if="true" prop="weituotype" label="检验类型" width="100" header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>

        <el-table-column v-if="true" prop="weituoztMc" label="委托状态" width="160" header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="smpType" label="样品类型" width="120" header-align="center" align="center"
                         show-overflow-tooltip>
          <template #default="{ row }">
            {{ smpTypeList.find(item => item.bm === row.smpType)?.wtmc }}
          </template>
        </el-table-column>
        <el-table-column  prop="quyangsj" label="取样时间" width="200" header-align="center"
                          align="center"
                          show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="chemRcvSmpName" label="接样人" width="100" header-align="center"
                         align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="chemRcvTime" label="接样时间" width="190" header-align="center"
                         align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="huaxuePdsj" label="化学提交时间" width="200" header-align="center"
                         align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="huaxuePdrname" label="化学提交人" width="100" header-align="center"
                         align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="huaxuezybh" label="化学制样编号" width="200" 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>

    <el-card :body-style="cardBodyStyle">
      <el-tabs v-model="activeNameBottom" type="border-card">
        <el-tab-pane label="化学数据" name="first">
          <el-table
              :data="detailData"
              border
              highlight-current-row
              height="250"
              @selection-change="handleSelectionChange"
              @cell-click="showUnitInput"
          >
<!--            <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-card>

  </div>
</template>

<script setup>

import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance, nextTick
} from 'vue'

const {
  proxy
} = getCurrentInstance()

import tools from '@/tools'
import ButtonBar from "@/components/ButtonBar.vue";
import {ElMessage, ElMessageBox} from "element-plus";
import { computed } from 'vue';
const cardBodyStyle = ref(tools.style.card)
const inputStyle = ref(tools.style.input)
const queryFormRef = ref(null)
const activeNameTop = ref('master')
const activeNameBottom = ref('first')
const tableDataMaster = ref([])
const dialogVisible = ref(false)


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

const isGuochengWeituo = computed(() => {
  return tableData.some(item => item.smpType === 'G');
});

let dept = localStorage.getItem('dept')
dept = JSON.parse(dept)
let deptCode = dept[0].deptCode

//重置表单
const reset = () => {
  Object.keys(queryForm.value).map(key => {
    queryForm.value[key] = ''
  })
}

// 格式化日期的函数
const formatDate = (row, column, cellValue) => {
  if (cellValue) {
    const date = new Date(cellValue);
    return date.toLocaleDateString(); // 只显示日期部分
  }
  return '';
};

//发送MES
const handleMES =() => {
  console.log('发送MES')
  ElMessage({
    type: 'success',
    message: '该功能暂未开发'
  })

}

//单元格校验规则
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 showUnitInput = (row, column) => {
  console.log(rows.value,'rows.value')
  if (rows.value.huaxuexgxt == '已提交') {
    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 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);
  }

  // 清除编辑状态
  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 handleSave = () => {
  if(!rows.value){
    ElMessage({
      type: 'warning',
      message: '请选择要保存哪一行的数据!'
    })
    return
  }
  if (updatedData.value.length == 0) {
    ElMessage.warning('没有修改数据哦~~')
    return
  }
  // const totalXiangmuZhi = ref(0); // 定义总和的响应式变量
  // const totalXiangmuXyz = ref(0);
  // detailData.value.forEach(detail => {
  //   let found = false; // 用于标记是否找到了相等的项
  //
  //   updatedData.value.forEach(item => {
  //     if (item.xiangmuMc === detail.xiangmuMc) {
  //       // 如果名称相等，则加上 updatedData 的 xiangmuZhi
  //       totalXiangmuZhi.value += parseFloat(item.xiangmuZhi) || 0;
  //       totalXiangmuXyz.value += parseFloat(item.xiangmuXyz) || 0;
  //       found = true;
  //     }
  //   });
  //
  //   if (!found) {
  //     // 如果没有找到相等的项，则加上 detailData 的 xiangmuZhi
  //     totalXiangmuZhi.value += parseFloat(detail.xiangmuZhi) || 0;
  //     totalXiangmuXyz.value += parseFloat(detail.xiangmuZhi) || 0;
  //   }
  // });
  // wlData.value.forEach(item=>{
  //   totalXiangmuZhi.value += parseFloat(item.xiangmuZhi) || 0
  //   totalXiangmuXyz.value += parseFloat(item.xiangmuZhi) || 0
  // })
  //
  // if (totalXiangmuZhi.value > 100||totalXiangmuXyz.value >100) {
  //   ElMessage({
  //     message: '所有项的数值总和不能超过 100，请修改后再保存',
  //     type: 'error',
  //   })
  //   return
  // }

  let userName = localStorage.getItem('userDesc')
  var url = 'sci/CresultEntry/edit'
  var param = {
    json: JSON.stringify(updatedData.value),
    userName: userName,
    deptCode: deptCode
  }
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      form.value = response.data.data
      ElMessage({
        message: '保存成功',
        type: 'success',
      })
      query()
      handleReSearch()
      updatedData.value = []
    } else {
      ElMessage({
        message: '操作失败' + response.data.msg,
        type: 'error'
      })
      handleReSearch()
    }
  })
}

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


const handleCancelSave = () => {
  dialogVisible.value = false
}



// 查询物料
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)
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
var userName = localStorage.getItem('userDesc')
// 化学提交
const handleCommit = () => {
  console.log('handleCommit')
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要提交的数据!'
    })
    return
  }
  var ids = []
  multipleSelection.value.forEach(item => {
    console.log(item, "1111111111111111")
    ids.push(item.id)

  });

  ElMessageBox.confirm('此操作将会把数据进行提交, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    var url = 'sci/CresultEntry/commit'
    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()
      } else {
        ElMessage({
          type: 'error',
          message: '操作失败!' + response.data.msg
        });
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消提交'
    })
  })
}


//撤销提交
const handleCancel = () => {
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要撤回的数据!'
    })
    return
  }
  var ids = []
  multipleSelection.value.forEach((item, index) => {
    ids.push(item.id)
  })
  var url = 'sci/CresultEntry/cancel'
  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()
    } else {
      ElMessage({
        type: 'error',
        message: '操作失败!' + response.data.msg
      });
    }
  })
}
const rows = ref()
const huaxue = ref()
const handleRowClick = (row, event, column) => {
  getDetailData(row.id)
  getWLData(row.id)
  temp.value = row.id
  rows.value = row
  updatedData.value = []
  console.log(rows.value,"rows")

}
const detailData = ref([])

// 下方数据查询
const getDetailData = (id) => {
  var url = 'sci/CresultEntry/queryHX'
  var param = {
    id: id,
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      detailData.value = response.data.data
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })

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

}
/**
 *   查询
 */


/**
 * 补充检验项目
 */
const temp = ref()
const handleReSearch = () => {
  if (temp.value == '' || temp.value == null) {
    return

  }
  getDetailData(temp.value)
}
const handleReQuery = () => {

  if (temp.value == '' || temp.value == null) {

    ElMessage({
      type: 'warning',
      message: '请选择要重新补充的检验项目!'
    })
    return
  }
  var url = 'sci/CresultEntry/handleReQuery'
  var param ={
    id:temp.value,
    userName:userName,
    deptCode:deptCode
  }
  proxy.$axios.post(url,param).then(response => {
    if (response.data.code == '0') {
      ElMessage({
        type: 'success',
        message: '操作成功!',
      });
      getDetailData(temp.value)
    } else {
      ElMessage({
        type: 'error',
        message: '操作失败!' + response.data.msg
      });
      getDetailData(temp.value)
    }
  })


  console.log(temp.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 queryForm = ref({
  leibiemc: '',
  huaxuePdsj: '1',
  huaxuezybh: '',
  smpType: '',
  chemRcvTime: '',
  chengchanTime:''
})


const form = ref({
  xiangmuMc: '',
  xiangmuZhi: '',
  xiangmuXyz: '',
  luruRen: '',
  luruSj: '',
  flagSjly: '',

})

const showNode = ref(false)
const show = () => {
  showNode.value = !showNode.value
}


const tableData = ref([])
const orderedKeys = ref([]);
const listKey = ref([])
const query = () => {
  detailData.value = []
  var url = 'sci/CresultEntry/query'
  var param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(queryForm.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 currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([10, 20, 30, 40])
const pageSize = ref(10)
const handleSizeChange = (val) => {
  pageSize.value = val
  query()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  query()
}
/**
 * 分页
 */


/**
 * 保存、修改、删除
 */


/**
 * 保存、修改、删除
 */

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}


</script>

<style scoped>
::v-deep .diaClass90 .el-form-item {
  width: 90%
}

.el-descriptions {
  margin-top: 20px;
}

.cell-item {
  display: flex;
  align-items: center;
}

.margin-top {
  margin-top: 20px;
}
</style>