<template>
  <view class="content">
    <view 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>
    </view>
    <view class="search-keyword">
      <scroll-view class="keyword-list-box" v-show="isShowKeywordList" scroll-y>
        <block v-for="(row, index) in keywordList" :key="index">
          <view class="keyword-entry" hover-class="keyword-entry-tap">
            <view class="keyword-text" @tap.stop="doSearch(keywordList[index].keyword)">
              <rich-text :nodes="row.htmlStr"></rich-text>
            </view>
            <view class="keyword-img" @tap.stop="doSearch(keywordList[index].keyword)">
              <image src="/static/HM-search/back.png"></image>
            </view>
          </view>
        </block>
      </scroll-view>
      <scroll-view class="keyword-box" v-show="!isShowKeywordList" scroll-y>
        <view class="keyword-block" v-if="oldKeywordList.length > 0">
          <view class="keyword-list-header">
            <view>历史搜索</view>
            <view>
              <image @tap="oldDelete" src="/static/HM-search/delete.png"></image>
            </view>
          </view>
          <view class="keyword">
            <view v-for="(keyword, index) in oldKeywordList" @tap="changeInp(keyword)" :key="index">{{ keyword }}
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <seiminModel ref="seiminModel"></seiminModel>
  </view>
</template>

<script>
  import {
    reqFetchDataList,
    reqChangeHospital,
    reqUpdData,
    reqGetCurrentUser,
  } from "../../request/api.js";
  import {
    mapState,
    mapMutations
  } from "vuex";
  export default {
    data() {
      return {
        keyword: "",
        oldKeywordList: [],
        keywordList: [],
        isShowKeywordList: false,
        deptList: [],
        timer: null, //定时器
        searchText: "", //搜索文本
        searchData: [], //搜索结果
      };
    },
    computed: {
      ...mapState("login", ["loginInfo"]),
      ...mapState('other', [
        "deptDisplay",
        "searchDeptParams",
        "searchDeptResult",
        "searchDeptResultList",
      ]),
    },
    onUnload() {
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      }
    },
    onLoad(options) {
      this.init();
    },
    methods: {
      ...mapMutations('other', [
        "changeSearchDeptResult",
        "changeSeiminModel",
        "changeSearchDeptResultList",
      ]),
      ...mapMutations("login", ["changeLoginInfo"]),
      init() {
        this.loadOldKeyword();
      },
      blur() {
        uni.hideKeyboard();
      },
      //加载历史搜索,自动读取本地Storage
      loadOldKeyword() {
        uni.getStorage({
          key: "OldKeys",
          success: (res) => {
            var OldKeys = JSON.parse(res.data);
            this.oldKeywordList = OldKeys;
          },
        });
      },
      //防抖搜索
      changeInp(event) {
        this.searchText = event;
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.inputChange(event);
        }, 500);
      },
      //监听输入
      inputChange(event) {
        //兼容引入组件时传入参数情况
        var keyword = event.detail ? event.detail.value : event;
        if (!keyword) {
          this.keywordList = [];
          this.isShowKeywordList = false;
          return;
        }
        this.keyword = keyword;
        this.isShowKeywordList = true;
        let postData = {
          idx: 0,
          sum: 20,
          department: {},
        };
        // 院区参数----start
        if (this.searchDeptParams.type === "changeDept_index") {
          //首页切换科室
          postData.department.hospital = {
            id: this.searchDeptParams.hospital.value,
          };
          postData.department.keyWord = keyword;
          postData.department.nurseSign = 1;
        } else if (
          this.searchDeptParams.type === "selectDept_start_qucikCreateOrder" ||
          this.searchDeptParams.type === "selectDept_end_qucikCreateOrder"
        ) {
          //快捷建单选择起点科室或选择终点科室
          postData.department.hospital = {
            id: this.loginInfo.user.currentHospital.id,
          };
          postData.department.searchType = 1;
          postData.department.ids = this.searchDeptParams.ids;
          postData.department.keyWord = keyword;
          postData.department.nurseSign = 1;
          if (this.searchDeptParams.departmentStrategy == 205) {
            // 固定科室类型
            postData.department.type = {
              id: this.searchDeptParams.deptType,
            };
          }
        } else {
          postData.department.hospital = {
            id: this.loginInfo.user.currentHospital.id,
          };
          // 科室名称或科室别称开关----start
          if (this.deptDisplay == 1) {
            //科室名称
            postData.department.dept = keyword;
          } else if (this.deptDisplay == 2) {
            //科室别称
            postData.department.deptalias = keyword;
          }
          // 科室名称或科室别称开关----end
        }
        // 院区参数----end
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
        reqFetchDataList("data", "department", postData).then((res) => {
          uni.hideLoading();
          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.showChangeDept({
              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 = "";
          if (this.deptDisplay == 1) {
            // 科室名称
            html = row.dept.replace(
              keyword,
              "<span style='color: #9f9f9f;'>" + keyword + "</span>"
            );
          } else if (this.deptDisplay == 2) {
            // 科室别称
            html = row.deptalias.replace(
              keyword,
              "<span style='color: #9f9f9f;'>" + keyword + "</span>"
            );
          }
          html = "<div>" + html + "</div>";
          var tmpObj = {
            keyword: this.deptDisplay == 1 ? row.dept : row.deptalias,
            htmlStr: html,
          };
          keywordArr.push(tmpObj);
        }
        return keywordArr;
      },
      //清除历史搜索
      oldDelete() {
        uni.showModal({
          content: "确定清除历史搜索记录?",
          success: (res) => {
            if (res.confirm) {
              console.log("用户点击确定");
              this.oldKeywordList = [];
              uni.removeStorage({
                key: "OldKeys",
              });
            } else if (res.cancel) {
              console.log("用户点击取消");
            }
          },
        });
      },
      //执行搜索
      doSearch(keyword) {
        keyword = keyword === false ? this.keyword : keyword;
        this.keyword = keyword;
        this.saveKeyword(keyword); //保存为历史
        let arr = this.deptList.filter((item) => {
          return this.deptDisplay == 1 ?
            item.dept === keyword :
            item.deptalias === keyword;
        });
        if (arr.length) {
          this.changeSearchDeptResult(arr[0]);
          if (this.searchDeptParams.type === "changeDept_index") {
            //首页切换科室
            this.changeDept_index_handler();
          } else if (
            this.searchDeptParams.type === "selectDept_start_qucikCreateOrder"
          ) {
            //快捷建单选择起点科室
            this.searchDeptResultList.start = arr[0];
            this.changeSearchDeptResultList(this.searchDeptResultList);
            this.selectDept_startOrEnd_qucikCreateOrder();
          } else if (
            this.searchDeptParams.type === "selectDept_end_qucikCreateOrder"
          ) {
            //快捷建单选择终点科室
            this.searchDeptResultList.end = arr[0];
            this.changeSearchDeptResultList(this.searchDeptResultList);
            this.selectDept_startOrEnd_qucikCreateOrder();
          }
        }
      },
      //保存关键字到历史记录
      saveKeyword(keyword) {
        uni.getStorage({
          key: "OldKeys",
          success: (res) => {
            var OldKeys = JSON.parse(res.data);
            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();
            uni.setStorage({
              key: "OldKeys",
              data: JSON.stringify(OldKeys),
            });
            this.oldKeywordList = OldKeys; //更新历史搜索
          },
          fail: (e) => {
            var OldKeys = [keyword];
            uni.setStorage({
              key: "OldKeys",
              data: JSON.stringify(OldKeys),
            });
            this.oldKeywordList = OldKeys; //更新历史搜索
          },
        });
      },
      //首页切换科室
      changeDept_index_handler() {
        if (this.searchDeptParams.type === "changeDept_index") {
          // 首页切换科室
          uni.showLoading({
            title: "加载中",
            mask: true,
          });
          if (
            this.loginInfo.user.currentHospital.id ==
            this.searchDeptParams.hospital.value
          ) {
            //没有切换院区
            this.changeDept_index_handler_common();
          } else {
            //切换院区
            reqChangeHospital({
              currentHosId: this.searchDeptParams.hospital.value,
              loginType: "PC",
            }).then((res) => {
              if (res.status == 200) {
                this.changeDept_index_handler_common();
              } else {
                uni.hideLoading();
                this.$refs.seiminModel.showChangeDept({
                  skin: "toast",
                  icon: "error",
                  content: res.msg || "操作失败",
                });
                throw new Error(res.msg || "操作失败");
              }
            });
          }
        }
      },
      // 首页切换科室,公共方法
      changeDept_index_handler_common() {
        // 更新用户
        reqUpdData("data", "user", {
          user: {
            dept: {
              id: this.searchDeptResult.id,
            },
            id: this.loginInfo.user.id,
          },
        }).then((res) => {
          if (res.status == 200) {
            // 获取当前登录用户信息
            reqGetCurrentUser().then((res) => {
              uni.hideLoading();
              if (res.status == 200) {
                this.$refs.seiminModel.showChangeDept({
                  skin: "toast",
                  icon: "success",
                  content: "切换科室成功",
                  btns: [{
                    click: (e) => {
                      this.changeLoginInfo(res.data);
                      this.changeSeiminModel(true);
                      uni.navigateTo({
                        url: this.searchDeptParams.backUrl,
                      });
                    },
                  }, ],
                });
              } else {
                this.$refs.seiminModel.showChangeDept({
                  skin: "toast",
                  icon: "error",
                  content: res.msg || "操作失败",
                });
                throw new Error(res.msg || "操作失败");
              }
            });
          } else {
            uni.hideLoading();
            this.$refs.seiminModel.showChangeDept({
              skin: "toast",
              icon: "error",
              content: res.msg || "操作失败",
            });
            throw new Error(res.msg || "操作失败");
          }
        });
      },
      // 快捷建单选择起点科室或选择终点科室
      selectDept_startOrEnd_qucikCreateOrder() {
        uni.navigateTo({
          url: this.searchDeptParams.backUrl,
        });
      },
    },
  };
</script>
<style lang="scss" scoped>
  view {
    display: block;
  }

  .search-box {
    background-color: rgb(242, 242, 242);
    padding: 15upx 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: 28upx;
    color: #fff;
    background: linear-gradient(to right, #ff9801, #ff570a);
    border-radius: 60upx;
  }

  .search-box .input-box>input {
    width: 100%;
    height: 60upx;
    font-size: 32upx;
    border: 0;
    border-radius: 60upx;
    -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 - 110upx);
    padding-top: 10upx;
    border-radius: 20upx 20upx 0 0;
    background-color: #fff;
  }

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

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

  .keyword-entry image {
    width: 60upx;
    height: 60upx;
  }

  .keyword-entry .keyword-text,
  .keyword-entry .keyword-img {
    height: 80upx;
    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 - 110upx);
    border-radius: 20upx 20upx 0 0;
    background-color: #fff;
  }

  .keyword-box .keyword-block {
    padding: 10upx 0;
  }

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

  .keyword-box .keyword-block .keyword-list-header image {
    width: 40upx;
    height: 40upx;
  }

  .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: 28upx;
    color: #6b6b6b;
  }

  .keyword-box .keyword-block .keyword>view {
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 60upx;
    padding: 0 20upx;
    margin: 10upx 20upx 10upx 0;
    height: 60upx;
    font-size: 28upx;
    background-color: rgb(242, 242, 242);
    color: #6b6b6b;
  }
</style>