<template>
  <div class="search-wrapper" :class="{ 'customer-bor': resultDisplay }">
    <c-input
      prefix-icon="el-icon-search"
      placeholder="全局搜索"
      v-model="searchContent"
      @keyup.enter.native="searchEvent"
      @keydown.up.native="preDownEvent"
      @keyup.up.native="preUpEvent"
      @keydown.down.native="nextDownEvent"
      @keyup.down.native="nextUpEvent"
      @focus="focusInput"
      @blur="blurInput"
    ></c-input>
    <div
      class="search-sug"
      v-show="resultDisplay"
      @mouseenter="isChoosing = true"
      @mouseleave="isChoosing = false"
    >
      <ul>
        <li
          :class="{ 'sug-selected': item.selected }"
          v-for="(item, idx) in searchResult"
          :key="idx"
          @mouseover="liOverEvent(idx)"
          @mouseup.left="searchEvent(item.text)"
          v-html="item.text"
        ></li>
      </ul>
    </div>
  </div>
</template>

<script>
import debounce from "lodash/debounce";

export default {
  name: "SearchInput",
  data() {
    return {
      searchContent: "",
      searchResult: [],
      selectedIndex: 0,
      resultDisplay: false,
      // 鼠标选择结果集的状态
      isChoosing: false,
      debounceWrapper: debounce(this.queryData, 500),
    };
  },
  watch: {
    searchContent: function(val, oldVal) {
      // console.log(val, oldVal);
      if (val.trim() === "") {
        this.searchResult = [];
        this.resultDisplay = false;
        return;
      }
      if (this.searchResult.map((r) => r.text).includes(val)) {
        return;
      }
      this.debounceWrapper();
    },
  },
  methods: {
    queryData() {
      const testData = [
        { text: "DD3500210260AA01", url: "" },
        { text: "OC3500190001AA", url: "" },
        { text: "KZ3500210313AA", url: "" },
        { text: "KZ3500210312AA", url: "" },
        { text: "DD3500210311AA01", url: "" },
        { text: "DD3500210311AA01", url: "" },
        { text: "KZ3500210311AA", url: "" },
        { text: "CH3500200001AA", url: "" },
        { text: "CH3323200001AB", url: "" },
        { text: "DV453500210260AA01", url: "" },
        { text: "KZ3500210313AA", url: "" },
        { text: "DD45350029760AA01", url: "" },
        { text: "CH3500343657001AA", url: "" },
        { text: "CH35987567001AA", url: "" },
        { text: "CH243534200001AA", url: "" },
        { text: "CH350086786001AA", url: "" },
        { text: "CH53454001AA", url: "" },
        { text: "CH65645FG4545AA", url: "" },
      ];
      console.log("query data ..." + new Date().toLocaleString());
      // this.shuffle(testData);
      // const res = testData;
      const res = testData
        .filter((d) => d.text.indexOf(this.searchContent) > -1)
        .map((d) =>
          Object.assign(d, {
            text: d.text.replace(
              this.searchContent,
              "<em>" + this.searchContent + "</em>"
            ),
          })
        );
      if (res && res.length > 0) {
        this.resultDisplay = true;
        this.searchResult = res;
      } else {
        this.searchResult = [];
        this.resultDisplay = false;
      }
    },
    shuffle(arr) {
      let i = arr.length - 1;
      while (i > 0) {
        const n = (Math.random() * i) >>> 0;
        [arr[n], arr[i]] = [arr[i], arr[n]];
        i--;
      }
    },
    searchEvent(val) {
      if (typeof val === "string") {
        this.searchContent = val;
      }
      this.resultDisplay = false;
      // TODO
      console.log("go to ...");
    },
    focusInput() {
      if (this.searchResult.length > 0) {
        this.resultDisplay = true;
      }
    },
    blurInput() {
      if (!this.isChoosing) {
        this.resultDisplay = false;
      }
      this.selectedIndex = -1;
      this.clearHighlightItem();
    },
    goNext() {
      if (this.searchResult.length === 0) {
        return;
      }
      if (this.selectedIndex >= this.searchResult.length - 1) {
        this.selectedIndex = 0;
      } else {
        this.selectedIndex++;
      }
      this.highlightItem(this.selectedIndex, true);
    },
    goPre() {
      if (this.searchResult.length === 0) {
        return;
      }
      if (this.selectedIndex <= 0) {
        this.selectedIndex = this.searchResult.length - 1;
      } else {
        this.selectedIndex--;
      }
      this.highlightItem(this.selectedIndex, true);
    },
    highlightItem(idx, changeVal) {
      // console.log(idx);
      const lis = this.$el.querySelectorAll(".search-sug ul li");
      lis.forEach((li) => (li.className = ""));
      if (lis[idx] && this.searchResult[idx]) {
        lis[idx].className = "sug-selected";
        if (changeVal) {
          this.searchContent = this.searchResult[idx].text;
        }
      }
    },
    liOverEvent(idx) {
      this.selectedIndex = idx;
      this.highlightItem(idx, false);
    },
    clearHighlightItem() {
      this.$el
        .querySelectorAll(".search-sug ul li")
        .forEach((li) => (li.className = ""));
    },
    /**
     * up按下
     */
    preDownEvent() {
      // console.log("up key: down");
      this.goPre();
    },
    /**
     * up弹起
     */
    preUpEvent() {
      // console.log("up key: up");
    },
    /**
     * down按下
     */
    nextDownEvent() {
      // console.log("down key: down");
      this.goNext();
    },
    /**
     * down弹起
     */
    nextUpEvent() {
      // console.log("down key: up");
    },
  },
};
</script>

<style scoped>
.search-wrapper {
  position: relative;
}
.search-wrapper >>> .el-input {
  z-index: 2001;
}
.search-wrapper >>> .el-input .el-input__inner {
  height: 30px;
}
.search-sug {
  position: absolute;
  width: 590px;
  top: 28px;
  border-radius: 0 0 10px 10px;
  border: 2px solid #4e71f2;
  box-shadow: none;
  font-family: "Microsoft YaHei", Arial, sans-serif;
  z-index: 2000;
  background: #fff;
}
.search-sug ul {
  margin: 7px 14px 0;
  padding: 8px 0 7px;
  background: 0 0;
  border-top: 2px solid #f5f5f6;
}
.search-sug ul li {
  list-style: none;
  width: auto;
  padding: 0 8px;
  padding-left: 14px;
  margin-left: -14px;
  margin-right: -14px;
  color: #626675;
  font: 14px arial;
  line-height: 28px;
  background: 0 0;
  font-family: "Microsoft YaHei", Arial, sans-serif;
  position: relative;
  cursor: pointer;
}
.search-sug ul li.sug-selected {
  background-color: #f5f5f6;
  color: #315efb;
}
.search-wrapper >>> .el-input__inner:focus {
  border: 2px solid #4e71f2;
  outline: 0;
}
.customer-bor >>> .el-input__inner {
  border-bottom: 0 !important;
  border-bottom-left-radius: 0;
  border-bottom-right-radius: 0;
}

.search-sug ul li >>> em {
  color: #f73131;
  font-style: normal;
}
</style>
