const colourBlend = (c1, c2, ratio) => {
  ratio = Math.max(Math.min(Number(ratio), 1), 0)
  let r1 = parseInt(c1.substring(1, 3), 16)
  let g1 = parseInt(c1.substring(3, 5), 16)
  let b1 = parseInt(c1.substring(5, 7), 16)
  let r2 = parseInt(c2.substring(1, 3), 16)
  let g2 = parseInt(c2.substring(3, 5), 16)
  let b2 = parseInt(c2.substring(5, 7), 16)
  let r = Math.round(r1 * (1 - ratio) + r2 * ratio)
  let g = Math.round(g1 * (1 - ratio) + g2 * ratio)
  let b = Math.round(b1 * (1 - ratio) + b2 * ratio)
  r = ('0' + (r || 0).toString(16)).slice(-2)
  g = ('0' + (g || 0).toString(16)).slice(-2)
  b = ('0' + (b || 0).toString(16)).slice(-2)
  return '#' + r + g + b

}
export const patentQueryMixins = {
  watch: {
    folder() {
      Object.assign(this.$data, this.$options.data())
      this.loadData()
    }
  },
  computed: {
    projectId() {
      return this.$store.state.patent.projectId
    },
    reportId() {
      return this.$store.state.patent.reportId
    },
    folder() {
      return this.$store.state.patent.folder
    },
    params() {
      return this.$store.state.patent.params
    },
    queryData() {
      return this.$store.state.patent.queryData
    },
    closeFieldDrawer() {
      return this.$store.state.project.closeFieldDrawer
    },
    submitIndexSetting() {
      return this.$store.state.project.submitIndexSetting
    }
  },
  mounted() {
    this.loadData()
  },
}

export const changeTranslation = {
  computed:{
    textStyle(){
      return this.$store.state.patent.style
    }
  },
  methods: {
    setStyle(){
      if(!this.textStyle){
        return false
      }
      return 'font-size:'+this.textStyle.size+'px;line-height:'+this.textStyle.lineHeight+';padding:'+this.textStyle.padding[0]+'px '+this.textStyle.padding[1]+'px '+this.textStyle.padding[2]+'px '+this.textStyle.padding[3]+'px'
    },
    getViewDom2(row, key,field) {
      let text = ""
      const change = row.change
      const change2 = row.change2
      switch (key) {
        case "name":
          text = !change ? "name" : "nameOut"
          break
        case "abstractStr":
          text = !change2 ? "abstractStr" : "abstractOut"
          break
      }
      return this.getViewDom(row[text],field)
    },
    handleChange(row, key) {
      switch (key) {
        case "name":
          this.$set(row,'change',!row.change)
          break
        case "abstractStr":
          this.$set(row,'change2',!row.change2)
          break
      }
    },
  }
}

export const patentViewList = {
  mixins: [changeTranslation],
  data() {
    return {
      refresh: true,
      click:false
    }
  },
  props: {
    selected: {
      type: Array
    },
    patentNoList:{
      type: Array
    }
  },
  computedData:{
    projectId() {
      return this.$store.state.patent.projectId
    },
    reportId() {
      return this.$store.state.patent.reportId
    },
  },
  computed: {
   
    params() {
      return this.$store.state.patent.params
    },
    records() {
      return this.$store.state.patent.records
    }
  },
  watch:{
    'patentNoList'(val){
      if(!this.click)
      this.refresh = false
      this.$nextTick(()=>{
        this.click = false
        this.refresh = true
      })
    }
  },
  mounted(){
   
  },
  methods: {
    addRecords(){
      if(!this.projectId){
        this.records.forEach((item,index)=>{
          this.getImageURL1(item)
        })
      }
    },
    getImageURL1(patent){
      var params = {
        patentCell:4,
        patentNo:patent.publicNo,
        appNo:patent.applicationNo,
      }
       this.$api.getPatentPart(params).then(response=>{
            if(response.code == 200){
              if(Object.keys(response.data).length>0 && response.data.image.length>0){
                this.$set(patent,'abstractPath2',response.data.image[0].url)
              }else{
                this.$set(patent,'abstractPath2','q')
              }
              
              this.getHeight(patent.abstractPath2, patent)
            }
        })
    },
    refreshCheckBox() {
      this.refresh = false
      this.$nextTick(() => {
        this.refresh = true
      })
    },
    changeSelect(patent) {
      this.click = true
      const index1 = this.patentNoList.indexOf(patent.patentNo)
      if (index1 === -1) {
        if(this.projectId){
          this.patentNoList.push(patent.patentNo)
        }else{
          this.patentNoList.push(patent.applicationNo)
        }
        
      } else {
        this.patentNoList.splice(index1, 1)
      }
      if(patent.id){
         const index = this.selected.indexOf(patent.id)
          if (index === -1) {
            this.selected.push(patent.id)
          } else {
            this.selected.splice(index, 1)
          }
      }
     
      this.$emit('select-change', this.selected)
      this.$emit('addSelect',patent.applicationNo)
    },
    handleLink(row,index) {
      if(this.projectId){
        var router = this.$router.resolve({
          path: '/workspace/folder/' + row.id,
          query: {
            id: this.projectId,
          }
        })
      }else{
        var router = this.$router.resolve({
          path: '/search/patentDetail',
          query: {
            applicationNo: row.applicationNo,
            patentNo: row.patentNo,
          }
        })
        this.params.index = (index) + ((this.params.current - 1) * this.params.size)
        this.params.name = this.$s.getSession('params').name
      }
      
      this.$s.setSession('params', this.params)
      window.open(router.href, '_blank');
    }
  }
}

export const patentKeywordsHighlight = {
 
  computed: {
    highlight() {
      return this.$store.state.patent.highlight
    },
    contrastList() {
      return this.$store.state.report.contrastList
    },
    piZhuContrastList() {
      return this.$store.state.report.piZhuContrastList
    },
    opinionContrastList() {
      return this.$store.state.report.opinionContrastList
    },
  },
  mounted() {
    window.mouseenter1=this.mouseenter1
     window.mouseleave1=this.mouseleave1
  },
  methods: {
    mouseenter1(e, id, selectType) {
      var dom = document.getElementsByClassName(id)
      var message = this.getMessage(id,selectType)
      // 普通for循环可以拿到dom节点，forEach是拿不到dom节点
      for (let i = 0; i < dom.length - 1; i++){
        dom[i].classList.add('greenColor')
        this.getChildNodesAdd(dom[i].childNodes)
      }
          // e.target是获取当前的,dom获取的是所有的class相同的节点
        e.target.parentNode.classList.add("pizhuLightHeigh");
        if (message.remark) {
          e.target.parentNode.appendChild(this.addPara(message.remark,e));
        }
    },
    // 添加背景色
    getChildNodesAdd(dom) {
      if (dom.length > 0) {
        for (let m = 0; m < dom.length; m++){
          if (dom[m].nodeType == 1) {
            dom[m].classList.add('greenColor')
          }
          if (dom[m].childNodes.length > 0) {
            this.getChildNodesAdd(dom[m].childNodes)
          }
        }
      }
    },
    // 删除背景色
    getChildNodesRemove(dom) {
      if (dom.length > 0) {
        for (let m = 0; m < dom.length; m++){
          if (dom[m].nodeType == 1) {
            dom[m].classList.remove('greenColor')
          }
          if (dom[m].childNodes.length > 0) {
            this.getChildNodesRemove(dom[m].childNodes)
          }
        }
      }
    },
    getMessage(id, selectType) {
      var Id = id.substring(1,id.length)
      var messageItem = {}
      if (selectType=='p') {
        var messageItem= this.piZhuContrastList.find(item => {
          return item.id == Id
        })
      } else if (selectType=='c')  {
        var messageItem=this.contrastList.find(item => {
          return item.id == Id
        })
      }else if (selectType=='o')  {
        var messageItem=this.opinionContrastList.find(item => {
          return item.id == Id
        })
      }else{
        var messageItem=this.contrastList.find(item => {
          return item.id == Id
        })
      }
      return messageItem
    },
    // getMessage(Id, selectType) {
    //   return this.contrastList.find(item => {
    //     return item.id == Id
    //   })
    // },
    addPara(val, e) {
      //创建div标签
       var p = document.createElement("div");
      //添加class
      p.classList.add('showPiZhu')
      if (e.clientY - 200 < 200 && e.clientX + 200 > document.documentElement.clientWidth) {
        p.setAttribute('style','left:-200px')
      }else if ((e.clientX + 200 > document.documentElement.clientWidth && e.clientY + 200 > document.documentElement.clientHeight) || e.clientX + 200 > document.documentElement.clientWidth) {
         p.setAttribute('style','bottom:25px;left:-200px;') 
      } else if((e.clientY + 200 > document.documentElement.clientHeight && e.clientX-200 < 200) || (e.clientY + 200 > document.documentElement.clientHeight && e.clientX-200 > 200)) {
        p.setAttribute('style','bottom:20px;left:10px')
      }
      //创建文本节点
      var text = document.createTextNode(val);
      //将文本节点追加到元素节点中
      p.appendChild(text);
       return p
  },
    mouseleave1(e, id,selectType) {
      var dom = document.getElementsByClassName(id)
      e.target.parentNode.classList.remove("pizhuLightHeigh");
      var message = this.getMessage(id,selectType)
      if (message.remark) {
        document.getElementsByClassName('showPiZhu')[0].remove()
      }
      for (let i = 0; i < dom.length - 1; i++){
        dom[i].classList.remove('greenColor')
        this.getChildNodesRemove(dom[i].childNodes)
      }
    },
    getViewDom1(row, field,key) {
      if(!row){
        return '';
      }
      var html = ''
      if(row.length == 1){
        var str = row[0][key]
        if(!str){
          return ''
        }
        var arr = str.split(/\r\n/g)
        arr.forEach((item,index)=>{
          html = html + `<p class="common" right-sort="${index}"> ${item} </p>`
        })
      }else{
        row.forEach((item,index) => {
          if(item[key]){
             html = html + `<p class="common" right-sort="${index}"> ${item[key]} </p>`
          }
       })
      }
      
     return this.getViewDom(html,field)
    },

    getObject(key,index,text, field) {
      var arr1 = ['color', 'Type', 'Id', 'column', 'index', 'text', 'remark', 'temNode', 'selectType']
      var obj = {
        'piZhuContrastList': ['color','scratchType','id','scratchField','position','text','remark'],
        'contrastList':['color','','id','fields','position','content'],
        'opinionContrastList':['color','scratchType','id','scratchField','position','content'],
      }
      var selectType=['p','c','o']
      var row = this[key]
      if (row.length > 0) {
        for (let i = 0; i < row.length; i++) {
          if (row[i].patentNo == this.patent.publicNo || row[i].patentNo == this.patent.patentNo ) {
            if (row[i][obj[key][3]].indexOf(field) != -1) { 
              var a = {}
              a.Type=1
              obj[key].forEach((item, index1) => {
                if (item) {
                  if (arr1[index1] == 'index') {
                    a[arr1[index1]]=Number(row[i][item])
                  } else {
                    a[arr1[index1]]=row[i][item]
                  }
                  
                }
              });
              a.temNode = text
              a.selectType =selectType[index]
              text = this.AddClass1(a);
            }
           }
        }
        return text
      }
    },
    getViewDom(text, field) {
      if (this.patent && this.patent.publicNo && this.patent.patentNo && field) {
        // SET_PATENT_OPINION_CONTRAST
        var arr = ['piZhuContrastList', 'contrastList', 'opinionContrastList']
        arr.forEach((item, index) => {
          if (this[item].length > 0) {
            text = this.getObject(item, index, text, field)
          }
        });
      
      }
      if (!this.highlight.enable || !text) {
        return text
      }
      
      try {
        this.highlight.configs.map(item => {
          const keywords = item.keywords.split(';')
          for (let keyword of keywords) {
            if (!keyword) {
              continue
            }
            let sText = text
            let num = -1
            const rStr = new RegExp(keyword, "g")
            const rHtml = new RegExp("\<.*?\>", "ig")
            const sKey = `<span style="background: ${item.color};color: #fff">${keyword}</span>`
            const aHtml = sText.match(rHtml)
            sText = sText.replace(rHtml, '{~}')
            sText = sText.replace(rStr, sKey)
            sText = sText.replace(/{~}/g, () => {
              num++
              return aHtml[num]
            })
            text = sText
          }
        })
      } catch (e) {
      }
      return text
    },
    // getViewDom(text, field) {
    //   if(!text){
    //     return ""
    //   }
    //   if (this.contrastList.length > 0) {
    //     for (let i = 0; i < this.contrastList.length; i++) {
    //       if (this.contrastList[i].patentNo == this.patent.patentNo) {
    //         if (this.contrastList[i].scratchField.indexOf(field) != -1) {
    //           // if(this.contrastList[i].id==401){
    //           //   this.contrastList[i].position = 69
    //           // }
    //           var a = {
    //             //  color:"#dff209",
    //             //  Type:1,
    //             //  Id:this.contrastList[i].id,
    //             //  column:this.contrastList[i].fields,
    //             //  index:Number(this.contrastList[i].position),
    //             //  text:this.contrastList[i].content,
    //             //  remark:this.contrastList[i].remark,
    //             //  temNode: text
    //             color: this.contrastList[i].color,
    //             Type: this.contrastList[i].scratchType,
    //             Id: this.contrastList[i].id,
    //             column: this.contrastList[i].scratchField,
    //             index: Number(this.contrastList[i].position),
    //             text: this.contrastList[i].text,
    //             remark: this.contrastList[i].remark,
    //             temNode: text
    //           }
    //           // if (i == 0) {
    //           //   a.pass = true
    //           // } else {
    //           //   a.pass = false
    //           // }
    //           text = this.AddClass1(a);
    //         }
    //       }


    //     }
    //   }

       
    //   if (!this.highlight.enable || !text) {
    //     return text
    //   }
    //   try {

    //     this.highlight.configs.map(item => {
    //       const keywords = item.keywords.split(';')
    //       for (let keyword of keywords) {
    //         if (!keyword) {
    //           continue
    //         }
    //         let sText = text
    //         let num = -1
    //         const rStr = new RegExp(keyword, "g")
    //         const rHtml = new RegExp("\<.*?\>", "ig")
    //         const sKey = `<span style="background: ${item.color};color: #fff">${keyword}</span>`
    //         const aHtml = sText.match(rHtml)
    //         sText = sText.replace(rHtml, '{~}')
    //         sText = sText.replace(rStr, sKey)
    //         sText = sText.replace(/{~}/g, () => {
    //           num++
    //           return aHtml[num]
    //         })
    //         text = sText
    //       }
    //     })

    //   } catch (e) {
    //   }
    //   return text
    // },
    SplitHtmlTag1(el) {
      let temInnerHtml = el.trim();
      let pattern = /<[^>]+>/g;
      let Indexs = [];
      let i = 0
      var match = null
      while ((match = pattern.exec(temInnerHtml)) != null) {
        Indexs[i] = match;
        i++;
      }
      var splitStrings = new Array();
      i = 0;
      var currentIndex = 0;
      for (var index = 0; index < Indexs.length; index++) {
        if (Indexs[index].index > currentIndex) {
          splitStrings[i] = { "text": temInnerHtml.substring(currentIndex, Indexs[index].index), "type": "text" };
          i++;
          splitStrings[i] = { "text": Indexs[index][0], "type": "tag" };
          i++;
        } else {
          splitStrings[i] = { "text": Indexs[index][0], "type": "tag" };
          i++;
        }
        currentIndex = Indexs[index].index + Indexs[index][0].length;
      }
      if (currentIndex < temInnerHtml.length) {
        splitStrings[i] = { "text": temInnerHtml.substring(currentIndex, temInnerHtml.length), "type": "text" };
      }

      return splitStrings;

    },
    AddClass1(selectObject) {
      let el = selectObject.temNode;
      // 将当前页面获取到的字符串进行处理，返回当前页面所有的标签及文本
      var splitStrings = this.SplitHtmlTag1(el);
      let bgColor = selectObject.color;
      if(!bgColor){
        selectObject.color = 'yellow'
      }
      // 添加线及高亮
      let startTag = '<span class="'+ selectObject.selectType + selectObject.Id + '" id="'+ selectObject.selectType + selectObject.Id + '" style="background-color:' + selectObject.color + '">';
      if (selectObject.Type == 0) {
        startTag = '<span class="'+ selectObject.selectType + selectObject.Id + '" id="'+ selectObject.selectType + selectObject.Id + '" style="border-bottom:2px solid ' + selectObject.color + '">';
      }
      if (selectObject.Type == 2) {
        startTag = '<span class = "'+ selectObject.selectType + selectObject.Id + '" id="'+ selectObject.selectType + selectObject.Id + '" style = "text-decoration-line: underline;text-decoration-style: wavy ;text-decoration-color: ' + selectObject.color + '">';
      }
      var a = 'icon-xinxi3'
      switch(selectObject.selectType){
        case 'p'://批注
          a = 'iconfont icon-xinxi3'
          break;
        case 'c'://对比
          a = 'el-icon-location-outline'
          break;
        case 'o'://陈述意见
          a = 'iconfont icon-xinxi2'
          break;
      }
      var imgTag = '<span  class="'+ selectObject.selectType + selectObject.Id + '" style="background-color:white !important;"><i class="'+ a +'" style="vertical-align: super;background-color:white !important;" onclick="selectMark(\''+ selectObject.selectType + selectObject.Id + '\',\'' + selectObject.selectType + '\')"  onmouseenter="mouseenter1(event,\''+ selectObject.selectType + selectObject.Id + '\',\'' + selectObject.selectType + '\')"  onmouseleave="mouseleave1(event,\''+ selectObject.selectType + selectObject.Id + '\',\'' + selectObject.selectType + '\')"></i></span>';
      if(selectObject.selectType == 'r'){
        imgTag = '<span class="'+ selectObject.selectType + selectObject.Id + '" style="background-color:white !important;"><i class="el-icon-delete" style="vertical-align: super;background-color:white !important;" onclick="deleteFeature(\''+ selectObject.selectType + selectObject.Id + '\',\'' + selectObject.selectType +'\')"></i></span>'
      }
      let endTag = '</span>';
      let elText = '';

      splitStrings.forEach(function (item) {
        if (item.type == 'text') {
          elText = elText + item.text;
        }
      });
      let Indexs = [];
      let i = 0
      if (selectObject.index < 0) {
        let pattern = new RegExp(selectObject.text.replace(/[\r\n]/g, "").replace(/\ +/g, ""), "g");
        while ((match = pattern.exec(elText)) != null) {
          Indexs[i] = match;
          i++;
        }
      } else {
        Indexs[i] = [selectObject.text];
        Indexs[i].index = selectObject.index;
      }
      Indexs.forEach(function (match) {
        let currentIndex = 0;
        let temSplitStrings = new Array();
        splitStrings.forEach(function (item) {
          if (item.type == 'text') {
            if (item.text) {
              if (match.index >= currentIndex && match.index < (currentIndex + item.text.length)) {
                if (selectObject.column.indexOf('权利要求') != -1) {
                  item.text = item.text.replace(/\r/g, ' ')
                  if (item.text.match(/\r/g)) {
                    match.index -= 1
                  }

                }
                if (selectObject.column.indexOf('说明书') != -1) {
                  // var b = selectObject.temNode.replace(/<[^>]+>/g, '')
                  // if (b.substring(0, match.index).indexOf('\r') == -1) {
                  //   var a = b.substring(0, match.index).match(/\n/g)
                  //   if (a) {
                  //     match.index -= a.length
                  //   }
                  // }
                  item.text = item.text.replace(/\r/g, "")
                }
                
                if ((match.index + match[0].length) <= (currentIndex + item.text.length) && item.text.indexOf(match[0]) != -1) {

                  if (match.index > currentIndex) {
                    temSplitStrings.push({ text: item.text.substring(0, match.index - currentIndex), type: 'text' });
                  }
                  temSplitStrings.push({ text: startTag, type: 'tag' });
                  temSplitStrings.push({ text: match[0], type: 'text' });
                  temSplitStrings.push({ text: imgTag, type: 'tag' });
                  // }
                  temSplitStrings.push({ text: endTag, type: 'tag' });

                  if ((match.index + match[0].length) < (currentIndex + item.text.length)) {
                    temSplitStrings.push({ text: item.text.substring((match.index + match[0].length) - currentIndex), type: 'text' });
                  }
                } else {
                  if (item.text.indexOf(match[0]) != -1) {
                    if (match.index > currentIndex) {
                      temSplitStrings.push({ text: item.text.substring(0, match.index - currentIndex), type: 'text' });
                    }
                    if (temSplitStrings.length > 1) {
                      // if (temSplitStrings[temSplitStrings.length - 2].text.substr(1, 1) != '/') {
                      //   let index = temSplitStrings[temSplitStrings.length - 2].text.indexOf('background-color:')
                      //   let colorStr = temSplitStrings[temSplitStrings.length - 2].text.substr(index + 17, 7)
                      //   let index2 = startTag.indexOf('background-color:')
                      //   let colorStr2 = startTag.substr(index2 + 17, 7)
                      //   let acolor = colourBlend(colorStr, colorStr2, 0.5)
                      //   let startTag2 = "<span style='background-color:" + acolor + "'>"
                      //   temSplitStrings.push({ text: startTag2, type: 'tag' });
                      // } else {
                      //   temSplitStrings.push({ text: startTag, type: 'tag' });
                      // }
                      temSplitStrings.push({ text: startTag, type: 'tag' });
                    } else {
                      temSplitStrings.push({ text: startTag, type: 'tag' });
                    }

                    temSplitStrings.push({ text: item.text.substring(match.index - currentIndex), type: 'text' });
                    temSplitStrings.push({ text: endTag, type: 'tag' });
                  } else {
                    // console.log(temSplitStrings,match.index,item.text,currentIndex,match[0])
                    // debugger
                    temSplitStrings.push({ text: item.text.substring(0, match.index - currentIndex), type: 'text' });
                    temSplitStrings.push({ text: startTag, type: 'tag' });
                    temSplitStrings.push({ text: item.text.substring( match.index - currentIndex,item.text.length), type: 'text' });
                    // temSplitStrings.push({ text: imgTag, type: 'tag' });
                    temSplitStrings.push({ text: endTag, type: 'tag' });
// return false
                    // temSplitStrings.push(item);
                  }
                }
              } else {
                // console.log(temSplitStrings,match.index,item.text,currentIndex,match[0])
                if ((match.index + match[0].length) <= (currentIndex + item.text.length) && (match.index + match[0].length) > currentIndex) {
                  // if (temSplitStrings[temSplitStrings.length - 1].text.substr(1, 1) != '/') {
                  //   let index = temSplitStrings[temSplitStrings.length - 1].text.indexOf('background-color:')
                  //   let colorStr = temSplitStrings[temSplitStrings.length - 1].text.substr(index + 17, 7)
                  //   let index2 = startTag.indexOf('background-color:')
                  //   let colorStr2 = startTag.substr(index2 + 17, 7)
                  //   let acolor = colourBlend(colorStr, colorStr2, 0.5)
                  //   let startTag2 = "<span style='background-color:" + acolor + "'>"
                  //   temSplitStrings.push({ text: startTag2, type: 'tag' });
                  // } else {
                  //   temSplitStrings.push({ text: startTag, type: 'tag' });
                  // }
                  temSplitStrings.push({ text: startTag, type: 'tag' });
                  temSplitStrings.push({ text: item.text.substring(0, match.index + match[0].length - currentIndex), type: 'text' });

                  temSplitStrings.push({ text: imgTag, type: 'tag' });

                  temSplitStrings.push({ text: endTag, type: 'tag' });
                  if ((match.index + match[0].length) < (currentIndex + item.text.length)) {
                    temSplitStrings.push({ text: item.text.substring((match.index + match[0].length - currentIndex)), type: 'text' });
                  }
                } else {
                  if (match.index < currentIndex && (match.index + match[0].length) >= (currentIndex + item.text.length)) {

                    temSplitStrings.push({ text: startTag, type: 'tag' });
                    temSplitStrings.push(item);
                    temSplitStrings.push({ text: endTag, type: 'tag' });
                  } else {

                    temSplitStrings.push(item);
                  }
                }
              }

              currentIndex = currentIndex + item.text.length;
            } else {
              temSplitStrings.push(item);
            }
          } else {
            temSplitStrings.push(item);
          }
        });

        splitStrings = temSplitStrings;
      });

      let temInnerHtml = '';
      splitStrings.forEach(function (item) {
        temInnerHtml = temInnerHtml + item.text;
      });
      return temInnerHtml;

    },
  }
}


//查看专利详情
export const PatentDetails = {
  methods:{
    toPatentDetails(patentNo, row) {
      const router = this.$router.resolve({
        path: '/patentDetails',
        query:{
          patentNo: patentNo,
          reportId:row?row.id:(this.reportId?this.reportId:''),
          projectId:true
        }
      })
      window.open(router.href, '_blank')
    }
  }
}