<template>
  <div class="patent-articles-patent-right height_100" @mouseup="mouseup">
    <el-container>
      <el-header class="basic_header">
        <el-tabs v-model="name" @tab-click="handleClick"  style="width:100%;">
          <el-tab-pane v-for="item in tabs" :key="item.label" :label="item.label"  :name="item.name">
            <span slot="label">
              <span>{{ item.label }}</span>
              <span v-if="item.icon && !outside" class="margin-left_10">
                <i :class="item.icon" @click.stop="exportData(item.value)"></i>
              </span>
            </span>
          </el-tab-pane>
        </el-tabs>
        <div v-if="!outside">
          <el-checkbox v-model="checkedRightTree" @change="changeShowRightTree">权要树</el-checkbox>
        </div>
      </el-header>
      <el-main style="overflow: auto;" ref="content">
        <div class="height_100" v-loading="loading" v-if="!checkedRightTree"  :style="setStyle()" >
          <template v-if="name != 2">
            <div  class="height_100" v-html="getContentOrContentOut(this.patent.claimTranslate, tabItem.field,name == 2?'权利要求原文':'权利要求'+tabItem.label,'claim')" :data-type="name == 2?'权利要求原文':'权利要求'+tabItem.label" ></div>
          </template>
          <template v-else>
            <div class="height_100 claim">
              <div v-equal_heights="'yiwen'" class="height_100" v-html="getContentOrContentOut(this.patent.claimTranslate,  tabItem.field,name == 2?'权利要求原文':'权利要求'+tabItem.label,'claim')" :data-type="name == 2?'权利要求原文':'权利要求'+tabItem.label" ref="yuanwen"></div>
              <div class="height_100" v-html="getContentOrContentOut(this.patent.claimTranslate,  'contentOut','权利要求译文','claim')" :data-type="'权利要求译文'" ref="yiwen"></div> 
            </div>
            
          </template>
          
        </div>
        
        <div v-else class="height_100">
          <my-view>
            <div slot="left">
              <myTree :list="patent.patentRightTree" style="height: 100%" :props="{
                name:'content',
                children:'children'
              }" nodeKey="sort" :expends="expends">
                <template v-slot:default="data">
                  <div v-if="tabItem.name == 0 || tabItem.name == 2" v-html="data.data.content"></div>
                  <div v-if="tabItem.name == 1" v-html="translateContent(data.data)"></div>
                  <div v-if="tabItem.name == 2" style="background:#f3f4f8;user-select:none;"  v-html="translateContent(data.data)">
                  </div>
                </template>
              </myTree>
            </div>
            <div slot="right" style="position: relative;">
              <div id="charts" style="max-width: 100%; min-width: 300px;position:relative;padding-top: 10px;"  v-if="show">
                <div v-for="(item,index) in this.patent.patentRightTree" :key="index" :id="'chart'+index" style="width:500px;margin:0 auto;"></div>
              </div>
              <div style="position:absolute;top:10px;right:20px;">
                <el-link type="primary" @click="imageDownLoad">下载为图片</el-link>
              </div>
            </div>
          </my-view>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { patentDetails } from './mixins';
import {translate} from './mixins/translate'
import html2canvas from "html2canvas"
export default {
  mixins: [patentDetails,translate],
  data() {
    return {
      expends: [],
      show:false,
      isClickId: "",
      height: null,
      fullHeight: document.documentElement.clientHeight,
      scrollTop:0,
      isClick:false,
      checkedRightTree:false,
      patentField:3,
      translate:{}
    };
  },
  watch: {
    // fullHeight() {
    //   this.refresh();
    // },
    patentNo() {
        this.showTabs()
        this.translate = {}
        if(this.checkedRightTree){
          this.show = false
          this.expends = []
          this.isClickId  = ''
          this.$nextTick(()=>{
            this.changeShowRightTree()
            this.handleClick()
          })
        }else{
          this.initData();
        }
        this.scrollToTop()
    },
    name(){
      if(!this.checkedRightTree){
        this.show = false
      }
    },
  },
  created() {
    window.addEventListener("resize", this.handleResize);
  },
  mounted() {
    this.handleResize();
    this.initData();
  },
  methods: {
    scrollToTop(){
      this.$nextTick(()=>{
        var dom = this.$refs.content.$el
        dom.scrollTo({
          top:0,
          behavior: "instant"
        })
      })
      
    },
    changeShowRightTree(){
      this.show = true
      if(!this.checkedRightTree){
        this.initData()
        this.handleClick()
        return
      }
      if (this.checkedRightTree && !this.patent.patentRightTree) {
        let params = {
          patentNo: this.patent.patentNo,
          appNo: this.patent.rowApplicationNo,
        }
        this.$api
          .getPatentRightTree(params)
          .then((response) => {
            if (response.code == 200) {
              this.$set(this.patent, "patentRightTree", response.data.data);
              this.$nextTick(()=>{
                this.getEchart();
              })
             
            }
          });
      } else if(this.checkedRightTree && this.patent.patentRightTree) {
        this.$nextTick(()=>{
          this.getEchart();
        })
      }
    },
    translateContent(item){
      
      if(item.translateContent){
        return item.translateContent
      }
      if(item.sort != 0 && !item.sort){
        return item.translateContent || ''
      }
      if(this.translate[item.sort]){
        return item.translateContent || ''
      }
      this.translate[item.sort] = true
      var params = {
        patentNo:this.patent.patentNo,
        patentField:this.patentField,
        order:item.sort
      }
      this.$api.getTranslateOrder(params).then(res=>{
        if(res.code == 200){
          var translate = res.data
          var obj = {
            translateContent:'无译文'
          }
          if(translate.length>0){
            var obj = translate[0]
          }
          this.$set(item,'translateContent',obj.translationContent)
        }
      })
    },
    imageDownLoad(){
      var dom = document.getElementById('charts')
      html2canvas(dom).then(canvas => {
        // 转成图片，生成图片地址
         var imgUrl = canvas.toDataURL("image/png");
         var blob = this.base64ToBlob(imgUrl)
         var eleLink = document.createElement("a");
          eleLink.href = URL.createObjectURL(blob); // 转换后的图片地址
          eleLink.download = "权要树";
          document.body.appendChild(eleLink);
          // 触发点击
          eleLink.click();
          // 然后移除
          document.body.removeChild(eleLink);
        
        // const link = document.createElement('a')
        // let url = URL.createObjectURL(blob)
        // link.href = url
        // link.download = item.url.substring(0,item.url.indexOf('?'))
        // link.click()
    });
    },
    base64ToBlob(data){
      var dataUrl = data.replace('data:image/png;base64,','')
      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" });
    },
    getData(data) {
      data.forEach((item) => {
        item.name = Number(item.sort) + 1;
        if (item.children && item.children.length > 0) {
          this.getData(item.children);
        }
      });
    },
    getEchart() {
      var data = JSON.parse(JSON.stringify(this.patent.patentRightTree));
      this.getData(data);
      var that = this
      data.forEach((item,index) => {
        var option = {
        // height: "100%",
        backgroundColor: "#fbfbfb",
        series: [
          {
          itemStyle: {
            normal: {
              color: "#06c",
              borderColor: "#06c",
            },
            emphasis: {
              borderColor: "#06c",
              color: "#06c",
            },
          },
          lineStyle: {
            color: "#2979ff",
          },
          type: "tree",
          data: [item],
          // top: "1%",
          left: "100px",
          // bottom: "1%",
          right: "100px",
          symbolSize: 0,
          symbol: "emptyCircle",
          label: {
            position: "left",
            verticalAlign: "middle",
            align: "right",
            color: "#293c55",
            margin: [2, 4],
            borderWidth: 1,
            borderColor: "#aaa",
            backgroundColor: "white",
            borderRadius: 2,
            padding: [5, 4],
            rich: {
              keywords: {
                color: "red",
                fontSize: "12",
              },
              index: {
                fontSize: 12,
                color: "#2979ff",
                position: "10%",
              },
            },
            formatter: function(data, data1) {
              // rgb(178, 215, 255)
              if(data.data.sort+'' == that.isClickId){
                data.data.label = {
                  fontSize: 12,
                  padding: [5, 4],
                  backgroundColor: 'rgb(178, 215, 255)',
                  borderColor: '#aaa',
                  color: '#293c55',
                }
              // }else{
                // data.data.label = {
                //   fontSize: 12,
                //   padding: [5, 4],
                //   backgroundColor: 'white',
                //   borderColor: '#aaa',
                //   color: '#293c55',
                // }
              }
            },
          },
          leaves: {
            label: {
              position: "right",
              verticalAlign: "middle",
              align: "left",
            },
          },

          expandAndCollapse: false,
          animationDuration: 550,
          animationDurationUpdate: 750,
        }
        ],
      };
      this.sendingChart(option,index);
      });
      
    },
    sendingChart(option,index) {
      var myChart = this.$echarts.init(document.getElementById("chart"+index));
      myChart.clear();
      var option = option;
      option && myChart.setOption(option);
      myChart.on("click", (param) => {
        this.showRightPosition(param.data.sort);
        var dom = document.getElementById("chart")
        if(!this.isClick){
          this.scrollTop = dom.scrollTop
        }
        this.isClick = true
       this.show = false
        this.$nextTick(()=>{
          this.show = true
          this.$nextTick(()=>{
            this.getEchart()
            this.isClick = false
            document.getElementById("chart").scrollTop = this.scrollTop
          })
          
        })
      });
      const eleArr = Array.from(new Set(myChart._chartsViews[0]._data._graphicEls))
        const itemHeight = 50
        const currentHeight = itemHeight * (eleArr.length-1) || itemHeight
        const newHeight = Math.max(currentHeight,itemHeight)
        myChart.resize({
          height:newHeight+50
        })

    },
    showRightPosition(id) {
      var index = this.expends.indexOf(id);
      if (index == -1) {
        this.expends.push(id);
      }else{
        this.expends.splice(1,index)
        this.expends.push(id);
      }
      if (this.isClickId + "") {
        var dom1 = document.getElementById("right" + this.isClickId);
        dom1.style.background = "";
      }
      this.isClickId = id;
      var dom = document.getElementById("right" + id);
      dom.style.background = "rgb(178, 215, 255)";
      this.$nextTick(()=>{
        this.tiaozhuan(id)
      })
      
    },
    tiaozhuan(id) {
      const href = `#right${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;
    },
    initData(sign=false) {
      if(sign){
        this.patent.claimTranslate = null
      }
        if(this.patent.claimTranslate && this.patent.claimTranslate.data & this.patent.claimTranslate.data.length >= 0){
          return false
        }
        if (this.outside) {
          var params = {
            // patentCell: 1,
            appNo: this.patent.rowApplicationNo,
            // pageNum: 1,
            // pageSize:10,
            // appNo: this.patent.applicationNo,
          };
          this.loading = true
          this.$api.queryExternalClaim(params).then((response) => {
            if (response.code == 200) {
              var data = []
              response.data.claimContent.forEach(item=>{
                var obj = {
                  originalContent:item.text_content.replace(/(\r\n)+/g,'<br/>').replace(/(\t)+/g,'<br/>')
                }    
                data.push(obj)
              })
              this.$set(this.patent, "claimTranslate", {
                data:data
              });
              // this.$set(this.patent, "claim", response.data.claimContent);
              this.loading = false
            }
          }).catch(error=>{
            this.loading = false
          })
        }else{
          if(!this.patent.claimTranslate){
            var params = {
              patentNo:this.patent.patentNo,
              patentField:this.patentField
            }
            this.loading = true
            this.$api.getTranslate(params).then(res=>{
              if(res.code == 200){
                this.loading = false
                this.getDataSign = true
                var data = res.data
                this.$set(this.patent, "claimTranslate", { 
                  data :data
                });
              }
            }).catch(error=>{
              this.loading = false
            })
          }
          
        }
    },
    
    handleResize(event) {
      this.fullHeight = document.documentElement.clientHeight;
      this.height = this.fullHeight - 350;
    },
  },
};
</script>

<style lang="scss">
.patent-articles-patent-right {
  // margin-bottom: 20px;
  .common {
    // font-size: 14px;
    margin-top: 0;
    padding-right: 5px;
    word-break: break-all;
  }
  .title {
    font-weight: bold;
    border-bottom: 1px solid #e6e6e6;
    padding-bottom: 5px;
    margin-top: 0;
  }
}
.highlightText{
  background: #c7ebaa !important;
}
</style>
<style lang="scss" scoped>

.claim{
  display: flex;
  &>div{
    width: 100%;
    // overflow: auto;
    padding: 0 5px;
  }
  
}


</style>