<template>
  <div>
    <el-select
      v-model="value"
      ref="select"
      placeholder="请选择存放仓库"
      filterable
      remote
      :remote-method="remoteMethod"
      @change = "onChange">
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value">
      </el-option>
      <el-option v-if="options.length > 0" label="加载更多" style="font-style: italic; color: #8a979e" value="undefined" @click.native="handleClick()"></el-option>
    </el-select>
  </div>
</template>

<script>
  export default {
    name: 'warehouse-select',
    props: ['warehouseId'],
    model: {
      prop: 'warehouseId',
      event: 'select'
    },
    data () {
      return {
        value: '',
        current: 1,
        size: 10,
        warehouseName: '',
        options: [],
        loading: false,
        noMore: false
      }
    },
    mounted () {
      this.init(this.warehouseId)
    },
    watch: {
      warehouseId (newVal) {
        this.init(newVal)
      }
    },
    methods: {
      async init (id) {
        this.current = 1
        this.options = []
        this.getList(id)
      },
      remoteMethod (query) {
        this.options = []
        this.current = 1
        this.warehouseName = query
        this.getList()
      },
      getList (id) {
        this.$http({
          url: this.$http.adornUrl(`/biz-service/stock-mg-ctl/listWarehouses`),
          method: 'get',
          params: this.$http.adornParams({
            'current': this.current,
            'size': this.size,
            'warehouseName': this.warehouseName
          })
        }).then(({data}) => {
          if (data && data.code === '200') {
            if (this.current > data.data.pages) {
              return
            }
            data.data.records.forEach(item => {
              let idx = this.options.findIndex(i => i.value === item.warehouseId)
              if (idx < 0) {
                this.options.push({
                  label: item.warehouseName,
                  value: item.warehouseId
                })
              }
            })
            if (id) {
              this.value = id
            }
          } else {
            this.options = []
          }
        })
      },
      handleClick () {
        this.loadMore()
      },
      loadMore () {
        this.current ++
        this.getList()
      },
      onChange (item) {
        if (item === 'undefined') {
          this.value = null
        }
        this.$emit('select', item)
      }
    }
  }
</script>

<style scoped>

</style>
