<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-form inline>
        <el-row :span="24">
          <el-col :span="5">
            <el-form-item label="委托编号" prop="">
              <el-input v-model="query.weituoid" placeholder="请输入委托编号" clearable style="width: 180px;">

              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="样品编号" prop="">
              <el-input v-model="query.ypbh" placeholder="请输入样品编号" clearable style="width: 180px;">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="物料名称" prop="">
              <el-select v-model="query.leibiemc" placeholder="请选择物料名称" filterable clearable style="width: 200px;">
                <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="7">
            <el-form-item label="操作时间" prop="">
              <el-date-picker v-model="query.czsj" type="datetimerange" align="right" unlink-panels
                              range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
                              style="width: 390px;" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>


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

    </el-card>
    <el-card :body-style="cardBodyStyle">
      <el-button type="primary" plain @click="handleSearch">查询</el-button>
    </el-card>
    <el-card :body-style="cardBodyStyle">
      <el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChange">
        <el-table-column type="selection" fixed></el-table-column>
        <el-table-column prop="weituoid" label="委托编号" width="200" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="ypbh" label="样品编号" width="200" header-align="center" align="center"
                         show-overflow-tooltip></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>
        </el-table-column>
        <el-table-column prop="luren" label="实验员" width="200" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="czsj" label="操作时间" width="200" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="leibiemc" 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>

  </div>
</template>

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


onMounted(() => {

  queryWTLXType()
  handleSearch()
  queryType()
  // queryNBHyjg()

})
const showA = ref(false)

const {proxy} = getCurrentInstance()
const cardBodyStyle = ref(style.card)
const dialogVisible = ref(false)
const form = ref({
  leibiemc: '',
  sftsflag: '',
  lotNumber: '',
  lotName: '',
  weituoztMc: '',
  weituotype: '',
  smpType: '',
  chuangjianname: '',
  tijiaoname: '',
  tijiaosj: '',
  zhiyangsj: '',
  leibieid: '',
  erpbm: '',
  gonghuodw: '',
  gonghuodwid: '',
  contractNo: '',
  shouhuodw: '',
  shouhuodwid: '',
})

var zph ='2411230113'
const queryNBHyjg = ()=>{
  var url = 'sci/JkJlxx/queryHyjg'
  var param = {
    zph:zph
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      console.log(response.data.data,"测试")
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

const ruleFormRef = ref()
const tableData = ref([])
const query = ref({
  leibiemc: '',
  weituoid: '',
  czsj: '',
  ypbh: '',
})

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 title = ref('')

// 查询物料
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)
    }
  })
}



// ==========按钮功能===========
// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}
// 撤回
const handleCancel = () => {
  console.log('撤回防法')
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要撤回的数据!'
    })
    return
  }
  var ids = []
  multipleSelection.value.forEach((item, index) => {
    ids.push(item.id)
  })
  var userName = localStorage.getItem('userDesc')
  var url = 'sci/platform/cancel'
  var param = {
    ids: JSON.stringify(ids),
    userName: userName
  }
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0') {
      ElMessage({
        type: 'success',
        message: '操作成功!',
      });
      getTableData()
      dialogVisible.value = false
    } else {
      ElMessage({
        type: 'error',
        message: '操作失败!' + response.data.msg
      });
      getTableData()
    }
  })
}
// 提交
const handleCommit = () => {
  console.log('提交方法')
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要提交的数据!'
    })
    return
  }
  var ids = []
  multipleSelection.value.forEach((item, index) => {
    ids.push(item.id)
  })
  var userName = localStorage.getItem('userDesc')
  var url = 'sci/platform/commit'
  let dept = localStorage.getItem('dept')
  dept = JSON.parse(dept)
  let deptCode = dept[0].deptCode
  var param = {
    ids: JSON.stringify(ids),
    userName: userName,
    deptCode
  }
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0') {
      ElMessage({
        type: 'success',
        message: '操作成功!',
      });
      getTableData()
      dialogVisible.value = false
    } else {
      ElMessage({
        type: 'error',
        message: '操作失败!' + response.data.msg
      });
      getTableData()
    }
  })
}
// 新增
const handleAdd = () => {
  // console.log('新增')
  title.value = '新增'
  form.value = {}
  dialogVisible.value = true


}
const data = ref()

const getData = async () => {

  var url = 'syi/checkPlan/queryTable'
  var param = {}
  await proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      data.value = response.data.data
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}


// 保存
const handleSave = async (ruleFormRef) => {
  await getData()

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

  })
  // 检查是否在 tableData.value 中存在 leibieid 与 form.value.leibieid 相等的情况
  const matched = data.value.some(y => form.value.leibieid == y.leibieid);
  console.log(matched, 'matched')

  if (!matched) {
    ElMessage.error('请先对该物料进行配置');
    return;
  }


  gongsiList.value.forEach(x => {
    if (form.value.gonghuodw == x.tradePartnerName) {
      form.value.gonghuodwid = x.tradePartnerCode
    }
  })
  gongsiList.value.forEach(x => {
    if (form.value.shouhuodw == x.tradePartnerName) {
      form.value.shouhuodwid = x.tradePartnerCode
    }
  })

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

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

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

// 批量删除
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  console.log(val)
}
const handleRemoveBatch = () => {
  console.log('handleRemoveBatch')
  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 = 'cot/SignRequest/removeBatch'*/
    var param = {
      ids: JSON.stringify(ids)
    }
    proxy.$axios.post(url, param).then(response => {
      if (response.data.code == '0') {
        ElMessage({
          type: 'success',
          message: '操作成功!',
        });
        getTableData()
        dialogVisible.value = false
      } else {
        ElMessage({
          type: 'error',
          message: '操作失败!' + response.data.msg
        });
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}


// 批量编辑
const handleEditBatch = () => {
  console.log('handleEditBatch')
  if (multipleSelection.value.length != 1) {
    ElMessage({
      type: 'warning',
      message: '请选择一条数据编辑!'
    })
    return
  }
  handleEdit(multipleSelection.value[0])
}

// 生成
const handleGenerate = () => {
  console.log('handleGenerate')
}


// 删除
const handleDelete = (row) => {
  if (!((row.weituoztMc === '委托创建' && row.weituoztBm === 'ZT00') || (row.weituoztMc === '委托提交' && row.weituoztBm === 'ZT05'))) {
    ElMessage.error('该委托类型不能操作');
    return;
  }

  ElMessageBox.confirm(
      '确定删除本条记录?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )
      .then(() => {
        var userName = localStorage.getItem('userDesc')
        var url = 'sci/platform/remove'
        var param = {
          id: row.id,
          userName
        }
        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 handleEdit = (row) => {
  title.value = '编辑'
  if (!((row.weituoztMc === '委托创建' && row.weituoztBm === 'ZT00') || (row.weituoztMc === '委托提交' && row.weituoztBm === 'ZT05'))) {
    ElMessage.error('该委托类型不能操作');
    return;
  }

  form.value = JSON.parse(JSON.stringify(row))
  dialogVisible.value = true
}

// ==========查询数据===========
const getTableData = () => {
  var url = 'syi/HUAXUEYSSJ/query'
  var param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(query.value),
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      tableData.value = response.data.data.records
      console.log(tableData.value, 'tableData')
      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
  getTableData()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}

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'
  }],
})
</script>

<style scoped></style>