<template>
  <div class="py-1.5 flex items-center" :class="bgColor">
    <div class="input-wrapper flex-1 relative">
      <app-icon
        icon-name="search-light"
        class-name="w-6 h-6 absolute left-2 top-1/2 transform -translate-y-1/2"
      />
      <form action=".">
        <input
          ref="c-search-input"
          type="search"
          class="py-2 rounded-full w-full pl-9"
          :class="getInputClass"
          :placeholder="placeholder"
          :value="value"
          @input="handleInput"
          @keypress="keyPress"
        >
        <input type="text" style="display:none;"/>
      </form>
      <div
        v-if="clearable && value && value.length > 0"
        class="clear absolute right-0 top-1/2 transform -translate-y-1/2 px-3.5 py-3.5 flex items-center justify-center"
        @click="clear"
      >
        <app-icon
          icon-name="close-small"
          class-name="w-2.5 h-2.5"
        />
      </div>
    </div>
    <div class="right flex-shrink-0 ml-4" v-if="showCancel">
      <slot name='action'>
        <div @click="$emit('cancel')">取消</div>
      </slot>
    </div>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'

export default Vue.extend({
  name: 'SearchBar',
  components:{ 
    'app-icon':()=>import('@/components/common/Icon.vue')
    // 'main-page': () => import('@/layout/main-page.vue')
  },
  props: {
    clearable: {
      type: Boolean,
      default: true
    },
    bgColor: {
      type: String,
      default: 'bg-common-bg'
    },
    placeholder: {
      type: String,
      default: '请输入..'
    },
    value: String,
    showCancel: {
      type: Boolean,
      default: true
    },
    inputClass: String
  },
  data() {
    return  {
      // value: '',
      length: 0,
      showError: false
    }
  },
  computed: {
    getInputClass() {
      return `${this.inputClass || ''} ${this.clearable ? 'pr-9' : 'pr-4'}`
    }
  },
  mounted() {
    (this.$refs['c-search-input'] as HTMLInputElement).focus()
  },
  methods: {
    handleInput(e: InputEvent) {
      this.$emit('input', (e.target as HTMLInputElement).value)
    },
    clear() {
      (this.$refs['c-search-input'] as HTMLInputElement).focus()
      this.$emit('input', '')
      
    },
    keyPress(e: KeyboardEvent) {
      if (e.key.toLowerCase() === 'enter') {
        this.$emit('search')
      }
      // alert(e.key)
    }
  }
})
</script>

<style lang="less">

</style>
