<template>
  <div>
    <el-card :body-style="cardBodyStyle">

      <el-form ref="queryFormRef" :inline="true" :model="queryForm" status-icon>
        <el-row>
          <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-row>
      </el-form>
    </el-card>
    <el-card :body-style="cardBodyStyle">
      <el-button type="primary" plain @click="query">条件查询</el-button>
      <el-button type="success" plain @click="handleSaveTfe">保存成分值</el-button>
      <el-button type="success" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="handleDelete">删除</el-button>
    </el-card>
  </div>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-table :data="tableData" border highlight-current-row
                @selection-change="handleSelectionChange"  @cell-click="showUnitInput">
        <el-table-column type="selection" fixed></el-table-column>
        <el-table-column v-if="true" prop="wuzimc" label="物料名称" width="200" header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="shengchanTime" label=日期 width="200" header-align="center"
            align="center"
            show-overflow-tooltip
            :formatter="formatDate"

        >
        </el-table-column>
        <el-table-column prop="banCi"
                         label="班次" width="200" header-align="center"
                         align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="tfe" label="TFe" 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.tfe"
                      ref="inputTfe"/>
            <span v-else @click="enableEdit(row, column)">{{ row.tfe }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="lururenXm" label="录入人" width="200"
                         header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="luruSj" 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-dialog :close-on-click-modal="false" draggable title="新增" v-model="dialogVisible" width="1200px" top="5vh"
               @open="openDialog">
      <el-form :model="form" label-width="120px" label-position="right" inline ref="ruleFormRef" :rules="rules">


        <el-form-item label="选择日期" prop="shengchanTime">
          <el-date-picker
              v-model="insertForm.shengchanTime"
              type="date"
              placeholder="选择日期"
              clearable style="width: 200px;"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleSave(ruleFormRef)">保存</el-button>
          <el-button type="danger" @click="handleCancelSave">取消</el-button>
        </div>
      </template>
    </el-dialog>

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

onMounted(() => {
  query()
  queryType()
})
const rules = reactive({
  shengchanTime: [
    {required: true, message: '请选择日期', trigger: 'blur'},
  ]
})


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

const handleAdd = () => {
  dialogVisible.value = true
  insertForm.value = {
  }
}


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


// //单元格校验规则
// const validateInput = (row) => {
//   // 保留数字和小数点，过滤非数字和非法小数点字符
//   let value = row.tfe?.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.tfe = value; // 保留合法输入
//   } else if (isNaN(numericValue)) {
//     ElMessage.error('输入格式不正确,请输入数字');
//     row.tfe = ''; // 清空输入
//   } else if (numericValue > 100 && value != '') {
//     ElMessage.error('最大值为100');
//     row.tfe = 100;
//   }
//
//   const MAX_LENGTH = 10;
//   if (row.tfe && row.tfe.length > MAX_LENGTH) {
//     ElMessage.error(`输入长度不能超过 ${MAX_LENGTH} 个字符`);
//     row.tfe = row.tfe.slice(0, MAX_LENGTH); // 保留前 10 个字符
//   }
//
//   // 检查是否有多个小数点
//   const dotCount = (value.match(/\./g) || []).length;
//   if (dotCount > 1) {
//     ElMessage.error('输入格式不正确，不能包含多个小数点');
//     row.tfe = ''; // 清空输入
//     return;
//   }
// };

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

// 处理单元格点击事件
const showUnitInput = (row, column) => {
  tableRowEditId.value = row.id; // 确定点击的单元格在哪行
  tableColumnEditIndex.value = column.id; // 确定点击的单元格在哪列
  nextTick(() => {
    if (column.property == 'tfe') {
      inputTfe.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

  // 更新修约值

  // 创建一个新的行数据对象
  const updatedRow = {
    id: row.id,
    tfe: row.tfe
  };

  // 查找原始数据行
  const originalRow = updatedData.value.find(item => item.id === row.id);

  // 判断编辑的数据是否与原始数据不同
  const hasChanges = !originalRow ||
      originalRow.tfe !== updatedRow.tfe;

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

const enableEdit = (row, column) => {
  tableRowEditId.value = row.id;
  tableColumnEditIndex.value = column.id;
  nextTick(() => {
    // 聚焦输入框
    if (inputTfe.value) {
      inputTfe.value.focus();
    }
  });
};
//保存成分值
const handleSaveTfe = () => {

  console.log(updatedData.value,'updatedData.value')
  let userName = localStorage.getItem('userDesc')
  var url = 'sci/GcHuaXue/saveTfe'
  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()
      updatedData.value = []
    } else {
      ElMessage({
        message: '操作失败' + response.data.msg,
        type: 'error'
      })
      handleReSearch()
    }
  })
}

const handleSave = () => {

  let userName = localStorage.getItem('userDesc')
  var url = 'sci/GcHuaXue/save'
  var param = {
    json: JSON.stringify(insertForm.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()
      updatedData.value = []
      dialogVisible.value = false
    } else {
      ElMessage({
        message: '操作失败' + response.data.msg,
        type: 'error'
      })
      handleReSearch()
      dialogVisible.value = false
    }
  })
}



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 rows = ref()
const huaxue = ref()
/**
 *   查询
 */


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

  }
  getDetailData(temp.value)
}
const handleDelete = () => {
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据!'
    })
    return
  }
  ElMessageBox.confirm('此操作将删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    var ids = []
    multipleSelection.value.forEach((item, index) => {
      ids.push(item.id)
    })
    var url = 'sci/GcHuaXue/removeBatch'
    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
        });
        query()
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

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({
  shengchanTime: ''
})


const form = ref({
  tfe:''
})

const insertForm = ref({
  shengchanTime: ''
})

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


const tableData = ref([])
const orderedKeys = ref([]);
const listKey = ref([])
const query = () => {
  var url = 'sci/GcHuaXue/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
      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>