<template>
  <div class="add-diagnose-wrap">

    <div class="fixed-wrap" v-show="showDiagnoseModal">
      <div class="fullscreen-bg"></div>
      <div class="add-diagnose-modal" >
        <span class="close-btn el-icon-close" @click="hideSelf"></span>
        <p class="title-text">添加诊断</p>
        <div class="search-input">
          <el-input v-model="searchInput" placeholder="搜索诊断" class="search-disease" @input="handleInputSearch" @blur="handleSearchListBlur"></el-input>
        </div>
        <div class="main-content">
          <div class="left-box left">
            <!-- 搜索列表 有搜索结果时-->
            <div
              v-if="searchList && searchList.length > 0"
              class="search-list-wrap"
              v-infinite-scroll="loadMore"
              :infinite-scroll-disabled="busy"
              infinite-scroll-distance="5"
              infinite-scroll-immediate-check="false"
            >
              <ul class="search-list">
                <li v-for="(searchLi, index) in searchList" @mousedown="handleSearchLiClick(searchLi)">
                  <div class="left">
                    <p class="disease-name" v-html="searchLi.diseaseName"></p>
                    <div class="one-line">
                      <p class="alias" v-html="searchLi.alias"></p>
                      <p class="sign" v-if="searchLi.alias">|</p>
                      <p class="code">{{searchLi.icdCode}}</p>
                    </div>
                  </div>
                  <div class="right" v-if="isSearchLiSelected(searchLi)"><i class="el-icon-check"></i></div>
                </li>
                <p v-if="busy" class="loading">加载中...</p>
                <p v-if="noMore" class="loading">没有更多了...</p>
              </ul>
            </div>

            <!-- 常用诊断 -->
            <div v-if="!(searchList && searchList.length > 0)" class="common-diagnose">
              <p class="title">常用诊断<span class='no-result' v-if="hasNoResult">没有找到相关搜索结果</span></p>
              <ul class="list">
                <li
                  v-for="item in commonList"
                  :class="returnEachCommonLiClass(item)"
                  @click="handleEachCommonLiClick(item)"
                >
                  {{item.diseaseName}}
                </li>
              </ul>
            </div>
          </div>
          <!-- 已选 -->
          <div class="choosed-list-wrap left">
            <div class="title">已选 {{choosedList.length}}/20</div>
            <div class="choosed-list">
              <el-tag
                v-for="(tag, index) in choosedList"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)">
                <div class="text" v-html="tag.alias ? tag.alias : tag.diseaseName"></div>
              </el-tag>
            </div>
          </div>
        </div>

        <div class="dialog-footer">
          <el-button @click="hideSelf">取 消</el-button>
          <el-button type="primary" @click="handleConfirm">确 定</el-button>
        </div>
      </div>
    </div>

    <!-- 已选数量不能超过20个 提示 -->
    <div class="tips-wrap"  @mousedown.prevent="preventDefault">
      <el-dialog
        title="提示"
        :close-on-click-modal="false"
        :visible.sync="limitTipsVisible"
        width="400px"
        center>
        <span>最多只能选择20种诊断</span>
        <span slot="footer" class="dialog-footer">
          <!-- <el-button type="primary" >我知道了</el-button> -->
          <div class="know-confirm" @mousedown.prevent="hideNumLimitTips" >我知道了</div>
        </span>
      </el-dialog>
    </div>

  </div>
</template>

<script>
  import {
    getCommonDiagnoseList,
    goToSearch,
  } from '@/utils/patients/patientsapi';

  export default {
    data() {
      return {
        showDiagnoseModal: false,
        limitTipsVisible: false,
        searchInput: '',
        searchList: [],
        commonList:  [],
        choosedList: [],
        hasNoResult: false,
        page: 1,
        pageSize: 30,
        busy: false,
        noMore: false,
        totalPageNum: 0,
        isInputResponse: false,
        searchFlagTimer: null,
      }
    },
    computed: {
    },
    created() {
      let that = this;
      getCommonDiagnoseList().then(res => {
        // console.log('>>>>>>*********** res: ', res)
        if(res.code == '000000'){
          that.commonList = res.data;
        }else{
          that.$message({
            message: (data && data.message) || '接口出错',
            type: 'warning'
          });
        }
      })
    },
    mounted() {
      // console.log('>>>>>>>>>>>>>>>>>>>>>>>> ', this.showDiagnoseModal)
    },
    watch: {
      showDiagnoseModal(val) {

      }
    },
    methods: {
      showSelf(params) {
        this.showDiagnoseModal = true;
        let list = JSON.parse(JSON.stringify(this.$store.state.patientsDiagnose.selectedDiagList));
        this.choosedList = list;
      },
      hideSelf() {
        this.showDiagnoseModal = false;
        this.choosedList = [];
        this.searchList = [];
        this.searchInput = ''
      },
      preventDefault() {
        // console.log('prevent>>>>>>>>>>>>>>>>>>>')
      },
      hideNumLimitTips() {
        this.limitTipsVisible = false;
      },
      isSearchLiSelected(item) {
        return this.hasItem(this.choosedList, item) > -1 ? true : false;
      },
      handleSearchLiClick(item) {
        this.searchInput = '';
        let hasIndex = this.hasItem(this.choosedList, item);
        if(  hasIndex > -1 ){
          this.choosedList.splice(hasIndex, 1);
        }else{
          // 已选20个后，不能再添加，出Tips
          if( this.choosedList && this.choosedList.length == 20 ){
            this.limitTipsVisible = true;
            return;
          }
          this.choosedList.push(item);
        }
      },
      handleSearchListBlur() {
        this.searchList = [];
        clearTimeout(this.searchFlagTimer);
        // console.log('blur.....')
      },
      handleSearchWrapScroll() {
        // console.log('ddxx88888888888')
        // let that = this;
        // // console.log('val: ', val)
        // // 搜索时
        // that.$nextTick(function(){
        //   let searchListWrap = document.querySelector('.search-list-wrap');
        //   console.log('>>> ', searchListWrap)
        //   if( searchListWrap ){
        //     // searchListWrap.onscroll = function(){
        //       let contentH = document.querySelector('.search-list').offsetHeight;
        //       let viewH = 290;
        //       let scrollTop = searchListWrap.scrollTop;
        //       if( that.canScroll && (contentH - viewH - scrollTop <= 50) ){
        //         console.log('到达临界点，开始加载下一页');
        //         that.canScroll = false;
        //         that.loadMoreSearchData();
        //       }
        //     // }
        //   }
        // })
      },
      // 搜索框中输入文字 时 page=1 pageSize=30
      handleInputSearch() {
        clearTimeout(this.searchFlagTimer);
        let that = this;
        that.page = 1;
        that.isInputResponse = false;
        if( that.searchInput == ''){
          that.searchList = [];
          return;
        }
        that.searchList = [];
        let params = {
          diseaseName: that.searchInput,
          page: 1,
          pageSize: 30,
        };
        this.searchFlagTimer = setTimeout(() => {
          goToSearch(params).then(res => {
            // console.log('>>>>>>*********** search: ', res)
            if(res.code == '000000'){
              that.isInputResponse = true;
              that.totalPageNum = Math.ceil(res.data.total/that.pageSize);  // 总页数
              let list = res.data.icdContentsList || [];
              if(list.length > 0){
                if(that.searchInput == ''){
                  that.searchList = [];
                  return;
                }
                that.searchList = list;
                that.hasNoResult = false;
              }else{
                that.searchList = [];
                that.hasNoResult = true;
              }
            }else{
              that.isInputResponse = false;
              that.searchList = [];
              that.$message({
                message: data.message,
                type: 'warning'
              });
            }
          })
        }, 300)
      },
      // 上拉加载更多
      loadMore() {
        // debugger;
        // console.log('loadmore...')
        let that = this;
        if( !that.isInputResponse ){
          return;
        }
        if( !(that.searchList && that.searchList.length > 0) ){
          return;
        }
        that.busy = true;
        that.page += 1;

        // console.log('请求第几页数据： ', that.page)
        if(that.page > that.totalPageNum){
          // console.log('没有更多了。。。。。');
          that.busy = false;
          that.noMore = true;
          return;
        }else{
          that.noMore = false;
        }
        let params = {
          diseaseName: that.searchInput,
          page: that.page,
          pageSize: that.pageSize,
        }
        setTimeout(()=>{
          goToSearch(params).then(res => {
            // console.log('>>>>>>*********** search: ', res)
            // request ...加载完成后，可以继续滚动加载\
            that.busy = false;
            if(res.code == '000000'){
              let list = res.data.icdContentsList || [];
              if(list.length > 0){
                that.searchList = that.searchList.concat(list);
              }
            }else{
              that.$message({
                message: data.message,
                type: 'warning'
              });
            }
          })
        }, 500)
      },

      handleInputSearchBlur(){
        this.searchList = [];
      },
      handleConfirm() {
        let list = JSON.parse(JSON.stringify(this.choosedList));
        this.$store.dispatch('patientsDiagnose/changeDiagnoseList', list)
        this.showDiagnoseModal = false;
        this.searchInput = '';
        this.searchList = [];
      },
      handleClose(tag) {
        this.choosedList.splice(this.hasItem(this.choosedList, tag), 1);
      },
      returnEachCommonLiClass(item) {
        let hasIndex = this.hasItem(this.choosedList, item);
        if(  hasIndex > -1 ){
          return 'active';
        }else{
          return '';
        }
      },
      handleEachCommonLiClick(item) {
        // console.log('ddd', item);
        let hasIndex = this.hasItem(this.choosedList, item);
        if(  hasIndex > -1 ){
          this.choosedList.splice(hasIndex, 1);
        }else{
          // 已选20个后，不能再添加，出Tips
          if( this.choosedList && this.choosedList.length == 20 ){
            this.limitTipsVisible = true;
            return;
          }
          this.choosedList.push(item);
        }
      },
      hasItem(list, item) {
        for(let i=0; i<list.length; i++){
          if( list[i].icdCode == item.icdCode ){
            return i;
          }
        }
        return -1;
      },

    },
  }
</script>

<style lang="less">
  .scroll-bar{
    /*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
    &::-webkit-scrollbar
    {
        width: 5px;
        height: 5px;
        background-color: #fff;
    }
    /*定义滚动条轨道 内阴影+圆角*/
    &::-webkit-scrollbar-track
    {
        // border-radius: 10px;
        // background-color: rgb(241, 239, 239);
        // background: #fff;
    }
    /*定义滑块 内阴影+圆角*/
    &::-webkit-scrollbar-thumb
    {
        border-radius: 10px;
        -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
        background-color: #bbb;
    }
  }
  .add-diagnose-wrap{
    .fixed-wrap{
      position: fixed;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      overflow: auto;
      z-index: 1000;
      .fullscreen-bg{
        position: absolute;
        width: 100%; height: 100%;
        background: black; opacity: 0.3;
      }
      .add-diagnose-modal{
        position: relative;
        border-radius: 4px;
        width: 910px; padding: 0 30px 0;
        position: fixed;
        left: 50%; margin-left: -455px;
        top: 60px;
        background: #fff;
        .close-btn{
          position: absolute; right: 20px; top: 20px;
          cursor: pointer;
          &:hover{
            color: #409eff;
          }
        }
        .title-text{
          text-align: center;
          line-height: 60px;
        }
        .search-disease{
          width: 370px;
        }
        .main-content{
          overflow: hidden;
          .left{
            float: left;
          }
          .left-box{
            width: 370px;
            height: 300px;
            .common-diagnose{
              width: 100%; height: 300px;
              .title{
                color: #303133;
                font-size: 16px;
                line-height: 40px;
                margin-top: 10px;
                .no-result{
                  font-size: 14px;
                  color: #e6a23c;
                  margin-left: 28px;
                }
              }
              .list{
                width: 100%; height: 250px;
                overflow: hidden;
                overflow-y: scroll;
                .scroll-bar;
                padding: 10px;
                border: 1px solid #DCDFE6;
                li{
                  height: 35px; line-height: 35px; padding: 0 15px;
                  background: #fff;
                  border: 1px solid #dcdfe6;
                  color: #606266;
                  cursor: pointer;
                  font-size: 12px;
                  &.active{
                    color: #fff;
                    background: #409eff;
                    border-color: #409eff;
                  }
                  display: inline-block;
                  margin: 0 10px 10px 0;
                  border-radius: 4px;
                  max-width: 350px;
                  overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
                }
              }
            }
            .search-list-wrap{
              width: 100%; height: 290px; margin-top: 10px;
              border: 1px solid #DCDFE6;
              overflow: hidden;
              overflow-y: scroll;
              .scroll-bar;
              .search-list{
                border-radius: 4px;
                width: 100%;
                padding: 10px;
                li{
                  position: relative;
                  line-height: 30px;
                  overflow: hidden;
                  cursor: pointer;
                  font-size: 12px;
                  &:hover{
                    background: #eee;
                  }
                  .left{
                    width: 310px;
                    float: left;
                    span{
                      color: #ff8429;
                    }
                    .disease-name{
                      font-size: 14px;
                    }
                    .one-line{
                      width: 100%; overflow: hidden;
                      font-size: 12px; color: #aaa;
                      .alias{
                        float: left;
                      }
                      .sign{
                        float: left;
                        margin: 0 5px;
                      }
                      .code{
                        float: left;
                      }

                    }
                  }
                  .right{
                    position: absolute;
                    right: 0;
                    top: 50%;
                    margin-top: -13px;
                    // width: 0px;
                    // float: left;
                    display: inline-block;
                    vertical-align: middle;
                    i{
                      font-size: 24px;
                      color: #449284;
                      font-weight: 700;
                    }
                  }
                  .code{
                    line-height: 30px;
                  }

                }
                .loading{
                    color: #ccc;
                    text-align: center;
                    margin: 0;
                    font-size: 12px;
                    margin-top: 5px;
                  }
              }
            }
          }
          .choosed-list-wrap{
            width: 450px;
            height: 300px;
            margin-left: 30px;
            .title{
              color: #303133;
              font-size: 16px;
              line-height: 40px;
              margin-top: 10px;
            }
            .choosed-list{
              overflow: hidden;
              overflow-y: scroll;
              width: 450px;
              height: 250px;
              padding: 10px;
              border: 1px solid #DCDFE6;
              .scroll-bar;
              .el-tag {
                margin: 0 10px 10px 0;;
                .text{
                  display: inline-block;
                  max-width: 342px;
                  overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
                }
                .el-tag__close{
                  top: -12px;
                }
              }
            }
          }

        }
      }
      .dialog-footer{
        text-align: center;
        margin: 20px auto;
      }

    }
    .tips-wrap {
        .know-confirm{
          width: 98px;
          height: 40px;
          background: #449284;
          border-radius: 4px;
          text-align: center;
          line-height: 40px;
          color: #FFF;
          margin: 0 auto;
          font-size: 14px;
          cursor: pointer;
        }
      }
  }
</style>


