<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-form status-icon inline v-model="query">
        <el-row :span="24">
          <el-col :span="5">
            <el-form-item label="物料名称">
              <el-select v-model="query.leibiemc" placeholder="请选择物料" filterable clearable style="width: 220px">
                <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="收货单位">
              <el-select v-model="query.shouhuodwid" placeholder="请选择收货单位" clearable style="width: 200px" filterable>
                <el-option v-for="item in gongsiList" :key="item.tradePartnerCode" :label="item.tradePartnerName"
                           :value="item.tradePartnerCode"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="计量日期" prop="">
              <el-date-picker v-model="query.jlTime" type="daterange" align="right" unlink-panels
                              range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
                              style="width: 403px;" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD">
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
    </el-card>

    <el-card :body-style="cardBodyStyle">
      <el-button type="primary" plain @click="handleSearch">委托查询</el-button>
      <el-button type="success" plain @click="handleImport">导入Excel</el-button>
      <el-button type="danger" plain @click="handleDelete">删除今日导入信息</el-button>


    </el-card>
    <ImportExcel ref="ImportExcelRef" :url="importUrl" :formData="formData" @importSuccess="importSuccess">
    </ImportExcel>
    <el-card :body-style="cardBodyStyle">
      <el-table :data="tableData" border highlight-current-row
                @selection-change="handleSelectionChange"
                :row-class-name="rowClassName"
      >
        <el-table-column type="selection" fixed></el-table-column>
        <el-table-column prop="id" label="莱钢计量号" width="150" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="jlTime" label="计量时间" width="180" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="carNo" label="车号" width="100" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="materName" label="物料名称" width="100" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="supName" label="供货单位" width="100" header-align="center" align="center"
                          show-overflow-tooltip></el-table-column>
        <el-table-column prop="recName" label="收货单位" width="180" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="grossb" label="莱钢毛重" width="90" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="tareb" label="莱钢皮重" width="90" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="suttleb" label="莱钢净重" width="90" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="lsSuttleb" label="来时净重" width="90" header-align="center" align="center"
                         show-overflow-tooltip>

        </el-table-column>

        <el-table-column prop="jlsuttleb" label="金岭净重" width="90" header-align="center" align="center"
                         show-overflow-tooltip>

        </el-table-column>
        <el-table-column prop="siji" label="司机" width="90" header-align="center" align="center"
                         show-overflow-tooltip>

        </el-table-column>
      </el-table>
    </el-card>
    <el-card :body-style="cardBodyStyle">
      <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 ButtonBar from '@/components/ButtonBar.vue'
import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance,
  nextTick
} from 'vue'
import style from '@/tools/style'
import {ElMessage, ElMessageBox} from "element-plus";
import {watch, watchEffect} from 'vue';
import ImportExcel from "@/components/ImportExcel.vue";

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

var userName = localStorage.getItem('userDesc')
const {proxy} = getCurrentInstance()
const cardBodyStyle = ref(style.card)
const dialogVisible = ref(false)
const ruleFormRef = ref()
const form = ref({
  pandingtjid: '',
  leibieid: '',
  leibiemc: '',
  chuangjiansj: '',
  smpType: '',
  chuangjianname: '',
  gonghuodw: '',
  gonghuodwid: '',
  contractNo: '',
})


// 计算行样式（转为数字后比较）
const rowClassName = ({ row }) => {
  if (Number(row.jlsuttleb).toFixed(3) !== Number(row.lsSuttleb).toFixed(3)) {
    return 'warning-row';
  }
  return '';
};
const importUrl = ref('syi/JKLGWL/importExcel')
const ImportExcelRef = ref(null)
const handleImport = () => {
  ImportExcelRef.value.open()
}
const importSuccess = () => {
  handleSearch()
}


let dept = localStorage.getItem('dept')
dept = JSON.parse(dept)
let deptCode = dept[0].deptCode
var userId = localStorage.getItem('userId')
const formData = ref({
  userId: userId,
  userName: userName,
  deptCode: deptCode

})
const tableData = ref([])
const query = ref({
  leibiemc: '',
  shouhuodwid: '',
  jlTime:''

})



const query_JLXX = ref({
  leibiemc: '',
  gonghuodw: '',
  contractNo: '',
  zph: '',
  jiliangh: 'Y',
})
const rules = reactive({
  leibiemc: [{
    required: true,
    message: '请选择物料',
    trigger: 'change' | 'blur'
  }],
  contractNo: [{
    required: true,
    message: '请输入合同号',
    trigger: 'change' | 'blur'
  }],
  gonghuodw: [{
    required: true,
    message: '请选择供货单位 ',
    trigger: 'change' | 'blur'
  }],
  shouhuodw: [{
    required: true,
    message: '请选择收货单位',
    trigger: 'change' | 'blur'
  }],
  smpType: [{
    required: true,
    message: '请选择样品类型',
    trigger: 'change' | 'blur'
  }],
})



const handleDelete = () => {

  ElMessageBox.confirm(
      '确定删除今日记录?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )
      .then(() => {
        var url = 'syi/JKLGWL/delete'
        var param = {
        }
        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 title = ref('')
//新增
const handleAdd = () => {
  // console.log('新增')
  title.value = '新增'
  form.value = {}
  dialogVisible.value = true


}
// 存储最新的数据
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 === 'jlgrossb') {
     inputJlgrossb.value.focus();
    }
    if (column.property === 'jltareb') {
     inputJltareb.value.focus();
    }
    if (column.property === 'jlsuttleb') {
      inputJlsuttleb.value.focus();
    }
    if (column.property === 'jlJlNo') {
      inputJlJlNo.value.focus();
    }
  });
};

// 处理失去焦点事件
const blurValueInput = (row, column) => {

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

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

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


  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 validateInput3 = (row) => {
  // 保留数字和小数点，过滤非数字和非法小数点字符
  let value = row.jlsuttleb?.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 MAX_LENGTH = 10;
  if (row.jlsuttleb && row.jlsuttleb.length > MAX_LENGTH) {
    ElMessage.error(`输入长度不能超过 ${MAX_LENGTH} 个字符`);
    row.jlsuttleb = row.jlsuttleb.slice(0, MAX_LENGTH); // 保留前 10 个字符
  }
  // 检查是否有多个小数点
  const dotCount = (value.match(/\./g) || []).length;
  if (dotCount > 1) {
    ElMessage.error('输入格式不正确，不能包含多个小数点');
    row.jlsuttleb = ''; // 清空输入
    return;
  }
};
const validateInput2 = (row) => {
  // 保留数字和小数点，过滤非数字和非法小数点字符
  let value = row.jltareb.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 MAX_LENGTH = 10;
  if (row.jltareb && row.jltareb.length > MAX_LENGTH) {
    ElMessage.error(`输入长度不能超过 ${MAX_LENGTH} 个字符`);
    row.jltareb = row.jltareb.slice(0, MAX_LENGTH); // 保留前 10 个字符
  }
  // 检查是否有多个小数点
  const dotCount = (value.match(/\./g) || []).length;
  if (dotCount > 1) {
    ElMessage.error('输入格式不正确，不能包含多个小数点');
    row.jltareb = ''; // 清空输入
    return;
  }
};

const validateInput1 = (row) => {
  // 保留数字和小数点，过滤非数字和非法小数点字符
  let value = row.jlgrossb.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 MAX_LENGTH = 10;
  if (row.jlgrossb && row.jlgrossb.length > MAX_LENGTH) {
    ElMessage.error(`输入长度不能超过 ${MAX_LENGTH} 个字符`);
    row.jlgrossb = row.jlgrossb.slice(0, MAX_LENGTH); // 保留前 10 个字符
  }
  // 检查是否有多个小数点
  const dotCount = (value.match(/\./g) || []).length;
  if (dotCount > 1) {
    ElMessage.error('输入格式不正确，不能包含多个小数点');
    row.jlgrossb = ''; // 清空输入
    return;
  }
};
const validateInput = (row) => {
  // 保留数字和小数点，过滤非数字和非法小数点字符
  let value = row.jlJlNo.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 MAX_LENGTH = 10;
  if (row.jlJlNo && row.jlJlNo.length > MAX_LENGTH) {
    ElMessage.error(`输入长度不能超过 ${MAX_LENGTH} 个字符`);
    row.jlJlNo = row.jlJlNo.slice(0, MAX_LENGTH); // 保留前 10 个字符
  }
  // 检查是否有多个小数点
  const dotCount = (value.match(/\./g) || []).length;
  if (dotCount > 1) {
    ElMessage.error('输入格式不正确，不能包含多个小数点');
    row.jlJlNo = ''; // 清空输入
    return;
  }
};
const inputJlgrossb = ref(null)
const inputJltareb = ref(null)
const inputJlsuttleb = ref(null)
const inputJlJlNo = ref(null)


const handleEdit = (row) => {
  title.value = '编辑'
  form.value = JSON.parse(JSON.stringify(row))
  dialogVisible.value = true

}

// 查询所有公司
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 reset = () => {
  Object.keys(query.value).map(key => {
    query.value[key] = ''
  })
}


// ==========按钮功能===========

const temp = ref('')

const data = ref([])


const handleSaveZL =()=>{
  console.log(updatedData.value, '保存')
  if(!clickRowValue.value){
    ElMessage({
      type: 'warning',
      message: '请选择要保存哪一行的数据!'
    })
    return
  }

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

    }
  })
}


// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}



const multipleSelection = ref([])
// 勾选一行
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  console.log(val)
}



// ==========================查询数据=========================
const getTableData = () => {
  var url = 'syi/JKLGWL/query'
  var param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(query.value),
    deptCode: deptCode,
    userName: userName
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      tableData.value = response.data.data.records
      console.log(tableData.value,'tableData.value')
      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
};


const clickRowValue = ref({})
// 点击一行需要查询计量信息
const handleChange = (currentRow, column, event) => {

  console.log(event)
  temp.value = currentRow

  clickRowValue.value = currentRow
  getTableData_JLXX(currentRow)
}

const handleReSearch = () => {
  if(!clickRowValue.value){
    return
  }
  getTableData_JLXX(clickRowValue.value)

}

const tableData_JLXX = ref([])
const getTableData_JLXX = (row) => {
  query_JLXX.value.chuangjiansj = query.value.chuangjiansj
  query_JLXX.value.leibiemc = row.leibiemc
  query_JLXX.value.leibieid = row.leibieid
  query_JLXX.value.contractNo = row.contractNo
  query_JLXX.value.gonghuodw = row.gonghuodw
  query_JLXX.value.gonghuodwid = row.gonghuodwid
  query_JLXX.value.jiliangh = row.jiliangh
  query_JLXX.value.zph = row.zph

  var url = 'syi/JkJlxx/query'
  var param = {
    page: currentPage_JLXX.value,
    rows: pageSize_JLXX.value,
    params: JSON.stringify(query_JLXX.value)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      tableData_JLXX.value = response.data.data.records
      // console.log(response.data.data.records[0])
      console.log(tableData_JLXX.value, "tableData_JLXX")
      totalRows_JLXX.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
// 查询 物料名称
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)
    }
  })
}


/**
 * 分页
 */
const currentPage = ref(1)
const totalRows = ref(10)
const pageSizes = ref([ 10, 20, 30, 40])
const pageSize = ref(10)
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}
/**
 * 分页
 */
const currentPage_JLXX = ref(1)
const totalRows_JLXX = ref(10)
const pageSizes_JLXX = ref([5, 10, 20, 30, 40])
const pageSize_JLXX = ref(5)
const handleSizeChange_JLXX = (val) => {
  pageSize_JLXX.value = val
  getTableData_JLXX(clickRowValue.value)
}
const handleCurrentChange_JLXX = (val) => {
  currentPage_JLXX.value = val
  getTableData_JLXX(clickRowValue.value)
}


</script>

<style scoped>
/* 设置红色背景 */
:deep(.el-table .warning-row) {
  background-color: #ffcccc !important;
}
</style>