<template>
  <!--带搜索功能的下拉框-->
  <q-select filled stack-label :option-value="optionValue" :option-label="optionLabel" v-model="vdata_model" :ref="id"
    :options="newData" :label="label" :class="classStr" :dense='densetype' :reactive-rules='reactiveRules' emit-value
    map-options clearable :use-input="useInput" @input="resetSearch" @filter="filterFn">
    <template v-slot:no-option>
      <q-item>
        <q-item-section class="text-grey">
          未找到相关数据
        </q-item-section>
      </q-item>
    </template>
  </q-select>
</template>
<script>
  export default {
    name: "select-search",
    props: {
      //样式字符串
      classStr: {
        type: String,
        default: ''
      },
      //选中数据
      vModel: {
        type: Number,
        default: ''
      },
      //下拉的数据
      Data: {
        type: Array,
        default: []
      },
      //是否紧凑
      densetype: {
        type: Boolean,
        default: false
      },
      //是否能输入
      useInput: {
        type: Boolean,
        default: false
      },
      //是否验证
      reactiveRules: {
        type: Boolean,
        default: false
      },
      //选项的值
      optionValue: {
        type: String,
        default: ''
      },
      //选项的标签
      optionLabel: {
        type: String,
        default: ''
      },
      //名称
      label: {
        type: String,
        default: ''
      },
 
    },
    data() {
      return {
        id: 'select-search' + (Math.floor((Math.random() * 10000) + 1)),
        vdata_model: 0,
        newData: []
      }
    },
    //监听数据变化
    watch: {
      //有默认值
      Data: {
        handler(newValue) {
          this.newData = JSON.parse(JSON.stringify(this.Data));
        },
        immediate: true
      },
      //值改变
      vModel: {
        handler(newValue) {
          this.vdata_model = this.vModel;
        },
        immediate: true
      },
    },
    created() {

    },
    methods: {
      resetSearch() {
        let data = this.vdata_model != null ? this.vdata_model : 0;
        this.$emit('returnData', data);
      },
      //搜索方法
      filterFn(val, update) {
        update(() => {
          let Name = this.optionLabel
          if (val === '') {
            this.newData = JSON.parse(JSON.stringify(this.Data));
          } else {
            const needle = val.toLowerCase();
            let that = this;
            that.newData = [];
            that.newData = that.Data.filter(v => v[Name].indexOf(needle) > -1);
          }
        })
      },
    }
  }

</script>
<style scoped>

</style>
