<template>
  <a-select :value="selected" placeholder="请输入单位名称查找单位" style="width:250px" :default-active-first-option="false" :filter-option="false" :not-found-content="null" @search="handleSearch" @change="handleChange" showSearch allowClear>
    <a-select-option v-for="d in data" :key="d.key">
      {{ d.title }}
    </a-select-option>
  </a-select>
</template>

<script>
let timeout;
function fetch (value, arr, callback) {
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  function fake () {
    let data = []
    let list = arr.filter(item => item.title.indexOf(value) != -1)
    if (list.length > 30) {
      let len = list.length > 30 ? 30 : list.length
      for (let i = 0; i < len; i++) {
        data.push(list[i])
      }
    } else
      data = list
    callback(data);
  }
  timeout = setTimeout(fake, 100);
}

export default {
  name: "unitSelect",
  data () {
    return {
      data: [],
      list: [],
      selected: null,
      state: false,
      unitType: 1
    };
  },
  props: {
    value: {
      type: String,
      default: () => {
        return ''
      }
    },
    typeId: {
      type: Number,
      default: () => {
        return null
      }
    },
  },
  created () {
    this.load(this.value)
  },
  methods: {
    load (value) {
      if (!!this.typeId) {
        this.unitType = this.typeId
      }
      if (this.list.length > 0) {
        if (value)
          this.loadSelected(value)
      }
      else {
        this.$api.unit.getIdListByType({ unitType: this.unitType }).then(({ data = {} }) => {
          if (data) {
            this.list = data
            if (!value) {
              if (this.list.length > 30) {
                let len = this.list.length > 30 ? 30 : this.list.length
                for (let i = 0; i < len; i++) {
                  this.data.push(this.list[i])
                }
              } else
                this.data = this.list
            } else
              this.loadSelected(value)
          }
        }).catch(() => { })
      }
    },
    handleSearch (value) {
      fetch(value, this.list, data => (this.data = data));
    },
    handleChange (value) {
      this.selected = value;
      this.$emit("input", value);
      this.$emit("change");
    },
    loadSelected (value) {
      let data = this.list.filter(item => item.key === value)
      this.data = data
      this.selected = value
    },
  },
  watch: {
    value: {
      handler (value) {
        if (!this.state) {
          this.load(value)
          this.state = true
        }
      }
    },
  }
};
</script>
