<template>
  <div v-loading="isLoading">
    <el-table :data="list" ref="goodsTable" style="width: 100%" @selection-change="chooseGoods">
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="goodsName" label="名称" show-overflow-tooltip/>
      <el-table-column prop="goodsFactory" label="厂家" show-overflow-tooltip/>
      <el-table-column prop="modelNumber" label="型号" show-overflow-tooltip/>
      <el-table-column prop="units" label="单位" show-overflow-tooltip/>
      <el-table-column prop="quantity" label="数量" show-overflow-tooltip/>
    </el-table>
    <div class="choose-good-page">
      <el-pagination
        :page-sizes="[10, 20, 30, 50]"
        :page-size="size"
        :total="total"
        :current-page="page"
        layout="slot, total, sizes, prev, pager, next, jumper"
        background
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getGoodsList } from '@/api/myTrade/purchaseContractManagement/purchaseContractManagement'

export default {
  name: 'BuyGoogsList',
  data() {
    return {
      list: [],
      page: 1,
      size: 10,
      total: 0,
      isLoading: false,
      selectedInfos: []
    }
  },
  props: ["info"],
  mounted() {
    this.selectedInfos = JSON.parse(JSON.stringify(this.info.list))
    this.fetchData()
  },
  methods: {
    // 获取货物信息列表
    fetchData() {
      this.isLoading = true
      getGoodsList({ businessNumber: this.info.businessNumber, page: this.page, rows: this.size }).then(({ data: { rows, records } }) => {
        this.list = rows || []
        this.total = records
        this.$nextTick(() => {
          this.list.forEach(item => {
            if(this.selectedInfos.some(i => i.id == item.id)) {
              this.$refs.goodsTable.toggleRowSelection(item)
            }
          })
          this.isLoading = false
        })
      })
    },
    handleCurrentChange(val) {
      this.page = val
      this.fetchData()
    },
    handleSizeChange(val) {
      this.size = val
      this.page = 1
      this.fetchData()
    },
    chooseGoods(val) {
      if(this.isLoading) return
      this.list.forEach(item => {
        if(val.some(i => i.id == item.id)) {
          if(!this.selectedInfos.some(i => i.id == item.id)) {
            this.selectedInfos.push(item)
          }
        } else {
          if(this.selectedInfos.some(i => i.id == item.id)) {
            this.selectedInfos.splice(this.selectedInfos.findIndex(i => i.id == item.id), 1)
          }
        }
      })
    }
  }
}
</script>

<style lang="scss">
.choose-good-page {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding-bottom: 10px;
}
</style>