<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.chehao" clearable style="width: 220px">
                <el-option label="未组批" value="N"></el-option>
                <el-option label="已组批" value="Y"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="收货单位">
              <el-select v-model="query.shouhuodw" 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>

    <ButtonBar area="top" @search="handleSearch" @jiepi="handleJiePi" @cancel="handleCancel"></ButtonBar>
    <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 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="id" label="委托编号" width="150" 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="zupibh" label="组批编号" width="150" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column v-if="true" prop="zpEndTime" label="结批时间" width="175" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="startTime" label="结算开始时间" width="175" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="endTime" label="结算截止时间" width="175" 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="200" 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>
    </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>
  <div>
    <ButtonBar area="bottom" @edit="handleAdd" @remove="handleRemoveBatch"></ButtonBar>
    <el-card :body-style="cardBodyStyle">
      <el-table @row-click="handleRowClick2" :data="tableData_JLXX" border highlight-current-row height="250"
                @selection-change="handleSelectionChange_JLXX" ref="tableRef2">
        <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_JLXX - 1) * pageSize + 1 }}</span>
          </template>
        </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="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>
  </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()
})

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

})

const query_JLXX = ref({
  leibiemc: '',
  gonghuodw: '',
  contractNo: '',
  zupibh: '',
  chehao: 'N',
  startTime:'',
  endTime:''
})


// 查询所有公司
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 handleJiePi = () => {

  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要结批的数据!'
    })
    return
  }
  var url = 'sci/Weituogl/jiepi'
  var ids = []
  multipleSelection.value.forEach((item, index) => {
    ids.push(item.id)
  })
  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()
    } else {
      ElMessage({
        type: 'error',
        message: '操作失败!' + response.data.msg
      });
      getTableData()
    }
  })
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  tableData_JLXX.value = []
  getTableData()
}
// 取消结批
const handleCancel = () => {

  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要取消结批的数据!'
    })
    return
  }
  var url = 'sci/Weituogl/cancel_jiepi'
  var ids = []
  let dept = localStorage.getItem('dept')
  dept = JSON.parse(dept)
  let deptCode = dept[0].deptCode
  multipleSelection.value.forEach((item, index) => {
    ids.push(item.id)
  })
  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()
    } else {
      ElMessage({
        type: 'error',
        message: '操作失败!' + response.data.msg
      });
    }
  })
}

const multipleSelection = ref([])
const multipleSelection_JLXX = ref([])
// 勾选一行
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  console.log(val)
}
const handleSelectionChange_JLXX = (val) => {
  multipleSelection_JLXX.value = val
  console.log(multipleSelection_JLXX.value)
}
// 删除组批
const handleRemoveBatch = () => {
  if (clickRowValue.value.zpEndFlag == 'Y') {
    ElMessage({
      type: 'warning',
      message: '已结批，不能进行操作!'
    })
    return
  }
  console.log(clickRowValue.value)
  if (multipleSelection_JLXX.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据!'
    })
    return
  }

  ElMessageBox.confirm('此操作将删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    var ids = []
    multipleSelection_JLXX.value.forEach((item, index) => {
      ids.push(item.id)
    })
    let dept = localStorage.getItem('dept')
    dept = JSON.parse(dept)
    let deptCode = dept[0].deptCode
    var url = 'sci/JkJlxx/removeBatch'
    var param = {
      ids: JSON.stringify(ids),
      json: JSON.stringify(clickRowValue.value),
      userName: userName,
      deptCode
    }
    proxy.$axios.post(url, param).then(response => {
      if (response.data.code == '0') {
        ElMessage({
          type: 'success',
          message: '操作成功!',
        });
        getTableData_JLXX(clickRowValue.value)
        getTableData()
        dialogVisible.value = false
      } else {
        ElMessage({
          type: 'error',
          message: '操作失败!' + response.data.msg
        });
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}


// 组批按钮
const handleAdd = () => {
  if (clickRowValue.value.zpEndFlag == 'Y') {
    ElMessage({
      type: 'warning',
      message: '已结批，不能进行操作!'
    })
    return
  }
  if (multipleSelection_JLXX.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要组批的数据!'
    })
    return
  }
  var ids = []
  multipleSelection_JLXX.value.forEach((item, index) => {
    console.log(item.id)
    ids.push(item.id)
  })
  var url = 'sci/JkJlxx/zupi'
  let dept = localStorage.getItem('dept')
  dept = JSON.parse(dept)
  let deptCode = dept[0].deptCode
  var param = {
    json: JSON.stringify(clickRowValue.value),
    ids: JSON.stringify(ids),
    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_JLXX(clickRowValue.value)
      tableData_JLXX.value = []
      getTableData()
      // dialogVisible.value = false
    } else {
      // ElMessage.error('操作失败！' + response.data.msg)
      ElMessage({
        message: '操作失败' + response.data.msg,
        type: 'error'
      })
    }
  })

}
// ==========================查询数据=========================
const getTableData = () => {
  var url = 'sci/Weituogl/queryC'
  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(response.data.data.records[0])
      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 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.shouhuodw = row.shouhuodw
  query_JLXX.value.shouhuodwid = row.shouhuodwid
  query_JLXX.value.zupibh = row.zupibh
  query_JLXX.value.cheshu = row.cheshu
  query_JLXX.value.startTime = row.startTime
  query_JLXX.value.endTime = row.endTime
  var url = 'sci/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)
      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([100,200])
const pageSize_JLXX = ref(200)
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行后,复选框被选中
 */
// 表格的实例引用，用于操作表格

const tableRef2 = ref(null);

// 点击行时执行的操作
const handleRowClick2 = (row) => {
  tableRef2.value.toggleRowSelection(row);
};
</script>

<style scoped></style>