<template>
  <div :style="{height:height-200+'px'}" :class="fullScreen?'pdf':''">
    <div style="margin:auto;padding:5px">
      <div class="menu">
      <!-- <el-link :underline="false" @click="changePage(item.path)"><i class="el-icon-minus"></i></el-link>
      <el-link :underline="false" @click="changePage(5)"><i class="el-icon-plus"></i></el-link> -->
      <!-- <el-link :underline="false" @click="changePage(1)"><i class="el-icon-minus"></i></el-link> -->
      <span>
        <el-tooltip class="item" effect="light" content="缩小页面" placement="top">
          <i class="el-icon-minus" @click="changeSize($event,1)"></i>
        </el-tooltip>
      </span>
      <span>
        <el-tooltip class="item" effect="light" content="放大页面" placement="top">
          <i class="el-icon-plus" @click="changeSize($event,2)"></i>
        </el-tooltip>
      </span>
      <span>
        <el-tooltip class="item" effect="light" content="实际大小" placement="top">
          <i class="iconfont icon-icon-test" @click="changeSize($event,4)"></i>
        </el-tooltip>
      </span>
      <span>
        <el-tooltip class="item" effect="light" content="适应宽度" placement="top">
          <i class="iconfont icon-hengxiangkuozhan" @click="changeSize($event,3)"></i>
        </el-tooltip>
      </span>
      <span v-if="!fullScreen">
        <el-tooltip class="item" effect="light" content="全屏" placement="top">
          <i class="iconfont icon-fangda" @click="changeSize($event,5)"></i>
        </el-tooltip>
      </span>
      <span v-else>
        <el-tooltip class="item" effect="light" content="恢复" placement="top">
          <i class="iconfont icon-icon-suoxiao" @click="changeSize($event,5)"></i>
        </el-tooltip>
      </span>
      <span>
        <el-input-number v-model="num" :controls="false" @change="handleChange" :min="1" :max="total" style="width:50px"></el-input-number>
        <span>/{{ total }}</span>
      </span>
      
    </div>
    </div>
      
    <div style="overflow:auto;background:rgb(229,231,236);" :style="{height:'calc(100% - 30px)'}"  ref="xqBox">
      <div v-for="(item,index) in tableData" :key="index" :id="'xqItem'+index"  style="padding:10px;border-bottom:1px solid  #e6e6e6;" :style="{height:imgHeight+20+'px' }">
        <div v-if="item">
            <el-checkbox :label="item.id" @change="changeSelect(item)" :checked="selected.indexOf(item.id) !== -1 || patentNoList.indexOf(item.patentNo)!== -1">
                <el-link  :disabled="!$permission('/workspace/details')" :class="$permission('/workspace/details')?'':'jinzhi'" :type="item.read === 1 ? 'success' : 'danger'" @click.native.prevent="handleLink(item)">
                    <span v-html="getViewDom(item.patentNo)"></span>
                </el-link>
            </el-checkbox>
        </div> 
        <div v-if="item">
            <el-image v-if="item.pdfFirstPage" :src="item.pdfFirstPage" style="background:white;display: block;margin:0 auto;" :style="{height:imgHeight+'px',width:imgWidth+'px'}"></el-image>
            <!-- <iframe :src="getPDFSrc(item.pdfFirstPage)" frameborder="0" :height="height" width="100%"></iframe> -->
            <div v-else style="margin:0 auto;text-align:center;background:white" :style="{height:imgHeight+'px',width:imgWidth+'px','line-height':imgHeight+'px'}">
              暂无数据
            </div>
        </div>
        <div v-else style="margin:0 auto;text-align:center;background:white" :style="{height:imgHeight+'px',width:imgWidth+'px','line-height':imgHeight+'px'}"></div>
    </div>
    </div>
    
    
  </div>
</template>

<script>
import { patentViewList, patentKeywordsHighlight } from '../mixins'
export default {
  components: {},
  mixins:[patentViewList, patentKeywordsHighlight ],
  props: {
    queryParams:{

    }
  },
  data() {
    return {
        tableData:[],
        height:document.documentElement.clientHeight,
        total:0,
        num:1,
        lastScrollTop:0,
        imgHeight:950,
        imgWidth:671,
        fullScreen:false,
        isLoading:[]
    };
  },
  watch: {
    queryParams(){
        this.getList()
    },
    num(val,oldval){
      //获取可视区高度
      const offsetHeight = this.xqBox.offsetHeight;
      if(offsetHeight<this.imgHeight){
        if(!this.tableData[val-1]){
          this.queryParams.current = val
          this.getList()
        }
      }
      
      
    },
  },
  computed: {
    xqBox() {
      return this.$refs.xqBox;
    }
  },
  created() {},
  async mounted() {
   await this.getList()
    this.$nextTick(() => {
      //监听这个dom的scroll事件
      this.xqBox.addEventListener("scroll", this.isInViewPort);
      this.queryParams.current++
      this.getList()
    });
  },
  methods: {
    handleScroll() {
      //获取dom滚动距离
      const scrollTop = this.xqBox.scrollTop;
      //获取可视区高度
      const offsetHeight = this.xqBox.offsetHeight;
      //获取滚动条总高度
      const scrollHeight = this.xqBox.scrollHeight;
      var data = scrollTop - this.lastScrollTop
      this.lastScrollTop = scrollTop
      //盒子距离顶部的距离
      const boxOffsetTop = this.xqBox.offsetTop
      for (let i =( this.num == this.total)?this.num-2:this.num-1; i < this.tableData.length - 1; data>0?i++:i--) {
        //offsetTop: 获取当前元素到其定位父级（offsetParent）的顶部距离
        let offset_before = this.$el.querySelector("#xqItem" + i).offsetTop - boxOffsetTop;  
        let offset_after = this.$el.querySelector("#xqItem" + (i + 1)).offsetTop - boxOffsetTop;
        // console.log("scrollTop:", scrollTop,"offsetHeight:", offsetHeight,"scrollHeight:", scrollHeight,"offset_before:",offset_before, "offset_after:",offset_after);
        //根据xqItem离顶部距离判断滚动距离落在哪两个item之间
        if (scrollTop >= offset_before+(this.imgHeight - offsetHeight) && scrollTop < offset_after) {
          
          // console.log("scrollTop:", scrollTop,"offsetHeight:", offsetHeight,"scrollHeight:", scrollHeight,"offset_before:",offset_before, "offset_after:",offset_after);
          //判断是否滚动到了底部
          if (scrollTop + offsetHeight >= scrollHeight) {
            // 把距离顶部的距离加上可视区域的高度 等于或者大于滚动条的总高度就是到达底部
            // console.log("已滚动到底部");
            if (this.num < i+1) {
              this.num = i+1;
            }
          } else {
            if(data>0){
              this.num = i+2;
            }else{
              this.num = i+1;
            }
          }
          break;
        }else{
          if(scrollTop == 0){
             this.num =1
          }
        }
      }
    },
    //是否在可视区域
    isInViewPort(){
      //获取可视区高度
      const offsetHeight = this.xqBox.offsetHeight;
      if(this.imgHeight<offsetHeight){
        this.isInViewPort1(this.num)
      }else{
        this.handleScroll()
      }
      
    },
    isInViewPort1(id,sign){
      var dom = this.$el.querySelector("#xqItem" + (id-1))
      if(!dom){
        return false
      }
      //获取dom滚动距离
      const scrollTop = this.xqBox.scrollTop;
      //获取可视区高度
      const offsetHeight = this.xqBox.offsetHeight;
      //获取滚动条总高度
      const scrollHeight = this.xqBox.scrollHeight;
      //获取滚动条总高度
      var data = scrollTop - this.lastScrollTop
      if(data>0){
        if(id != this.total){
          var a = id + 1
        }
      }else{
        if(scrollTop + offsetHeight >= scrollHeight){
          var a = id + 1
        }else{
          var a = id - 1
        }
      }
      this.lastScrollTop = scrollTop
      //盒子距离顶部的距离
      const boxOffsetTop = this.xqBox.offsetTop
      var {top,bottom} = dom.getBoundingClientRect(); 
      top = top - boxOffsetTop
      // console.log(id,dom.getBoundingClientRect())
      // if(data>0){
      //   if(id != this.total){
      //     var a = id + 1
      //   }
      // }else{
      //   if(scrollTop + offsetHeight >= scrollHeight){
      //     var a = id + 1
      //   }else{
      //     var a = id - 1
      //   }
      // }
      if(top<0  && top+this.imgHeight>0){
        this.num = id+1
        // this.isGetList(a)
        // this.isInViewPort1(a)
        if(!sign){
          this.getTenData(id)
        }
      }
      if(top>0 && top<offsetHeight){
        // this.isGetList(a)
        this.isInViewPort1(id-1,true)
        if(!sign){
          this.getTenData(id)
        }
        
      }
      if(top == 0){
        this.num = 1
        // this.isGetList(a)
        // this.isInViewPort1(a)
        if(!sign){
          this.getTenData(id)
        }
      }

    },
    //获取前后数据
    getTenData(num){
      //获取可视区高度
      const offsetHeight = this.xqBox.offsetHeight;
      var a = Math.ceil(offsetHeight / this.imgHeight)
      var num1 = num - a
      var num2 = num + a
      for(var i = num1>0?num1:0;i<num2;i++){
        if(i>this.total){
          break;
        }
        this.isGetList(i)
      }
    },
    isGetList(val){
      if(this.isLoading.indexOf(val-1)==-1){
        this.isLoading.push(val-1)
        this.queryParams.current = val
        this.getList()
      }
      if(this.total - val == 1){
        if(this.isLoading.indexOf(val)==-1){
          this.isLoading.push(val)
          this.queryParams.current = val+1
          this.getList()
        }
      }
    },
     handleChange(val){
      if(this.isLoading.indexOf(val-1)==-1){
        this.isLoading.push(val-1)
        this.queryParams.current = val
        this.getList()
      }
      this.isInViewPort1(val)
      this.tiaozhuan(val-1)
    },
    tiaozhuan(id) {
      const href = `#xqItem${id}`
      const anchor = document.createElement('a');
        anchor.href = href;
        anchor.style.display = "none";
        document.body.appendChild(anchor);
        setTimeout(function () {
          anchor.click();
          document.body.removeChild(anchor);
        }, 66);
        return true;
    },
    changeSize(e,type){
      var width = e.currentTarget.parentNode.parentNode.parentNode.offsetWidth
      var scale = this.imgWidth / this.imgHeight 

      switch(type){
        case 1://变小
          this.imgWidth = this.imgWidth - 100
          this.imgHeight = this.imgWidth / scale
          this.getTenData(this.num)
          // this.getWidth(imgWidth,width)
          break;
        case 2://变大
          this.imgWidth = this.imgWidth + 100
          this.imgHeight = this.imgWidth / scale
          this.getTenData(this.num)
          break;
        case 3://适应宽度
          this.imgWidth = width
          this.imgHeight = this.imgWidth / scale
          break;
        case 4://1：1还原
          this.imgHeight = 950
          this.imgWidth = 671
          break;
        case 5://全屏或恢复
          this.fullScreen = !this.fullScreen
          break;
      }
    },
    async getWidth(maxWidth,width){
      // let size = await this.getImageSize(url);
       const scale = maxWidth / width
       var width1=scale * maxWidth
       this.$set(this,'imgWidth',width1+'px')
       return true
    },
     getImageSize(url) {
     return new Promise(function (resolve, reject) {
         let image = new Image();
         image.onload = function () {
             resolve({
                 width: image.width,
                 height: image.height
             });
         };
       image.onerror = function () { };
         image.src = url;
     });
 },
   async getList(){
    
        let params = JSON.parse(JSON.stringify(this.queryParams))
        params.tree.map(tree => {
            let field = params.field.filter(item => item.key === tree.key)
            if (field.length === 0) {
            params.field.push(tree)
            }
        })
        params.tree = undefined
        params.size = 1
        this.$store.commit('SET_PATENT_PARAMS', params)
       await this.$api.queryPatentPdfFirstPages(params).then(response=>{
            if(response.code == 200){
              this.tableData.length = 70
              // this.num = params.current*params.size
                // this.tableData =this.tableData.concat(response.data.records) 
                if(response.data.records[0].pdfFirstPage){
                  response.data.records[0].pdfFirstPage = this.getPDFSrc(response.data.records[0].pdfFirstPage)
                }
                
                this.tableData.splice(params.current*params.size-1,params.size,Object.freeze(response.data.records[0]))
                this.total = response.data.total
            }
        })
    },
    getPDFSrc(url) {
      let blob = this.base64ToBlob(url)
      return URL.createObjectURL(blob)
    },
    base64ToBlob(url){
      var dataUrl = url
      let bstr = window.atob(dataUrl)
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: "image/png" });
    },
  },
};
</script>
<style lang="scss" scoped>
.menu{
  width: 320px;
  margin: auto;
  i{
    font-size: 20px;
  }
}
.menu>*{
  margin-right:20px;
}
.pdf{
  background: white;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100% !important;
  z-index: 999;
}
</style>