<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-button type="primary" plain @click="query">查询</el-button>
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="success" plain @click="handleSave">保存项目值</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 v-if="true" prop="id" label="委托编号" width="200" 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="true" prop="zph" label="组批编号" width="200" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column v-if="true" prop="gonghuodw" label="供货单位" width="200" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column v-if="true" prop="startTime" label="开始日期" width="200" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column v-if="true" prop="endTime" label="结束日期" width="200" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column v-if="true" prop="cheshu" label="车数" width="100" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" header-align="center" align="center" width="300px" fixed="right">
          <template #default="scope">
            <el-button type="success" plain @click="editFile(scope.row)">上传附件</el-button>
<!--            <el-button plain type="warning" @click="handleEdit(scope.row)">编辑</el-button>-->
            <el-button plain type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </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-dialog :close-on-click-modal="true" draggable v-model="dialogVisibleFile" width="800px" @open="openDialog"
               @close="closeDialogFile">
      <el-card :body-style="cardBodyStyle">
        <Attachment ref="AttachmentRefManual" :fId="fId"></Attachment>
      </el-card>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" draggable :title="title" v-model="dialogVisible" width="1200px" top="5vh" height="1000px"
               @open="openDialog">
      <el-form :model="queryForm" label-width="120px" label-position="right" inline ref="ruleFormRef" :rules="rules">
        <el-form-item label="样品类型" prop="smpType">
          <el-select v-model="queryForm.smpType" placeholder="请选择样品类型" clearable style="width: 200px;" @change="handleChangeYCG">
            <el-option label="原料委托" value="Y"></el-option>
            <el-option label="成品委托" value="C"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物料类别" prop="leibiemc">
          <el-select v-model="queryForm.leibiemc" placeholder="请选择物料类别" clearable style="width: 200px;">
            <el-option v-for="item in YCGList" :key="item.itemCd" :label="item.itemNm"
                       :value="item.itemNm"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="fhdwmc">
          <el-select v-model="queryForm.fhdwmc" placeholder="请选择供应商" clearable style="width: 200px;" filterable >
            <el-option v-for="item in gongsiList" :key="item.tradePartnerCode" :label="item.tradePartnerName"
                       :value="item.tradePartnerName"/>
          </el-select>
        </el-form-item>

<!--        <el-form-item label="计量时间" prop="suttleTime">-->
<!--          <el-date-picker v-model="queryForm.suttleTime" type="datetimerange" align="right" unlink-panels-->
<!--                          range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"-->
<!--                          style="width: 350px;" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
        <el-form-item label="开始时间" prop="startTime" >
          <el-date-picker
              v-model="queryForm.startTime"
              type="date"
              placeholder="选择日期"
              clearable style="width: 200px;"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="截止时间" prop="endTime">
          <el-date-picker
              v-model="queryForm.endTime"
              type="date"
              placeholder="选择日期"
              clearable
              style="width: 200px;"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="车数" prop="cheshu">
          <el-input v-model="queryForm.cheshu" placeholder="请输入车数" clearable style="width: 200px;">
          </el-input>
        </el-form-item>
      </el-form>
      <el-card :body-style="cardBodyStyle">
        <el-button type="success" @click="handleQuery">查询计量信息</el-button>
      </el-card>

      <el-card :body-style="cardBodyStyle">
        <el-table  :data="jlData" 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">
            <template #default="scope">
              <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="true" prop="jlh" label="计量号" width="150" header-align="center" align="center"
                           show-overflow-tooltip></el-table-column>
          <el-table-column v-if="true" prop="suttleTime" label="计量时间" width="180" header-align="center" align="center"
                           show-overflow-tooltip></el-table-column>
          <el-table-column v-if="true" prop="wuzimc" label="物料" width="180" header-align="center" align="center"
                           show-overflow-tooltip></el-table-column>
          <el-table-column v-if="true" prop="carno" label="车号" width="120" header-align="center" align="center"
                           show-overflow-tooltip></el-table-column>
          <el-table-column v-if="true" prop="fhdwmc" label="供应商" width="150" header-align="center" align="center"
                           show-overflow-tooltip></el-table-column>
          <el-table-column v-if="true" prop="shdwmc" label="收货商" width="150" header-align="center" align="center"
                           show-overflow-tooltip></el-table-column>
          <el-table-column v-if="true" prop="htbh" label="合同号" width="120" header-align="center" align="center"
                           show-overflow-tooltip></el-table-column>
          <el-table-column v-if="true"  prop="mzh" label="毛重" width="80" header-align="center" align="center"
                            show-overflow-tooltip></el-table-column>
          <el-table-column v-if="true"  prop="pzh" label="皮重" width="80" header-align="center" align="center"
                             show-overflow-tooltip></el-table-column>
          <el-table-column v-if="true"  prop="jzh" label="净重" width="80" header-align="center" align="center"
                             show-overflow-tooltip></el-table-column>
        </el-table>
      </el-card>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleSaveJL(ruleFormRef)">保存</el-button>
          <el-button type="danger" @click="handleCancelSave">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <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="400"
              @selection-change="handleSelectionChange"
              @cell-click="showUnitInput"
          >

            <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"
                             show-overflow-tooltip>
<!--              <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 {ElMessage, ElMessageBox} from "element-plus";

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)
const ruleFormRef = ref(null)

onMounted(() => {
  query()
  queryType()
  queryWTLXType()
  queryGS()
  // queryNBHyjg()
})

// var zph ='ZP202502140016'
// var carNo ='冀ET5295'
// const queryNBHyjg = ()=>{
//   var url = 'syi/WFWeituo/queryData'
//   var param = {
//     zph:zph,
//     carNo:carNo
//   }
//   proxy.$axios.get(url, param).then(response => {
//     if (response.data.code == '0') {
//       console.log(response.data.data,"测试")
//     } else {
//       ElMessage.error('操作失败！' + response.data.msg)
//     }
//   })
// }

const rules = reactive({
  leibiemc: [{
    required: true,
    message: '请选择物料',
    trigger: 'change'
  }],
  fhdwmc: [{
    required: true,
    message: '请选择',
    trigger: 'change'
  }],
  smpType: [{
    required: true,
    message: '请选择',
    trigger: 'change'
  }],
  startTime: [{
    required: true,
    message: '请选择',
    trigger: 'change'
  }],
  endTime: [{
    required: true,
    message: '请选择',
    trigger: 'change'
  }],
  cheshu: [{
    required: true,
    message: '请选择',
    trigger: 'change'
  }],
})

import Attachment from '@/components/Attachment.vue';
const fId = ref(null)


const dialogVisibleFile = ref(false)
const editFile = (row) => {
  dialogVisibleFile.value = true
  fId.value = row.id
  form.value = row
}

const closeDialogFile = () => {
  dialogVisibleFile.value = false
}


const handleEdit = (row) => {
  title.value = '编辑';
  dialogVisible.value = true;
  queryForm.value = row;
  queryForm.value.fhdwmc = row.gonghuodw;
  queryForm.value.fhdwbm = row.gonghuodwid;

  // 确保给 smpType 赋值，以便触发 @change 事件
  queryForm.value.smpType = row.smpType || '';  // 如果 row.smpType 是空的，使用空字符串
  handleChangeYCG();  // 手动触发查询
}
var fileId = ref('')
const handleDelete = async (row) => {
  console.log(row.id,'id')
  fileId.value = row.id
 await getFileData()
  if(fileData.value.length > 0){
    ElMessage.error('请先删除附件');
    return;
  }
  ElMessageBox.confirm(
      '确定删除本条记录?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )


.then(() => {
        var url = 'syi/WFWeituo/remove'
        var param = {
          id: row.id
        }
        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 fileData = ref([])
const getFileData = async () => {
  var url = 'framework/Common/queryFile'
  var param = {
    fId: fileId.value
  }
  await proxy.$axios.get(url, param).then(response => {
    if (response.data.code == 0) {
      fileData.value = response.data.data
    } else {
      ELMessage({
        type: 'error',
        message: '失败！' + response.data.msg,
      })
    }
  })
}

// const handleDeleteFile = () => {
//   ElMessageBox.confirm(
//       '此操作将删除该数据, 是否继续?',
//       '提示', {
//         confirmButtonText: '确认',
//         cancelButtonText: '取消',
//         type: 'warning',
//         draggable: true,
//       }
//   )
//       .then(() => {
//         var url = 'framework/Common/removeFile'
//         var param = {
//           id: fileId.value
//         }
//         proxy.$axios.post(url, param).then(response => {
//           if (response.data.code == 0) {
//             ElMessage({
//               type: 'success',
//               message: '删除成功!',
//             });
//             getTableData()
//           } else {
//             ElMessage({
//               type: 'error',
//               message: '删除失败;' + response.data.msg
//             });
//           }
//         });
//       }).catch(() => {
//     ElMessage({
//       type: 'info',
//       message: '已取消删除'
//     })
//   })
// }

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

  typeList.value.forEach(x => {
    if (x.itemNm == form.value.leibiemc) {
      queryForm.value.leibieid = x.itemCd
      console.log(form.value.leibieid,'leibieid')
    }

  })

  gongsiList.value.forEach(x => {
    if (queryForm.value.fhdwmc == x.tradePartnerName) {
      queryForm.value.fhdwbm = x.tradePartnerCode
    }
  })

  var url = 'sci/carEntry/queryJL'
  var param = {
    params: JSON.stringify(queryForm.value)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      console.log(response.data)
      jlData.value = response.data.data
      console.log(jlData.value,'jlData')

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






const YCGList = ref([])
const smpType = ref('')
const handleChangeYCG = ()=>{
  if(!queryForm.value.smpType){
    return
  }
  console.log(form.value.smpType,'form.smpType')
  var url = 'sci/platform/getYCG'
  var param = {
    smpType: queryForm.value.smpType,
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      console.log(response.data)
      YCGList.value = response.data.data
      console.log(YCGList.value,'YCGList.value')

    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
const gongsiList = ref([])
const queryGS = () => {
  gongsiList.value = []
  var url = 'sci/Weituogl/queryGS'
  var param = {}
  proxy.$axios.get(url, param).then(resp => {
    if (resp.data.code == '0') {
      gongsiList.value = resp.data.data
      console.log(gongsiList.value)
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }

  })
}





//单元格规则校验
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) => {
  if (rows.value.wulixgzt == '已提交' || rows.value.weituoztBm > 'ZT75') {
    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 title = ref('')

const handleAdd = ()=>{
  queryForm.value={}
  jlData.value = []
  queryGS()
  dialogVisible.value = true
  title.value = '新增'
}

// 生成委托，并给计量赋值
const handleSaveJL = (ruleFormRef) => {
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择计量数据!'
    })
    return
  }
  if (multipleSelection.value.length != queryForm.value.cheshu) {
    ElMessage({
      type: 'warning',
      message: '所选数据和车数不符，请重新选择!'
    })
    return
  }
  typeList.value.forEach(x => {
    if (x.itemNm == queryForm.value.leibiemc) {
      queryForm.value.leibieid = x.itemCd
    }

  })
  gongsiList.value.forEach(x => {
    if (queryForm.value.gonghuodw == x.tradePartnerName) {
      queryForm.value.fhdwbm = x.tradePartnerCode
    }
  })
  var ids = []
  multipleSelection.value.forEach(item => {
    console.log(item.id, "1111111111111111")
    ids.push(item.id)

  });

  ruleFormRef.validate((valid, fields) => {
    if (valid) {
      let dept = localStorage.getItem('dept')
      dept = JSON.parse(dept)
      let deptCode = dept[0].deptCode
      var url = 'syi/WFWeituo/save'
      var param = {
        json: JSON.stringify(queryForm.value),
        userName: userName,
        deptCode,
        ids:JSON.stringify(ids)
      }
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
          form.value = response.data.data
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          query()
          dialogVisible.value = false
        } else {
          // ElMessage.error('操作失败！' + response.data.msg)
          ElMessage({
            message: '操作失败' + response.data.msg,
            type: 'error'
          })
        }
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}

// 保存物理值
const handleSave = () => {
  if(!rows.value){
    ElMessage({
      type: 'warning',
      message: '请选择要保存哪一行的数据!'
    })
    return
  }
  if (updatedData.value.length == 0) {
    ElMessage.warning('没有修改数据哦~~')
    return
  }


  var url = 'syi/WFHyjg/save'
  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',
      })
      handleReSearch()
      updatedData.value = []
    } else {
      ElMessage({
        message: '操作失败' + response.data.msg,
        type: 'error'
      })
      handleReSearch()
    }
  })
}

// 取消
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/resultEntry/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/resultEntry/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
      });
    }
  })
}
var temp = ref('')
const rows = ref()
const handleRowClick = (row, event, column) => {
  getDetailData(row.id)
  temp.value = row.id
  rows.value = row
  console.log(rows.value, "222222222222")


}
const detailData = ref([])

// 下方数据查询
const getDetailData = (id) => {
  var url = 'syi/WFHyjg/query'
  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 handleReQuery = () => {


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

    ElMessage({
      type: 'warning',
      message: '请选择要重新补充的检验项目!'
    })
    return
  }
  var url = 'syi/WFHyjg/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 handleReSearch= () => {
  if (temp.value == '' || temp.value == null) {

    return
  }
  console.log(temp.value)
  getDetailData(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: '',
  leibieid:'',
  smpType: '',
  startTime:'',
  endTime:'',
  cheshu:'',
  fhdwmc:'',
  fhdwbm:''

})


const form = ref({
  xiangmuMc: '',
  xiangmuZhi: '',
  xiangmuXyz: '',
  luruRen: '',
  luruSj: '',
  flagSjly: ''
})
const queryForm2 = ref({
  time: '',

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


const tableData = ref([])

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


const query = () => {

  detailData.value = []
  temp.value = ''
  var url = 'syi/WFWeituo/queryWeituo'
  var param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(queryForm2 .value)
  }

  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      tableData.value = response.data.data.records
      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
/**
 *   查询
 */


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


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

const openDialog = () => {
}


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

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>