<template>
  <p-card>
    <div slot="title" style="display: inline-block; align-items: center; cursor: pointer" @click="clickEvent('back')">
      <a-icon type="arrow-left" style="color: #1990ff" class="mr-10"/>
      指定库位
    </div>
    <div slot="extra">
      <!-- <a-button type="primary" @click="clickEvent('handleOkreplenishment')">指定库位</a-button> -->
      <a-button type="primary" @click="clickEvent('handleOkreplenishment')">保存</a-button>
      <a-button type="primary" @click="tableDelete" style="margin-left: 10px;">删除</a-button>

    </div>
    <p-grid-form ref="modelForm" :span="20" :label-col="{ span: 4 }" :items="items"
                 @submit.prevent="hchanlderSubmit"/>
    <div>
      <span style="font-weight: bold; margin:5px">商品未处理数量: {{ itemNum }}</span>
      <span style="font-weight: bold; margin:5px">指定数量: {{ itemNum - computedNum }}</span>
      <span style="font-weight: bold; margin:5px">剩余待指定数量: {{ computedNum }}</span>
    </div>
    <p-table-edit-pro
        ref="logTable"
        :rowSelectType="false"
        :row-selection="rowSelection"
        :columns="avlcolumns"
        :loading="loading"
        @colChange="colChange"
        :hasRepairDataSource="true"
        :rowKey="rowKey"
        :scroll="{ x: true }"
        :data-source="innerData"
    />
    <p-table
        :rowSelectType="2"
        :selectedRowKeys.sync="selectedRowKeys2"
        :columns="avlcolumnsQuery"
        :scroll="{ x: true }"
        :loading="loadingtable"
        :hasRepairDataSource="true"
        :data-source="queryData"
    />
  </p-card>
</template>

<script>
import {avlcolumns, items, avlcolumnsQuery} from '../js/detailspilt'
import {getavlpagelist, getbillDPrePosition} from '../api/index'
import {diffOption} from '@/views/kzyWMS/utils/index.js'

export default {
  name: '',
  components: {},
  props: {
    TS: {
        type: String,
        default: ''
    },
    num: {
      type: Number,
      default: 0
    },
    orderModifyData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      avlcolumns: null,
      items: items(this),
      avlcolumnsQuery,
      loading: false,
      loadingtable: false,
      queryData: [],
      rowKey: 'id',
      selectedRowKeys: [],
      selectedRows: [],
      innerData: [],
      itemNum: 0,
      computedNum: 0,
      selectedRowKeys2: []
    }
  },
  created() {
    diffOption(avlcolumns).then(res => {
      this.avlcolumns = res
    })
    console.log(this.orderModifyData,'========');
  },
  mounted() {
  },
  computed: {
    rowSelection() {
      let _this = this
      return {
        onSelectAll(selected, selectedRows, changeRows) {
          var checked = selected
          var key = changeRows.map(item => item.id)
        },
        onSelect(record, selected, selectedRows, nativeEvent) {
          var checked = selected
          console.log(record)
          if (checked) {
          } else {
          }
          var key = record.id
          console.log(selectedRows)
        },
        onChange(selectedRowKeys, selectedRows) {
          _this.selectedRowKeys = selectedRowKeys
          _this.selectedRows = selectedRows
        }
      }
    }
  },
  watch: {
    num: {
      handler(val) {
        this.itemNum = val
        this.computedNum = val
      },
      immediate: true
    },
    orderModifyData: {
        
      handler(val) {
        this.$nextTick(() => {
          console.log(this.$refs.modelForm.form)
          //   this.$refs.modelForm.form.enableItem()
          if (val.manufacturerLotNum) this.$refs.modelForm.form.disableItem('manufacturerLotNum')
          console.log(val);
          this.$refs.modelForm.form.setFieldsValue(val)
        })
        this.loading = true
        console.log(val,'===');
        getavlpagelist(val).then(res => {
          this.loading = false
          if (res.success && res.data.list.length > 0) {
            this.innerData = res.data.list.filter(i=>i.warehouseAreaCategory!='PDK')
            // this.innerData[0].availableQuantity = 3
            this.innerData.forEach(item => {
              item.qty = 0
            })
          } else {
            // this.$exception(res)
          }
        })
        getbillDPrePosition({billDId: val.billDId}).then(res => {
          if (res.success) {
            this.queryData = res.data
          } else {
            // this.$exception(res)
          }
        })
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
      tableDelete () {
        if (this.selectedRowKeys2.length) {
            let arr = [...this.queryData]
            let arr2 = []
            arr.forEach((item,index) => {
                this.selectedRowKeys2.forEach((item2,index2) => {
                if (item.id != item2) {
                    arr2.push(item)
                }
                })
            })
            this.queryData = [...arr2]
        }
      },
    hchanlderSubmit() {
      this.$refs.modelForm.form.validateFields((error, values) => {
        if (!error) {
          // const params = {
          //   warehouseId: this.orderModifyData.warehouseId,
          //   cargoOwnerId: this.orderModifyData.consignorId,
          //   itemId: this.orderModifyData.itemId,
          //   manufacturerLotNum: values.manufacturerLotNum
          // }
          const params = {
            ...this.orderModifyData,
            ...values
          }
          getavlpagelist(params).then(res => {
            // this.innerData = res.data.list
            if (res.success) {
                 this.innerData = res.data.list.filter(i=>i.warehouseAreaCategory!='PDK')
            } else {
              this.$exception(res)
            }
          })
        }
      })
    },
    queryReplenishment() {
      this.loadingtable = true
      getbillDPrePosition({billDId: this.orderModifyData.billDId}).then(res => {
        if (res.success) {
          this.queryData = res.data
          this.loadingtable = false
        } else {
          // this.$exception(res)
        }

      })
    },
    colChange(data) {
      console.log(data)
      this.computedNum = this.itemNum
      if (data.name == 'scatteredQty') {

          if (this.TS == 'TS' && this.orderModifyData.isCaseOrPiece === 1 && this.innerData[data.record._row_count - 1].completeQty > 0) {
              this.$message.error('整散不可同时录入')
              return
          }


        this.innerData[data.record._row_count - 1].scatteredQty = data.value
        this.innerData.forEach(item => {
          item.qty = Number(item.scatteredQty) + Number(item.completeQty) * Number(item.caseConversionRate)
          this.computedNum =
              this.computedNum - (Number(item.scatteredQty) + Number(item.completeQty) * Number(item.caseConversionRate))
        })
      }
      if (data.name == 'completeQty') {

          if (this.TS == 'TS' && this.orderModifyData.isCaseOrPiece === 1 && this.innerData[data.record._row_count - 1].scatteredQty > 0) {
              this.$message.error('整散不可同时录入')
              return
          }

        this.innerData[data.record._row_count - 1].completeQty = data.value
        this.innerData.forEach(item => {
          item.qty = Number(item.scatteredQty) + Number(item.completeQty) * Number(item.caseConversionRate)
          this.computedNum =
              this.computedNum - (Number(item.scatteredQty) + Number(item.completeQty) * Number(item.caseConversionRate))
        })
      }
    },
    chekTableData() {
      if (this.computedNum != 0) {
        this.$message.error('输入总数量必须等于商品数量')
        return true
      }
      let availableStatus = this.innerData.every(item => {
        let allNum = Number(item.scatteredQty) + Number(item.completeQty) * Number(item.caseConversionRate)
        return item.availableQuantity >= allNum
      })
      let Status = true
      this.innerData.forEach(item => {
        if (item.locatorType == 0 && item.scatteredQty > 0) {
          Status = false
        } else if (item.locatorType == 1 && item.completeQty > 0) {
          Status = false
        } else {
          //   let Status = true
        }
      })
      if (!Status) {
        this.$message.error('整件散件类型输入错误')
        return true
      }
      if (!availableStatus) {
        this.$message.error('输入数量不能超过可用库存数量')
        return true
      }
    },
    clickEvent(event) {
      this.$emit('clickEvent', event)
    }
  }
}
</script>

<style scoped lang="less">
.title-bold {

}
</style>
