<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-input v-model="query.id" placeholder="请输入委托编号" clearable style="width: 220px">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="供货单位">
              <el-select v-model="query.gonghuodw" placeholder="请选择供货单位" filterable clearable style="width: 220px">
                <el-option v-for="item in gongsiList" :key="item.tradePartnerCode" :label="item.tradePartnerName"
                           :value="item.tradePartnerName"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="委托时间">
              <el-date-picker v-model="query.chuangjiansj" type="datetimerange" align="right" unlink-panels
                              range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
                              style="width: 375px;"
                              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 plain type="primary" icon="el-icon-search" @click="handleSearch">委托查询</el-button>
    </el-card>
    <el-card :body-style="cardBodyStyle">
      <el-table @row-click="handleChange" :data="tableData" border highlight-current-row height="250"
                @selection-change="handleSelectionChange" ref="tableRef1">
        <el-table-column type="selection" fixed></el-table-column>
        <el-table-column v-if="true" prop="id" label="委托编号" width="170" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column v-if="true" prop="chuangjiansj" label="委托时间" width="180" header-align="center"
                         align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column v-if="true" prop="leibiemc" label="物料类别" width="130" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>

        <el-table-column v-if="true" prop="zupibh" label="组批编号" width="140" 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="shouhuodw" label="收货单位" width="200" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column v-if="true" prop="contractNo" label="计划号" width="200" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column v-if="true" prop="chehao" label="车号" width="180" header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="cheshu" label="车数" width="80" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" header-align="center" align="center" width="180px" fixed="right">
          <template #default="scope">
            <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>

  </div>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-table :data="tableData_JLXX" border highlight-current-row height="250"
                @selection-change="handleSelectionChange_JLXX">
        <el-table-column type="selection" fixed></el-table-column>

        <el-table-column prop="jlh" label="计量号" width="160" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="suttleTime" label="计量时间" width="200" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="carno" label="车号" width="150" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="wuzimc" label="物料名称" width="200" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="zph" label="组批编号" width="200" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="planNumber" label="计划号" width="200" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="fhdwmc" label="供货单位" width="240" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="shdwmc" label="收货单位" width="240" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
      </el-table>
      <el-pagination :current-page="currentPage_JLXX" :page-size="pageSize_JLXX" :page-sizes="pageSizes_JLXX"
                     :total="totalRows_JLXX" background="background" layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange_JLXX" @current-change="handleCurrentChange_JLXX">
      </el-pagination>
    </el-card>
    <el-dialog :close-on-click-modal="false" draggable :title="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="smpType">
          <el-select v-model="form.smpType" placeholder="请选择样品类型" clearable style="width: 200px;"
                     @change="handleChangeYCG" disabled="disabled">
            <el-option label="原料委托" value="Y"></el-option>
            <el-option label="成品委托" value="C"></el-option>
            <el-option label="过程委托" value="G"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物料类别" prop="leibiemc">
          <el-select v-model="form.leibiemc" placeholder="请选择物料类别" filterable clearable style="width: 200px;"
                     @change="getJiHuahao" disabled="disabled">
            <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="contractNo" label-width="120px">
          <el-select v-model="form.contractNo" placeholder="请选择计划号" clearable style="width: 200px;">
            <el-option
                v-for="item in jihuahaos"
                :key="item.id"
                :label="item.planNumber"
                :value="item.planNumber"
                style="width: 600px;"
            >
              <template #default>
                <div>
                  <strong>{{ item.planNumber }}</strong> -- {{
                    item.fhdwmc
                  }} -- {{ item.shdwmc }}
                </div>
              </template>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="gonghuodw">
          <el-select v-model="form.gonghuodw" placeholder="请选择供应商" clearable style="width: 200px;">
            <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="shouhuodw">
          <el-select v-model="form.shouhuodw" placeholder="请选择收货商" clearable style="width: 200px;">
            <el-option v-for="item in gongsiList" :key="item.tradePartnerCode" :label="item.tradePartnerName"
                       :value="item.tradePartnerName"/>
          </el-select>
        </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 SearchBox from '@/components/SearchBox.vue'
import ButtonBar from '@/components/ButtonBar.vue'
import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance
} from 'vue'
import style from '@/tools/style'
import {ElMessage, ElMessageBox} from "element-plus";
import {watch, watchEffect} from 'vue';

onMounted(() => {
  queryType()
  queryGS()
  handleSearch()
})
const ruleFormRef = ref()

var userName = localStorage.getItem('userDesc')
const {proxy} = getCurrentInstance()
const cardBodyStyle = ref(style.card)
const dialogVisible = ref(false)
const tableData = ref([])
const query = ref({
  leibiemc: '',
  id: '',
  chuangjiansj: '',
  gonghuodw: '',

})

const query_JLXX = ref({
  leibiemc: '',
  gonghuodw: '',
  contractNo: '',
  zupibh: '',
})

const form = ref({
  leibiemc: '',
  smpType: '',
  leibieid: '',
  gonghuodw: '',
  gonghuodwid: '',
  contractNo: '',
  shouhuodw: '',
  shouhuodwid: '',
})

const openDialog = () => {
  // 初始化数据
  if (form.value.smpType) {
    handleChangeYCG();
  }
  if (form.value.leibiemc) {
    getJiHuahao(form.value.leibiemc)
  }
}
const YCGList = ref([])
const smpType = ref('')
const handleChangeYCG = () => {
  if (!form.value.smpType) {
    return
  }
  console.log(form.value.smpType, 'form.smpType')
  var url = 'sci/platform/getYCG'
  var param = {
    smpType: form.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 jihuahaos = ref([])
const getJiHuahao = (value) => {
  let itemCd = ''
  typeList.value.forEach(x => {
    if (x.itemNm == value) {
      itemCd = x.itemCd
    }
  })
  console.log(itemCd, '物料编码')
  var url = 'sci/platform/getJiHuahao'
  var param = {
    itemCd
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      console.log(response.data)
      jihuahaos.value = response.data.data
      console.log(jihuahaos.value, '计划号')
      if (jihuahaos.value.length == 0) {
        ElMessage.error('该物料没有计划号')
      }
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}


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
      console.log(form.value.leibieid, 'leibieid')
      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(data.value, 'data.value')
  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/Weituogl/saveWeituo'
      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()
          handleReSearch()
          dialogVisible.value = false
        } else {
          // ElMessage.error('操作失败！' + response.data.msg)
          ElMessage({
            message: '操作失败' + response.data.msg,
            type: 'error'
          })
          handleReSearch()
        }
      })

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

// 删除
const handleDelete = (row) => {

  ElMessageBox.confirm(
      '确定删除本条记录?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )
      .then(() => {
        var userName = localStorage.getItem('userDesc')
        var url = 'sci/Weituogl/removeWeituo'
        var param = {
          id: row.id,
          userName
        }
        proxy.$axios.post(url, param).then(response => {
          if (response.data.code == 0) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            getTableData()
            handleReSearch()
          } else {
            ElMessage({
              type: 'error',
              message: '删除失败' + response.data.msg
            });
            getTableData()
            handleReSearch()

          }
        });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })
}


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

const title = ref()
//编辑
const handleEdit = (row) => {
  title.value = '编辑'
  dialogVisible.value = true
  form.value = row
}


// 查询所有公司
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 handleSearch = () => {
  currentPage.value = 1
  tableData_JLXX.value = []
  getTableData()
}


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



// ==========================查询数据=========================
const getTableData = () => {
  var url = 'sci/Weituogl/queryAll'
  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)
      totalRows.value = response.data.data.total
      if (clickRowValue.value) {
        console.log(clickRowValue.value)
        tableData.value.forEach(x => {
          if (x.id == clickRowValue.value.id) {
            clickRowValue.value = x
          }
        })

        console.log(clickRowValue.value)
      }
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
};


const clickRowValue = ref({})
// 点击一行需要查询计量信息
const handleChange = (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.zupibh = row.zupibh

  var url = 'sci/JkJlxx/queryJk'
  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)
      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, 100])
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([10, 20, 30, 40, 100, 200])
const pageSize_JLXX = ref(10)
const handleSizeChange_JLXX = (val) => {
  pageSize_JLXX.value = val
  getTableData_JLXX(clickRowValue.value)
}
const handleCurrentChange_JLXX = (val) => {
  currentPage_JLXX.value = val
  getTableData_JLXX(clickRowValue.value)
}


/**
 * 用于单击table行后,复选框被选中
 */
// 表格的实例引用，用于操作表格


</script>

<style scoped></style>