<template>
  <section>
    <section class="bx-search">
      <div
        :class="['bx-search-box', showAction ? 'bx-search-box--with-action' : '']"
        :style="`background:${background}`"
        >
        <p 
          class="bx-search-icon" 
          @click="search"
          >
          <bxs-icon 
            name="search" 
            size="18px"
            />
        </p>
        <p class="bx-search-form">
          <input
            :disabled="disabled"
            type="text"
            :placeholder="placeholder"
            v-model="vl"
            v-on="listeners"
            class="bx-search-input"
            >
        </p>
        <p 
          class="bx-search-clear" 
          v-if="!!vl" 
          @click="clear"
          >
          <bxs-icon 
            name="close-solid" 
            size="18px"
            />
        </p>
      </div>
      <div 
        v-if="showAction"
        class="bx-search-action"
        >
        <slot
          name="action"
          :addHistory="addHistory"
          >
          <div @click="cancel">
            取消
          </div>
        </slot>
      </div>
    </section>
    <div
      class="bx-search-suggestion-overlay"
      v-if="attachModuleShow"
      >
      <section class="bx-search">
        <div
          :class="['bx-search-box', showAction ? 'bx-search-box--with-action' : '']"
          :style="`background:${background}`"
          >
          <p 
            class="bx-search-icon" 
            @click="search"
            >
            <bxs-icon 
              name="search" 
              size="18px"
              />
          </p>
          <p class="bx-search-form">
            <input
              ref="attachModule"
              :disabled="disabled"
              type="text"
              :placeholder="placeholder"
              v-model="vl"
              v-on="listeners"
              class="bx-search-input"
              >
          </p>
          <p 
            class="bx-search-clear" 
            v-if="!!vl" 
            @click="clear"
            >
            <bxs-icon 
              name="close-solid" 
              size="18px"
              />
          </p>
        </div>
        <div 
          v-if="showAction" 
          class="bx-search-action"
          >
          <slot
            name="action"
            :addHistory="addHistory"
            >
            <div @click="cancel">
              取消
            </div>
          </slot>
        </div>
      </section>
      <div
        class="bx-search-block"
        v-if="historyList && historyList.length"
        >
        <p class="bx-search-block-title">
          搜索历史
        </p>
        <ul class="bx-search-history">
          <li
            class="bx-search-history-one"
            v-for="(item, index) in historyList"
            :key="index"
            >
            <bxs-icon name="clock" />
            <em
              class="bx-search-history-text"
              @click="goSearch(item)"
              >
              {{ item }}
            </em>
            <p
              class="bx-search-history-close"
              @click="clearHistory(index)"
              >
              <bxs-icon name="close" />
            </p>
          </li>
        </ul>
        <p
          class="bx-search-history-clear"
          @click="clearHistory()"
          >
          清除搜索历史
        </p>
      </div>
    </div>
  </section>
</template>
<script>
import { create } from '../utils'
import Icon from '../icon/index'

export default create({
  name: 'search',
  props: {
    placeholder: {
      type: String,
      default: '请输入搜索关键字',
    },
    showAction: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    background: {
      type: String,
      default: '#f2f2f2',
    },
    history: {
      type: String,
    },
    value: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      attachModuleShow: false,
      historyList: null,
      vl: '',
    }
  },
  components: {
    [Icon.name]: Icon,
  },
  watch: {
    value(a) {
      if (typeof a !== 'undefined') {
        this.vl = a
      }
    },
  },
  computed: {
    listeners() {
      const self = this
      const listeners = {
        ...this.$listeners,
        keypress: self.keypress,
        input: self.input,
        clear: self.clear,
        focus: self.focus,
      }
      const searchListeners = {}
      Object.keys(listeners).forEach(attr => {
        searchListeners[attr] = ev => {
          if (self[attr] && typeof self[attr] === 'function') {
            self[attr](ev)
          } else {
            self.doFn(attr)
          }
        }
      })
      return self.disabled ? {} : searchListeners
    },
    attachModuleDeploy() {
      return typeof this.history !== 'undefined'
    },
    historyTag() {
      return this.history ? this.history : 'common'
    },
  },
  methods: {
    doFn(str, v) {
      if (this.disabled) {
        return
      }
      if (v) {
        this.$emit(str, v)
      } else {
        this.$emit(str)
      }
    },
    clear() {
      this.vl = this.disabled ? this.vl : ''
      this.doFn('clear')
    },
    search() {
      this.doFn('search')
      this.attachModuleShow = false
      if (this.attachModuleDeploy) this.addHistory()
    },
    goSearch(str) {
      this.vl = str
      this.search()
    },
    cancel() {
      this.vl = this.disabled ? this.vl : ''
      this.doFn('cancel')
    },
    focus() {
      const self = this
      if (this.attachModuleDeploy) {
        this.attachModuleShow = true
        this.getHistoryLocal(true)
        setTimeout(() => {
          self.$refs.attachModule.focus()
        }, 100)
      }
    },
    input() {
      this.doFn('input', this.vl)
    },
    keypress(event) {
      if (
        event &&
        (event.keyCode === 13 || event.code === 'Enter') &&
        !this.disabled
      ) {
        event.preventDefault()
        this.search()
      }
      this.doFn('keypress', event)
    },
    getHistoryLocal(b) {
      const self = this
      const type = self.historyTag
      let historyLocal
      try {
        historyLocal = JSON.parse(window.localStorage.bxsSearchHis)
        historyLocal = typeof historyLocal !== 'object' ? {} : historyLocal
      } catch (e) {
        historyLocal = {}
      }
      if (b) {
        if (historyLocal[type] && historyLocal[type] instanceof Array) {
          self.historyList = historyLocal[type]
        } else {
          self.historyList = []
        }
      }
      return historyLocal
    },
    addHistory(b) {
      if (b) {
        this.attachModuleShow = false
      }
      if (!this.vl.trim()) {
        return
      }
      const historyLocal = this.getHistoryLocal()
      const type = this.historyTag
      let arr = historyLocal[type] ? historyLocal[type] : []
      arr = arr instanceof Array ? arr : []
      arr.unshift(this.vl)
      arr = arr.splice(0, 4)
      this.historyList = arr
      historyLocal[type] = arr
      window.localStorage.bxsSearchHis = JSON.stringify(historyLocal)
    },
    clearHistory(n) {
      const history = this.historyList
      if (typeof n !== 'undefined' && history[n]) {
        history.splice(n, 1)
      } else if (typeof n === 'undefined') {
        this.historyList = null
      }
      const historyLocal = this.getHistoryLocal()
      const type = this.historyTag
      historyLocal[type] =
        this.historyList && this.historyList.length ? this.historyList : null
      window.localStorage.bxsSearchHis = JSON.stringify(historyLocal)
    },
  },
  created() {
    this.vl = this.value
  },
})
</script>
<style>
@import './index.css';
</style>
