<template>
  <div class="content">
    <div class="search-box">
      <seiminSearch
        class="mSearch-input-box"
        :mode="2"
        button="inside"
        placeholder="请输入科室名称"
        @search="doSearch(false)"
        @input="changeInp"
        @confirm="doSearch(false)"
        v-model="keyword"
      ></seiminSearch>
    </div>
    <div class="search-keyword">
      <cube-scroll class="keyword-list-box" v-show="isShowKeywordList">
        <div class="keyword-entry" v-for="(row, index) in keywordList" :key="index">
          <div
            class="keyword-text"
            @click.stop="doSearch(keywordList[index].keyword)"
          >
            <span v-html="row.htmlStr"></span>
          </div>
          <div
            class="keyword-img"
            @click.stop="doSearch(keywordList[index].keyword)"
          >
            <img src="../assets/HM-search/back.png" />
          </div>
        </div>
      </cube-scroll>
      <cube-scroll class="keyword-box" v-show="!isShowKeywordList">
        <div class="keyword-block" v-if="oldKeywordList.length > 0">
          <div class="keyword-list-header">
            <div>历史搜索</div>
            <div>
              <img @click="oldDelete" src="../assets/HM-search/delete.png" />
            </div>
          </div>
          <div class="keyword">
            <div
              v-for="(keyword, index) in oldKeywordList"
              @click="changeInp(keyword)"
              :key="index"
            >
              {{ keyword }}
            </div>
          </div>
        </div>
      </cube-scroll>
    </div>
    <!-- <seiminModel ref="seiminModel"></seiminModel> -->
  </div>
</template>

<script>
import seiminSearch from "../custom/seiminSearch.vue";
export default {
  components: {
    seiminSearch
  },
  data() {
    return {
      reFresh: "",
      keyword: "",
      oldKeywordList: [],
      keywordList: [],
      isShowKeywordList: false,
      deptList: [],
      timer: null, //定时器
      searchText: "", //搜索文本
      searchData: [] //搜索结果
    };
  },
  beforeDestroy() {
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }
  },
  mounted() {
    // this.$route.query.type
    this.init();
  },
  methods: {
    init() {
      this.loadOldKeyword();
    },
    //加载历史搜索,自动读取本地Storage
    loadOldKeyword() {
      this.oldKeywordList = JSON.parse(localStorage.getItem("OldKeys")) || [];
    },
    //防抖搜索
    changeInp(event) {
      this.searchText = event;
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.inputChange(event);
      }, 500);
    },
    //监听输入
    inputChange(event = "") {
      //兼容引入组件时传入参数情况
      var keyword = event.target ? event.target.value : event;
      if (!keyword) {
        this.keywordList = [];
        this.isShowKeywordList = false;
        return;
      }
      this.keyword = keyword;
      this.isShowKeywordList = true;
      let postData = {
        idx: 0,
        sum: 9999,
        department: {
          dept: keyword,
          selectType: "pinyin_qs",
          branch: this.$route.params.branch ? +this.$route.params.branch : undefined,
        }
      };
      this.toast = this.$createToast({
        mask: true,
        txt: "正在加载中"
      });
      this.toast.show();
      this.$http
        .post("service/user/data/fetchDataList/department", postData)
        .then(res => {
          res = res.data;
          this.toast.hide();
          if (res.status == 200) {
            this.searchData.push({
              name: keyword,
              list: res.list || []
            });
            let searchText = this.searchText.detail
              ? this.searchText.detail.value
              : this.searchText;
            let index = this.searchData.findIndex(
              item => item.name === searchText
            );
            this.deptList = index >= 0 ? this.searchData[index].list : [];
            this.keywordList = this.drawCorrelativeKeyword(
              this.deptList,
              keyword
            );
          } else {
            this.$refs.seiminModel.show({
              skin: "toast",
              icon: "error",
              content: res.msg || "获取数据失败"
            });
            throw new Error(res.msg || "获取数据失败");
          }
        });
    },
    //高亮关键字
    drawCorrelativeKeyword(keywords, keyword) {
      var len = keywords.length,
        keywordArr = [];
      for (var i = 0; i < len; i++) {
        var row = keywords[i];
        //定义高亮#9f9f9f
        var html = "";
        // 科室名称
        html = row.dept.replace(
          keyword,
          "<span style='color: #9f9f9f;'>" + keyword + "</span>"
        );
        html = "<div>" + html + "</div>";
        var tmpObj = {
          keyword: row.dept,
          htmlStr: html
        };
        keywordArr.push(tmpObj);
      }
      return keywordArr;
    },
    //清除历史搜索
    oldDelete() {
      this.$createDialog({
        type: "confirm",
        icon: "cubeic-alert",
        title: "提示",
        content: "确定清除历史搜索记录？",
        confirmBtn: {
          text: "确定",
          active: true,
          disabled: false,
          href: "javascript:;"
        },
        cancelBtn: {
          text: "取消",
          active: false,
          disabled: false,
          href: "javascript:;"
        },
        onConfirm: () => {
          this.oldKeywordList = [];
          localStorage.removeItem("OldKeys");
        },
        onCancel: () => {}
      }).show();
    },
    //执行搜索
    doSearch(keyword) {
      keyword = keyword === false ? this.keyword : keyword;
      this.keyword = keyword;
      this.saveKeyword(keyword); //保存为历史
      let arr = this.deptList.filter(item => {
        return item.dept === keyword;
      });
      if (arr.length) {
        this.$router.push({name: 'NewIncident', params: {
            model: this.$route.params.model,
            order: this.$route.params.order,
            selectedCategoryTxt: this.$route.params.selectedCategoryTxt,
            dept: {
              id: arr[0].id,
              dept: arr[0].dept,
              phone: arr[0].phone || '',
              areaId: arr[0].place ? arr[0].place.area.id : '',
              areaName: arr[0].place ? arr[0].place.area.area : '',
              placeId: arr[0].place ? arr[0].place.id : '',
              placeName: arr[0].place ? arr[0].place.place : '',
            }
        }})
      }
    },
    //保存关键字到历史记录
    saveKeyword(keyword) {
      var OldKeys = JSON.parse(localStorage.getItem("OldKeys"));
      if (OldKeys) {
        var findIndex = OldKeys.indexOf(keyword);
        if (findIndex == -1) {
          OldKeys.unshift(keyword);
        } else {
          OldKeys.splice(findIndex, 1);
          OldKeys.unshift(keyword);
        }
        //最多10个纪录
        OldKeys.length > 10 && OldKeys.pop();
        localStorage.setItem("OldKeys", JSON.stringify(OldKeys));
        this.oldKeywordList = OldKeys; //更新历史搜索
      } else {
        OldKeys = [keyword];
        localStorage.setItem("OldKeys", JSON.stringify(OldKeys));
        this.oldKeywordList = OldKeys; //更新历史搜索
      }
    }
  }
};
</script>
<style lang="less" scoped>
.search-box {
  background-color: rgb(242, 242, 242);
  padding: 0.15rem 2.5%;
  display: flex;
  justify-content: space-between;
  position: sticky;
  top: 0;
}

.search-box .mSearch-input-box {
  width: 100%;
}

.search-box .input-box {
  width: 85%;
  flex-shrink: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.search-box .search-btn {
  width: 15%;
  margin: 0 0 0 2%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-shrink: 0;
  font-size: 0.28rem;
  color: #fff;
  background: linear-gradient(to right, #ff9801, #ff570a);
  border-radius: 0.6rem;
}

.search-box .input-box > input {
  width: 100%;
  height: 0.6rem;
  font-size: 0.32rem;
  border: 0;
  border-radius: 0.6rem;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  padding: 0 3%;
  margin: 0;
  background-color: #ffffff;
}

.placeholder-class {
  color: #9e9e9e;
}

.search-keyword {
  width: 100%;
  background-color: rgb(242, 242, 242);
}

.keyword-list-box {
  height: calc(100vh - 1.1rem);
  padding-top: 0.1rem;
  border-radius: 0.2rem 0.2rem 0 0;
  background-color: #fff;
}

.keyword-entry-tap {
  background-color: #eee;
}

.keyword-entry {
  width: 94%;
  height: 0.8rem;
  margin: 0 3%;
  font-size: 0.3rem;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: solid 1px #e7e7e7;
}

.keyword-entry img {
  width: 0.6rem;
  height: 0.6rem;
}

.keyword-entry .keyword-text,
.keyword-entry .keyword-img {
  height: 0.8rem;
  display: flex;
  align-items: center;
}

.keyword-entry .keyword-text {
  width: 90%;
}

.keyword-entry .keyword-img {
  width: 10%;
  justify-content: center;
}

.keyword-box {
  height: calc(100vh - 1.1rem);
  border-radius: 0.2rem 0.2rem 0 0;
  background-color: #fff;
}

.keyword-box .keyword-block {
  padding: 0.1rem 0;
}

.keyword-box .keyword-block .keyword-list-header {
  width: 94%;
  padding: 0.1rem 3%;
  font-size: 0.27rem;
  color: #333;
  display: flex;
  justify-content: space-between;
}

.keyword-box .keyword-block .keyword-list-header img {
  width: 0.4rem;
  height: 0.4rem;
}

.keyword-box .keyword-block .keyword {
  width: 94%;
  padding: 3px 3%;
  display: flex;
  flex-flow: wrap;
  justify-content: flex-start;
}

.keyword-box .keyword-block .hide-hot-tis {
  display: flex;
  justify-content: center;
  font-size: 0.28rem;
  color: #6b6b6b;
}

.keyword-box .keyword-block .keyword > div {
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 0.6rem;
  padding: 0 0.2rem;
  margin: 0.1rem 0.2rem 0.1rem 0;
  height: 0.6rem;
  font-size: 0.28rem;
  background-color: rgb(242, 242, 242);
  color: #6b6b6b;
}
</style>
