<template>
  <div>
    <a-select v-model="selected" placeholder="输入学科代码名称" :default-active-first-option="false" showSearch 
    :show-arrow="false" :filter-option="false" @search="onSearch" @change="handleChange" :style="{width: width + 'px'}" allowClear>
      <a-select-option v-for="item in selectArray" :key="item.key" :value="item.key"> 
        {{ item.title }}
      </a-select-option>
    </a-select>
  </div>
</template>
<!-- :filterOption="filterOption" -->
<script>
export default {
  name: "knowledgeSelect",
  props: {
    value: {
      type: undefined,
      default () {
        return null
      }
    },
    width: {
      type: Number,
      default() {
        return 180;
      },
    },
  },
  data() {
    return {
      selectArray: [],
      selected: null,
      defaultValue: {
        title: "--请选择" + this.title + "--",
        key: "",
        description: "",
        selected: true,
        disabled: true,
      }
    };
  },
  created() {
    if (this.value)
      this.selected = this.value
  },
  methods: {
    onSearch(value) {
      if (value == '') {
        return
      }
      let pars = { SystemCodeOrName: value }
      this.$api.parameter.getParameterListBySystemCode(pars).then(({ data = {} }) => {
        this.selectArray = []
        // 模拟从数据库查询数据
        if (data && data.length > 0) {
          this.selectArray = data
        }
        // else {
        //   this.selectArray.push({ title: value, key: "00000000-0000-0000-0000-000000000000" })
        // }
      })
    },
    // filterOption(input, option) {
    //   // 自定义过滤逻辑,如果没有匹配的选项就保留输入值
    //   return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    // },
    handleChange(value) {
      this.$emit("input", value);
      var newArr = this.selectArray.filter(x => x.key == value);
      if (value && !!newArr && newArr.length > 0) {
        var text = !!value ? newArr[0].title : ''
        this.$emit('changeTitle', text)
      }
      this.$emit("change");
    },
    loadValue () {
      if (this.isAll) {
        this.selectArray.unshift(this.defaultValue)
      }
      if (!!!this.selected) {
        if (!!this.value) {
          this.selected = this.value + ''
        } else {
          if (this.selectArray.length > 0)
            this.selected = this.selectArray[0].key
          else
            this.selected = ''
        }
      }
      this.$emit("input", this.selected)
    },
    reset() {
      this.selected = undefined
      this.selectArray = []
      this.$nextTick(() => {
        this.$emit('input', undefined)
        this.$emit('change')
      })
    }
  },
  watch: {
    value: {
      handler (value) {
        if (!value) {
          this.selected = undefined
          this.selectArray = []
        } else {
          this.selected = value + ''
        }
        this.$emit("input", this.selected)
      },
      immediate: true
    },
  }
};
</script>