<template>
  <div>
    <p-modal
      title="代管库位"
      :visible="visible"
      :dialogStyle="{ top: '40px' }"
      :draggable="true"
      :width="'70%'"
      :destroyOnClose="true"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <div class="box-wrapper">
        <p-table-edit
          ref="mainlist"
          :rowKey="'id'"
          :columns="nColumns"
          :autoLoad="false"
          :data-source.sync="dataList"
          :hasRowSelectCheck="true"
          :rowSelectType="2"
          @selectChange="selectChange"
          :scroll="{ y: 400 }"
        >
        </p-table-edit>
      </div>
    </p-modal>
  </div>
</template>

<script>
import { getHost, cols } from './config'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    hostData: {
      type: Object,
      default: null,
    },
    refList: {
      type: Array,
      default: null,
    },
  },

  model: {
    prop: 'visible',
    event: 'change',
  },

  watch: {
    visible: {
      handler(visible) {
        if (!visible) return
        this.$nextTick(() => {
          this.dataList = []
          this.initLineData()
        })
      },
    },
  },
  data() {
    return {
      nColumns: cols,
      dataList: [],
      selectedRows: [],
    }
  },

  methods: {
    initLineData() {
      let paramData = this.hostData
      const enterpriseId = this.$store.state.user.info.enterpriseId
      var itemList = JSON.parse(JSON.stringify(this.refList))
      var item = []
      var data = {
        num: 'item_instock_list',
        params: {
          itemId: paramData.itemId,
          cargoOwnerId: paramData.mtlOwnerId,
          warehouseId: paramData.warehouseId,
          enterpriseId: enterpriseId,
          status: 5,
        },
      }
      getHost(data).then((res) => {
        if (!res.success) {
          this.$exception(res)
          return
        }
        itemList.forEach((t) => {
          //遍历商品明细表数据
          //明细代管货位id是否为空
          // debugger
          if (!t.hostLocatorId == null || !t.hostLocatorId == '') {
            //再根据同批次id batchId 、货位 locatorId 扣除对应数量
            this.dataList = []
            item = []
            res.data.list.forEach((j) => {
              if (t.batchId == j.batchId && t.locatorId == j.locatorId) {
                j.availableQuantity -= t.pieceQty
              }
              if (j.availableQuantity != 0) {
                item.push(j)
              }
              return
            })
          } else {
            //筛选数量不为0的
            res.data.list.forEach((k) => {
              if (k.availableQuantity != 0) {
                item.push(k)
              }
              // this.$message.warning('当前暂无可用代管库位')
              return
            })
          }
          this.dataList = item
        })
      })
    },
    handleOk(e) {
      var rowData = this.hostData
      var itemList = JSON.parse(JSON.stringify(this.refList))
      var a = null
      this.selectedRows.forEach((t) => {
        a += t.availableQuantity
      })
      if (a >= rowData.pieceQty) {
        //根据当前商品明细行ref 找到对应明细行
        var item = itemList.find((t) => rowData.asnLineId == t.asnLineId) //商品明细行
        var ab = []
        var c1 = item
        var i = 0
        var t = this.selectedRows
        while (c1.pieceQty > 0) {
          //明细行大于货位数量
          let batchProductionDate = t[i].batchProductionDate.substring(0, 10)
          let batchExpiredDate = t[0].batchExpiredDate.substring(0, 10)
          if (c1.pieceQty - t[i].availableQuantity >= 0) {
            ab.push({
              ...c1,
              locatorCode: t[i].locatorCode,
              batchId: t[i].batchId,
              batchNum: t[i].batchNum,
              hostLocatorId: t[i].locatorId,
              locatorName: t[i].locatorName,
              pieceQty: t[i].availableQuantity,
              manufacturerLotNum: t[i].manufacturerLotNum,
              showProductionDate: t[i].batchExpiredDateShow,
              batchProductionDate: batchProductionDate,
              showExpiredDate: t[i].batchExpiredDateShow,
              batchExpiredDate: batchExpiredDate,
              rqcReportNo: t[i].rqcReportNo,
              tempQty: t[i].availableQuantity,
            })
          } else {
            ab.push({
              ...c1,
              locatorCode: t[i].locatorCode,
              batchId: t[i].batchId,
              batchNum: t[i].batchNum,
              hostLocatorId: t[i].locatorId,
              locatorName: t[i].locatorName,
              manufacturerLotNum: t[i].manufacturerLotNum,
              showProductionDate: t[i].batchExpiredDateShow,
              batchProductionDate: batchProductionDate,
              showExpiredDate: t[i].batchExpiredDateShow,
              batchExpiredDate: batchExpiredDate,
              rqcReportNo: t[i].rqcReportNo,
              tempQty: t[i].availableQuantity,
            })
            ab[i].asnLineId = ab[i].asnLineId + '_cus_' + Math.floor(Math.random() * 1000)
            ab[i].oddCaseQty = Math.floor(ab[i].pieceQty / ab[i].conversionRate)
            ab[i].oddPieceQty = ab[i].pieceQty % ab[i].conversionRate
            break
          }
          c1.pieceQty -= t[i].availableQuantity
          //生成id
          ab[i].asnLineId = ab[i].asnLineId + '_cus_' + Math.floor(Math.random() * 1000)
          //件数oddCaseQty (数量pieceQty/包装数conversionRate)
          ab[i].oddCaseQty = Math.floor(ab[i].pieceQty / ab[i].conversionRate)
          //零散数oddPieceQty (数量pieceQty%包装数conversionRate)
          ab[i].oddPieceQty = ab[i].pieceQty % ab[i].conversionRate
          i++
        }
        let index = item._row_count - 1
        this.refList.splice(index, 1, ...ab)
        this.$emit('change', false)
        return
      }
      this.$message.warning('当前所选数量总和小于任务总数，请重新选择或者进行损溢处理！')
    },
    handleCancel(e) {
      this.$emit('change', false)
    },
    selectChange(selectedRowKeys, selectedRows) {
      this.selectedRows = selectedRows
    },
  },
}
</script>

<style scoped>
.box-wrapper {
  margin-bottom: 20px;
  background: #fff;
}
.btn {
  color: #2b80ff;
  margin-right: 10px;
  cursor: pointer;
}
.btn:hover {
  text-decoration: underline;
}
</style>
