<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-form :inline="true">
        <el-row :span="24">

          <el-col :span="5">
            <el-form-item label="原材料" style="margin-bottom: 5px;width: 220px;" prop="name">
              <el-select v-model="query.leibmc" placeholder="" filterable clearable>
                <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="留样编号" prop="">
              <el-input v-model="query.lybm" placeholder="请输入留样编号" clearable style="width: 200px;">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item prop="" label="出入库时间">
              <el-date-picker v-model="query.time" type="datetimerange" align="right"
                              unlink-panels range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
                              style="width: 350px;" 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-button type="success" plain @click="handleRK">入库</el-button>
      <el-button type="success" plain @click="handleCK">出库</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 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 prop="wtid" label="委托编号" align="center" width="200">
        </el-table-column>
        <el-table-column prop="lybm" label="留样编号" width="200px" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="leibmc" label="物料名称" width="300px" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="bcqx" label="保存期限(月)" width="200px" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="rkrname" label="入库人" width="200px" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="rksj" label="入库时间" width="200px" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="ckrname" label="出库人" width="200px" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="cksj" label="出库时间" width="200px" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="bcqx" label="保存期限" width="200px" header-align="center" align="center"
                         show-overflow-tooltip fixed="right">
          <template #default="scope">
            <el-tag
                :type="scope.row.isExpired === '已到期' ? 'success' : 'danger'"
                :plain="true"
                size="small">
              {{ scope.row.isExpired }}
            </el-tag>
          </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>


</template>

<script setup>
import {useRoute} from 'vue-router';
import SearchBox from "@/components/SearchBox.vue";
import ButtonBar from '@/components/ButtonBar.vue'
import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance,
  watch
} from 'vue'
import style from '@/tools/style'
import {ElMessage, ElMessageBox} from "element-plus";
import Templates from "@/views/system/templates.vue";
import dayjs from "dayjs";

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

const {proxy} = getCurrentInstance()
const dialogVisible = ref(false)
const ruleFormRef = ref()
const cardBodyStyle = ref(style.card)
const searchBarRef = ref(null)

//查询表单
const query = ref({
  leibmc: '',
  lybm: '',
  time: '',
})

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

// 上方数据
const tableData = ref([])
const totalRows = ref(0)

const multipleSelection = ref([])

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const LYBcqx = ref([])

// 入库
const handleRK = () => {
  if (!query.value.lybm) {
    ElMessage({
      type: 'warning',
      message: '请输入留样编号!'

    })
    return
  }
  var url = 'sci/LYGL/ruku'
  var param = {
    json: JSON.stringify(query.value),
    userName: userName,
    deptCode: deptCode
  }
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0') {
      ElMessage({
        type: 'success',
        message: '操作成功!',
      });
      query.value.lybm=''
      getTableData()
      getLYBcqx()
    } else {
      ElMessage({
        type: 'error',
        message: '操作失败!' + response.data.msg
      });
    }
  })
}

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

// 查询
const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}


// 查询产品类型
const typeList = ref([])
const queryType = () => {
  var url = 'syi/wuliao/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 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 userName = localStorage.getItem('userDesc')
// 上方数据查询
const getTableData = () => {

  var url = 'sci/LYGL/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
      totalRows.value = response.data.data.total
      // 调用处理逻辑
      processTableData();
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

const getLYBcqx = () => {
  var url = 'syi/YPLX/queryBcqx'
  var param = {}
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0') {
      LYBcqx.value = response.data.data
    } else {
      ElMessage({
        type: 'error',
        message: '操作失败!' + response.data.msg
      });
    }
  })
}


// 比较tableData和LYBcqx，并判断出库时间
const processTableData = () => {
  if (!tableData.value || !LYBcqx.value) return;

  tableData.value.forEach(item => {
    const matchingBcqx = LYBcqx.value.find(bc => bc.leibmc === item.leibmc);

    if (matchingBcqx) {
      // 使用dayjs计算保存期限加上入库时间后的出库时间
      const expirationDate = dayjs(item.rksj).add(matchingBcqx.bcqx, 'month');

      item.chukuTime = expirationDate.format('YYYY-MM-DD'); // 设置出库时间

      // 判断是否已到出库时间
      item.isExpired = expirationDate.isBefore(dayjs()) ? '已到期' : '未到期';
    }
  });
};


</script>

<style scoped></style>
