<template>
  <el-select
    v-model="index"
    filterable
    clearable
    remote
    reserve-keyword
    placeholder="请输入关键词"
    :remote-method="remoteMethod"
    :loading="loading"
  >
    <el-option
      v-for="(item, index) in list"
      :key="item.id"
      :label="item.companyZh"
      :value="index"
    />
  </el-select>
</template>
<script>
import { getSupplier, getSupplierPage } from '@/api/supplier'

export default {
  props: {
    companyType: [String, Number],
    value: [String, Number]
  },
  data() {
    return {
      index: null,
      list: [],
      loading: false
    }
  },
  watch: {
    index(val) {
      this.$emit('input', val !== null ? this.list[val].id : null)
      this.$emit('change', val !== null ? this.list[val] : null)
    },
    value(val) {
      this.init()
    }
  },
  created() {
    this.remoteMethod('')
    this.init()
  },
  methods: {
    init() {
      if (!this.value) return
      const index = this.list.findIndex(item => item.id == this.value)
      if (index < 0) {
        getSupplier({id: this.value}).then(res => {
          this.list.unshift(res.data)
          this.index = 0
        })
      } else this.index = index
    },
    remoteMethod(keyword) {
      const params = {
        rows: 500,
        companyType: this.companyType
      }
      params.keyword = keyword
      this.loading = true
      getSupplierPage(params)
        .then(res => this.list = res.data.list)
        .finally(() => this.loading = false)
    }
  }
}
</script>
