<!-- 供应商列表 -->
<template>
    <div>
      <el-select
        v-model="value"
        ref="select"
        placeholder="请选择"
        clearable
        filterable
        remote
        :remote-method="remoteMethod"
        @change = "onChange"
        @focus="cancelReadOnly"
        @hook:mounted="cancelReadOnly"
        @visible-change="cancelReadOnly">
        <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: 'supplier-component',
    props: {
      supplierId: {
        type: String,
        default: ''
      }
    },
    model: {
      prop: 'supplierId',
      event: 'supplierSelected'
    },
    data () {
      return {
        value: '',
        current: 1,
        size: 10,
        name: '',
        options: [],
        loading: false,
        noMore: false
      }
    },
    mounted () {
      this.init()
    },
    watch: {
      supplierId (value) {
        this.value = value
      }
    },
    methods: {
      async init () {
        this.getList()
      },
      remoteMethod (query) {
        this.options = []
        this.current = 1
        this.name = query
        this.getList()
      },
      getList () {
        this.$http({
          url: this.$http.adornUrl(`/biz-service/supplier/list`),
          method: 'get',
          params: this.$http.adornParams({
            'current': this.current,
            'size': this.size,
            'supplierName': this.name,
            'supplierState': 1
          })
        }).then(({data}) => {
          if (data && data.code === '200') {
            if (this.current > data.data.pages) {
              return
            }
            data.data.records.forEach(item => {
              this.options.push({
                label: item.supplierName,
                value: item.supplierId
              })
            })
          } else {
            this.options = []
          }
        })
      },
      handleClick () {
        this.loadMore()
      },
      loadMore () {
        this.current ++
        this.getList()
      },
      onChange (item) {
        if (item === 'undefined') {
          this.value = null
        }
        this.$emit('supplierSelected', item)
      },
      cancelReadOnly (onOff) {
        this.$nextTick(() => {
          if (!onOff) {
            const input = this.$refs.select.$el.querySelector('.el-input__inner')
            const timer = setTimeout(() => {
              input.removeAttribute('readonly')
              clearTimeout(timer)
            }, 200)
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>
