<template>
  <div class="search-bar">
    <form action @submit.prevent="onSearch">
      <div class="inner">
        <input
          type="search"
          class="search-input"
          :placeholder="placeholder"
          v-model="currentValue"
          v-bind="$attrs"
          @input="onChange"
          ref="formInput"
        />
        <input type="button" value="搜索" class="search-button" @click="onSearch" />
      </div>
    </form>
  </div>
</template>

<script>
export default {
  props: {
    value: String,
    focus: { type: Boolean, default: false },
    placeholder: { type: String, default: '全国道路运输安全生产管理培训' }
  },
  data() {
    return {
      currentValue: this.value,
      debounced: null
    }
  },
  watch: {
    value(value) {
      this.currentValue = value
    }
  },
  computed: {
    formInput() {
      return this.$refs.formInput
    }
  },
  methods: {
    bindFocus() {
      this.focus && this.formInput.focus()
    },
    onChange() {
      this.$emit('input', this.currentValue)
      this.$emit('change', this.currentValue)
    },
    onSearch() {
      this.$emit('search', this.currentValue)
    }
  },
  mounted() {
    this.bindFocus()
  }
}
</script>

<style lang="scss">
.search-bar {
  padding: 0.4rem 0;
}
.search-input {
  display: block;
  width: 100%;
  padding: 0.2rem 0.2rem 0.2rem 0.9rem;
  height: 0.66rem;
  font-size: 0.26rem;
  line-height: 0.26rem;
  background: #f7f7f7 url('~@/assets/images/icon_search.png') no-repeat 0.4rem
    center;
  background-size: 0.31rem;
  border: 0;
  border-radius: 0.1rem;
  outline: none;
}
.search-button {
  margin-left: 0.2rem;
  color: #222;
  font-size: 0.3rem;
  appearance: none;
  background-color: transparent;
}
.inner {
  display: flex;
}
</style>
