<template>
  <div class="SearchPanel" @click="resetSearch">
    <cr-search
      ref="searchInput"
      v-model.trim="keyWords"
      shape="round"
      left-icon="search"
      placeholder="搜索你想要的宝贝"
      @search="searchEnterEvent"
      @clear="clearInputText"
    />
    <cr-tag
      v-if="isSearch"
      size="medium"
      color="#999"
      shape="round"
      closable
      @close="resetSearch"
      >{{ keyWords }}</cr-tag
    >
  </div>
</template>
<script>
const SEARCH_EVENT = 'enter';
const CLEAR_EVENT = 'clear';
export default {
  props: {
    isSearch: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      keyWords: ''
    };
  },
  watch: {
    keyWords(val) {
      if (val) this.$track.registeredEvents('H5_2B_CommodityListPageExposure');
    }
  },
  methods: {
    clearInputText() {
      this.keyWords = '';
    },
    resetSearch() {
      this.clearInputText();
      this.$emit(CLEAR_EVENT);
    },
    searchEnterEvent() {
      if (!this.keyWords) {
        return this.$dialog({
          message: '请输入内容',
          showCancelButton: false
        });
      }
      this.$refs.searchInput.$el.querySelector('input').blur();
      this.$emit(SEARCH_EVENT, this.keyWords);
    }
  }
};
</script>

<style lang="less" scoped>
.SearchPanel {
  @{deep} .cr-icon--cross {
    position: absolute;
    right: 5px;
    top: 5px;
  }
  @{deep} .cr-search {
    padding: @padding-sm @padding-sm + 4;
    .cr-icon--search {
      .text-size(16);
      color: #999;
    }
  }
  position: relative;
  .cr-tag {
    padding-left: 10px;
    padding-right: 20px;
    position: absolute;
    top: @padding-sm + 3;
    left: 45px;
    max-width: 84%;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    box-sizing: border-box;
    -webkit-box-orient: vertical;
    word-break: break-all;
  }
}
</style>
