<style scoped>
.searchBar-wrapper {
  position: relative;
  display: flex;
  height: 70px;
  margin: 0 40px;
  padding: 0 132px 0 40px;
  align-items: center;
  background: #F7F7F7;
  color: #666;
  font-size: 24px;
  border-radius: 40px;
}

.searchBar-wrapper input {
  flex-grow: 1;
}

.searchBar-icon-wrapper {
  display: flex;
  position: absolute;
  width: 80px;
  height: 70px;
  top: 50%;
  right: 38px;
  justify-content: center;
  align-items: center;
  transform: translateY(-50%);
}

.searchBar-wrapper img {
  display: block;
  width: 38px;
  height: 38px;
}
</style>

<template>
  <div class="searchBar-wrapper">
    <input v-model="value" :maxlength="maxLength" :placeholder="placeholder" type="text">
    <div @click="manualSearch" class="searchBar-icon-wrapper">
      <img :src="searchIcon || '/static/images/search.svg'" >
    </div>
  </div>
</template>

<script>
let autoSeachTimer

export default {
  /**
    * list：Array
    * searchKey：String（list 为 Object Array时指定显示的Key指）
    * placeholder：String
    * searchIcon：String
    * maxLength：String | Number
    * autoSearch：Boolean（是否在用户输入的时候进行模糊搜索)
    * autoSearchInterval：String | Number（自动搜索的间隔时间）
  */
  props: {
    list: {
      type: String,
      default: () => []
    },
    searchkey: {
      type: String,
      default: () => ''
    },
    placeholder: {
      type: String,
      default: () => ''
    },
    searchIcon: {
      type: String,
      default: () => ''
    },
    maxLength: {
      type: String | Number,
      default: () => 99
    },
    autoSearch: {
      type: Boolean,
      default: () => false
    },
    autoSearchInterval: {
      type: String | Number,
      default: () => 500
    }
  },
  data: () => {
    return {
      value: undefined
    }
  },
  mounted () {
  },
  methods: {
    // 点击搜索按钮的回调
    manualSearch () {
      this.$emit('getResult', this.list.filter(item => {
        return this.searchkey ? item[this.searchkey].indexOf(this.value) > -1 : item.indexOf(this.value) > -1
      }), 'manual')
    },
    // 自动搜索的回调
    autoSearchHandler (val) {
      if (autoSeachTimer) {
        clearTimeout(autoSeachTimer)
      }
      if (!val && typeof val !== 'number') {
        this.$emit('getResult', this.list, 'auto')
        clearTimeout(autoSeachTimer)
        return
      }
      autoSeachTimer = setTimeout(() => {
        this.$emit('getResult', this.list.filter(item => {
          return this.searchkey ? item[this.searchkey].indexOf(val) > -1 : item.indexOf(val) > -1
        }), 'auto')
      }, this.autoSearchInterval)
    }
  },
  watch: {
    value: {
      handler: function (cur, pre) {
        if (this.autoSearch) {
          this.autoSearchHandler(cur)
        }
      }
    }
  }
}
</script>

