<template>
  <view class="content">
    <view class="search-box">
      <!-- mSearch组件 如果使用原样式，删除组件元素-->
      <mSearch class="mSearch-input-box" :mode="2" button="inside" :placeholder="defaultKeyword"
        @search="doSearch(false)" @input="changeInp" @confirm="doSearch(false)" v-model="keyword"></mSearch>
    </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(row)">
              <rich-text :nodes="row.htmlStr"></rich-text>
            </view>
            <view class="keyword-img" @tap.stop="doSearch(row)">
              <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>
  </view>
</template>

<script>
  //引用mSearch组件，如不需要删除即可
  import mSearch from "@/components/mehaotian-search-revision/mehaotian-search-revision.vue";
  import {
    get,
    post,
    webHandle
  } from "../../http/http.js";
  export default {
    data() {
      return {
        type: "", //进入该页面的类型
        configName: "", //快速组合名称
        id: "", //快速组合id
        changedept: 0, //是否从列表过来的切换负责科室
        hosId: "",
        defaultKeyword: "",
        keyword: "",
        oldKeywordList: [],
        keywordList: [],
        isShowKeywordList: false,
        deptList: [],
        //送回病房扫码 start
        code: '',
        infoDATA: '',
        patientOrders: '',
        workData: '',
        //送回病房扫码 end
        //送回病房-患者列表 start
        cid: '',
        cdept: '',
        currentItem: '',
        scrollYY: '',
        //送回病房-患者列表 end
        // 设置科室二维码 start
        uniName: '',
        queryDept: '',
        queryDeptId: '',
        sourceQr: '',
        qrCode: '',
        // 设置科室二维码 end
        // 选择血制品送达科室 start
        bloodDTO: {},
        // 选择血制品送达科室 end
        timer: null, //定时器
        searchText: '', //搜索文本
        searchData: [], //搜索结果
        //系统设置的科室类型
        sysDeptType: 0,
        //自选排班-科室绑定人员-科室类型 start
        quickCombinationDeptType: 0,
        //自选排班-科室绑定人员-科室类型 end
        //医废绑定 start
        medicalWasteBindCode: '',
        medicalWasteBindRemark: '',
        medicalWasteBindWeight: '',
        medicalWasteTypeIndex: '',
        //医废绑定 end
      };
    },
    onUnload() {
      if (this.timer) {
        clearTimeout(this.timer);
        this.timer = null;
      }
    },
    onLoad(options) {
      console.log(options, 'options');
      this.type = options.type;
      if (this.type == "setDept") {
        this.configName = options.configName;
        this.id = options.id;
        this.changedept = options.changedept;
        
        options.quickCombinationId && this.getQuickCombinationDeptType(+options.quickCombinationId);
        
      } else if (this.type == "sendBack") {
        this.code = options.code;
        this.infoDATA = options.infoDATA;
        this.patientOrders = options.patientOrders;
        this.workData = options.workData;
        this.sysDeptType = -1;
      } else if (this.type == "sendBackPatientList") {
        this.cid = options.cid;
        this.cdept = options.cdept;
        this.currentItem = options.currentItem;
        this.scrollYY = options.scrollYY;
        this.sysDeptType = -1;
      } else if (this.type == "settingCode") { //设置科室二维码
        this.uniName = options.uniName;
        this.queryDept = options.queryDept;
        this.queryDeptId = options.queryDeptId;
        this.sourceQr = options.sourceQr;
        this.qrCode = options.qrCode;
        this.sysDeptType = -1;
      }  else if (this.type == "pharmacy") { //药房切换科室
        this.sysDeptType = 386;
      }  else if (this.type == "medicalWasteBind") { //医废绑定
        this.medicalWasteBindCode = options.code;
        this.medicalWasteBindRemark = options.remark;
        this.medicalWasteBindWeight = options.weight;
        this.medicalWasteTypeIndex = options.medicalWasteTypeIndex;
        this.sysDeptType = -1;
      }  else if (this.type == "showDepartmentQrcode") { //科室二维码绑定
        this.sysDeptType = -1;
      }  else if (this.type == "bloodSelect") { //选择血制品送达科室
        this.bloodDTO = JSON.parse(options.bloodDTO);
      } else {
        this.getSysDeptType();
      }
      this.init();
      // #ifdef APP-PLUS
      webHandle("no", "app");
      // #endif
      // #ifdef H5
      webHandle("no", "wx");
      // #endif
    },
    components: {
      //引用mSearch组件，如不需要删除即可
      mSearch,
    },
    methods: {
      init() {
        this.hosId = uni.getStorageSync("userData").user.currentHospital.id;
        this.loadDefaultKeyword();
        this.loadOldKeyword();
      },
      blur() {
        uni.hideKeyboard();
      },
      //加载默认搜索关键字
      loadDefaultKeyword() {
        //定义默认搜索关键字，可以自己实现ajax请求数据再赋值,用户未输入时，以水印方式显示在输入框，直接不输入内容搜索会搜索默认关键字
        this.defaultKeyword = "请输入科室名称";
      },
      //加载历史搜索,自动读取本地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)
      },
      //获取系统设置的科室类型 sysDeptType
      getSysDeptType() {
        let postData = {
          "idx": 0,
          "sum": 1,
          systemConfiguration: {
            keyconfig: "busiViewDeptId"
          }
        }
        post("/simple/data/fetchDataList/systemConfiguration", postData).then((res) => {
          if (res.status == 200) {
            this.sysDeptType = res.list[0].valueconfig
          }
        })
      },
      //获取系统设置的科室类型 quickCombinationDeptType
      getQuickCombinationDeptType(quickCombinationId) {
        let postData = {
          "idx": 0,
          "sum": 1,
          workAllocationQuickConfig: {
            id: quickCombinationId
          }
        }
        post("/simple/data/fetchDataList/workAllocationQuickConfig", postData).then((res) => {
          if (res.status == 200) {
            let workAllocationQuickConfig = res.list[0] || {};
            // 科室绑定人员
            if(workAllocationQuickConfig.ruleType == 3){
              if(workAllocationQuickConfig.deptTypeList){
                this.quickCombinationDeptType = workAllocationQuickConfig.deptTypeList.map(v => v.id).toString();
              }else{
                // 没有获取到配置,则获取之前的
                this.getSysDeptType();
              }
            }else{
              this.getSysDeptType();
            }
          }
        })
      },
      //监听输入
      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: {
            hospital: {
              id: this.hosId,
            },
            dept: keyword,
          },
        };
        if(this.type == 'setDept'){
          postData = {
            idx: 0,
            sum: 20,
            department: {
              cascadeHosId: this.hosId,
              dept: keyword,
            },
          }
        }
        //不是送回病房
        if (this.type != "sendBack" && this.type != "sendBackPatientList" && this.type != "settingCode" && this.type != "bloodSelect" && this.type != "showDepartmentQrcode" && this.type != "medicalWasteBind") {
          if(this.quickCombinationDeptType){
            postData.department.deptTypeIds = this.quickCombinationDeptType;
          } else if (this.sysDeptType === 0) {
            return;
          } else {
            postData.department.type = {
              id: this.sysDeptType
            }
          }
        }
        
        // 设置二维码
        if(this.type == "settingCode"){
          postData = {
            hosId: this.hosId,
            searchKey: keyword,
          }
        }
        
        uni.showLoading({
          title: "加载中",
        });
        
        post(this.type == "settingCode" ? "/dept/queryChangeDept" : "/data/fetchDataList/department", postData).then((res) => {
          if (res.status == 200 || res.state == 200) {
            if(this.type == "settingCode"){
              let deptList = res.deptList.map(v => ({...v, sign: 'dept'}));
              let qrList = res.qrList.map(v => ({...v.deptDTO, sign: 'qr', qrId: v.id, name: v.name}));
              this.searchData.push({
                name: keyword,
                list: deptList.concat(qrList)
              });
            }else{
              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);
            uni.hideLoading();
          } else {
            uni.hideLoading();
            uni.showToast({
              icon: "none",
              title: res.msg || "接口获取数据失败！",
            });
          }
        });
      },
      //高亮关键字
      drawCorrelativeKeyword(keywords, keyword) {
        var len = keywords.length,
          keywordArr = [];
        for (var i = 0; i < len; i++) {
          var row = keywords[i];
          //定义高亮#9f9f9f
          var html = row.dept.replace(
            keyword,
            "<span style='color: #9f9f9f;'>" + keyword + "</span>"
          );
          html = "<div>" + html + (row.sign == 'qr' ? '（'+ row.name +'）' : '') + (row.sign == 'qr' ? '<span class="red">（配置）</span>' : '') + "</div>";
          var tmpObj = {
            id: row.id,
            qrId: row.qrId,
            keyword: row.dept,
            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("用户点击取消");
            }
          },
        });
      },
      // 建单并签到-指定科室
      buildOrderAndSign(deptDto) {
        uni.showModal({
          title: "提示",
          content: `您当前选择的科室为【${deptDto.dept}】，请确认是否建单并签到？`,
          success: (result) => {
            if (result.confirm) {
              console.log("用户点击确定");
              let postData = {
                type: 'blood',
                id: this.bloodDTO.id,
                applyDept: deptDto.id,
              };
              uni.showLoading({
                title: "加载中",
                mask: true,
              });
              post("/transflow/createOrTakeOrder", postData).then((ress) => {
                uni.hideLoading();
                if (ress.state == 200) {
                  uni.navigateTo({
                    url: `../scanning_blood_process/scanning_blood_process?orderId=${ress.data.orderId}&bloodDTO=${encodeURIComponent(JSON.stringify(this.bloodDTO))}&scanCount=${ress.data.scanCount}&status=${ress.state}`,
                  });
                } else {
                  uni.showToast({
                    icon: "none",
                    title: ress.msg || "接口获取数据失败！",
                  });
                }
              });
            } else if (result.cancel) {
              console.log("用户点击取消");
            }
          },
        });
      },
      //执行搜索
      doSearch(data) {
        console.log(data);
        let keyword = keyword === false ? this.keyword : data.keyword;
        this.keyword = keyword;
        this.saveKeyword(keyword); //保存为历史
        let arr = this.deptList.filter((item) => data.qrId ? (item.qrId === data.qrId) : (item.dept === keyword));
        if (arr.length) {
          let msg = "";
          if (this.type == "patientInformationList" || this.type == "inspectList" || this.type == "pharmacy" || this.type == "showDepartmentQrcode" || this.type == "medicalWasteBind") {
            msg = "切换科室成功";
            uni.showToast({
              title: msg,
              icon: "none",
              duration: 2000,
            });
          } else if (this.type == "setDept") {
            msg = "添加科室成功";
            uni.showToast({
              title: msg,
              icon: "none",
              duration: 2000,
            });
          }
          if (this.type == "patientInformationList") {
            //患者列表进入
            uni.setStorageSync("patientCurrentDept", arr[0]); //科室切换存本地
            uni.navigateTo({
              url: `../patientInformationList/patientInformationList?id=${arr[0].id}&dept=${arr[0].dept}`,
            });
          } else if (this.type == "inspectList") {
            //患者列表进入
            uni.setStorageSync("patientCurrentDept", arr[0]); //科室切换存本地
            uni.navigateTo({
              url: `../inspectList/inspectList?id=${arr[0].id}&dept=${arr[0].dept}`,
            });
          } else if (this.type == "bloodSelect") {
            //血制品建单进入
            this.buildOrderAndSign(arr[0]);
          } else if (this.type == "pharmacy") {
            //药房进入
            uni.navigateTo({
              url: `../pharmacy/pharmacy?id=${arr[0].id}&dept=${arr[0].dept}`,
            });
          } else if (this.type == "showDepartmentQrcode") {
            //科室二维码进入
            uni.navigateTo({
              url: `../receiptpage/receiptpage?showDepartmentQrcodeId=${arr[0].id}&showDepartmentQrcodeDept=${arr[0].dept}`,
            });
          } else if (this.type == "medicalWasteBind") {
            //医废绑定进入
            uni.navigateTo({
              url: `/pages/medicalWaste/medicalWasteBind/medicalWasteBind?qrcode=${this.medicalWasteBindCode}&deptId=${arr[0].id}&deptName=${arr[0].dept}&remark=${this.medicalWasteBindRemark}&weight=${this.medicalWasteBindWeight}&medicalWasteTypeIndex=${this.medicalWasteTypeIndex}`,
            });
          } else if (this.type == "setDept") {
            //上班添加科室进入
            let obj = uni.getStorageSync("setDepts");
            console.log(arr,obj)
            if (obj) {
              let i = obj.findIndex((item) => item.id == arr[0].id);
              if (i < 0) {
                uni.setStorageSync("setDepts", [arr[0], ...obj]);
              }
            } else {
              uni.setStorageSync("setDepts", [arr[0]]);
            }
            uni.navigateTo({
              url: `../setDept/setDept?configName=${this.configName}&id=${this.id}&changedept=${this.changedept}`,
            });
          } else if (this.type == "sendBack") {
            uni.navigateTo({
              url: `../scanning_ins/scanning_ins?id=${arr[0].id}&dept=${arr[0].dept}&code=${this.code}&infoDATA=${this.infoDATA}&patientOrders=${this.patientOrders}&workData=${this.workData}`,
            });
          } else if (this.type == "sendBackPatientList") {
            uni.navigateTo({
              url: `../patientInformationList/patientInformationList?did=${arr[0].id}&ddept=${arr[0].dept}&currentItem=${this.currentItem}&id=${this.cid}&dept=${this.cdept}&scrollYY=${this.scrollYY}`,
            });
          } else if (this.type == "settingCode") {
            if (this.queryDept) { //替换
              console.log(arr);
              uni.navigateTo({
                url: `../settingCode/settingCode?destQr=${arr[0].qrId || ''}&name=${arr[0].name || ''}&targetId=${arr[0].id}&targetDept=${arr[0].dept}&uniName=${this.uniName}&queryDept=${this.queryDept}&queryDeptId=${this.queryDeptId}&sourceQr=${this.sourceQr || ''}&qrCode=${this.qrCode}`,
              });
            } else { //设置
              uni.navigateTo({
                url: `../settingCode/settingCode?qrId=${arr[0].qrId || ''}&targetId=${arr[0].id}&targetDept=${arr[0].dept}&uniName=${this.uniName}&qrCode=${this.qrCode}`,
              });
            }
          } else if (this.type == "takeOrder") { //接单
						let data = uni.getStorageSync("admStore")
						data.deptId = arr[0].id
						data.dept = arr[0].dept
						data.type = 'searchAdm'
						data.isSearch = true
						uni.setStorageSync("admStore",data)
						uni.navigateTo({
							url: `../receiptpage/receiptpage`,
						});
					}
        }
      },
      //保存关键字到历史记录
      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; //更新历史搜索
          },
        });
      },
    },
  };
</script>
<style>
  view {
    display: block;
  }

  .search-box {
    width: 95%;
    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>
