import { patentKeywordsHighlight } from '../../components/mixins'
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 commonMixins = {
  props: ['patent', 'reportId', 'patentId','projectId','patentNo'],
  mixins: [patentKeywordsHighlight],
  data() {
    return {
      style:{
        height:'100%',
        width:'100%'
      },
      size:{}
    }
  },
  mounted() {
    window.addEventListener('resize', this.changeWidth)
  },
  methods: {
    changeWidth() {
      var dom = document.querySelector('.picture')
       var maxWidth = null
       var maxHeight = null
       if(dom){
         maxWidth =  dom.clientWidth - 30
         maxHeight = 200
       }else{
          maxWidth =  120
          maxHeight = 150
       }
       var size = JSON.parse(JSON.stringify(this.size))
       const scale = Math.min(maxWidth / size.width, maxHeight / size.height); 
       size.width=scale * size.width
       size.height=scale * size.height
       this.$set(this.style,'width',size.width+'px')
      this.$set(this.style, 'height', size.height + 'px')
      if (this.patent) {
        this.$set(this.patent,'imgWidth',size.width+'px')
         this.$set(this.patent,'imgHeight',size.height+'px')
      }
    },
    getImagePath(url) {
      if (!url) {
        return ''
      }
      if(this.reportId){
        var url1 = this.$p2 + url
      }else{
        var url1 = url
      }
      return url1
    },
    getImagePath1(patent) {
      if(Object.keys(patent).length==0){
        return ''
      }
      if(!patent.abstractPath){
        return this.getErrorImage(patent)
       }
       var url = this.$p2 + patent.abstractPath
       this.$set(patent,'abstractPath2',url)
       this.getHeight(url, patent)
      return url
    },
    async getHeight(url,patent){
      let size = await this.getImageSize(url);
      var dom = document.querySelector('.picture')
      
       var maxWidth = null
       var maxHeight = null
      if (dom) {
         maxWidth =  dom.clientWidth -5
         maxHeight = dom.clientHeight -5
       }else{
          maxWidth =  120
          maxHeight = 150
      }
       const scale = Math.min(maxWidth / size.width, maxHeight / size.height);  
       this.size = size
       size.width=scale * size.width
       size.height=scale * size.height
       this.$set(this.style,'width',size.width+'px')
      this.$set(this.style, 'height', size.height + 'px')
      this.$set(patent,'imgWidth',size.width+'px')
       this.$set(patent,'imgHeight',size.height+'px')
      
       return size
    },
    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 () {
             //  reject(new Error('error'));
          };
          image.src = url;
      });
  },
    getErrorImage(patent){
      if(Object.keys(patent).length==0){
        return ''
      }
      if(!patent.publicNo){
        return ''
      }
      var cc =  patent.publicNo.substring(0,2)
      if(patent.publicAccreditDate){
        var date = patent.publicAccreditDate.replace(/-/g,'')
      }else{
        var date = patent.publicDate.replace(/-/g,'')
      }
        var NR = patent.publicNo.substring(2,patent.publicNo.length)
        var KD = patent.publicNo.substring(patent.publicNo.length-2,patent.publicNo.length)
        var a = 'http://worldwide.espacenet.com/espacenetImage.jpg?flavour=firstPageClipping&locale=en_EP&FT=D&date='+ date +'&CC='+ cc +'&NR='+ NR +'&KD='+ KD +'&bg='
      return a
    }
  }
}

export const addContrast = {
  props:['reportId','activeName','evidenceFlieId','signPatentNo','reportType','taskId','type','projectId'],
  data() {
    return {
      mX: 0,
      mY: 0,
      isSelecting: false,
      anchorOffset: 0,
      currentSelectObj:{},
      contrast: {},
      currentColor:null,
      duiBiCurrentSelectObj: {},
      name:this.activeName,
    }
  },
  computed: {
    index() {
      return JSON.stringify(this.$store.state.patent.index)
    },
    contrastList() {
      return this.$store.state.report.contrastList
    },
    opinionContrastList() {
      return this.$store.state.report.opinionContrastList
    },
  },
  watch: {
    index(val) {
      var index1 = JSON.parse(val)
      this.currentColor = index1.color
    },
    activeName(val) {
      this.name = val
    },
  },
  mounted() {
    window.pizhu = this.pizhu
    window.hiddenPizhu = this.hiddenPizhu
    window.selectMark = this.selectMark
    window.addDuiBi = this.addDuiBi
  },
  methods: {
    // 点击对比按钮
    addDuiBi() {
      this.duiBiCurrentSelectObj=this.$store.state.patent.index
      // open打开弹窗
      if (this.duiBiCurrentSelectObj.Id) {
        this.duiBiCurrentSelectObj.patentNo = this.duiBiCurrentSelectObj.pno
        this.$emit('openContrast',this.duiBiCurrentSelectObj)
      }
    },
    //点击图标回显数据
    selectMark(id, selectType) {
      if(!this.$reportPermission(this.reportId,[0,1])){
        return false
      }
      var Id = id.substring(1,id.length)
      if (selectType=='p') {
        var index = this.piZhuContrastList.findIndex(item => {
        if (item.id == Id) {
          // 清空currentSelectObj，否则Id与id同时存在
          this.currentSelectObj = {}
          this.$store.commit("SET_PATENT_INDEX", this.currentSelectObj)
          this.contrast = item
          this.$store.commit('SET_PATENT_INDEX', this.contrast)
        }
        return item.id == Id
        })
        if (index != -1) {
          this.showPizhu()
        }
      } else if (selectType == 'c') {
        let a=this.contrastList.find(item => {
          return item.id==Id
        })
        this.$emit('openContrast', a)
      } else if (selectType == 'o') {
        let a=this.opinionContrastList.find(item => {
          return item.id==Id
        })
        this.$emit('openOpinioncontrast', a)
      }
      
    },
    mousemove(e) {
      this.mX = e.pageX;
      this.mY = e.pageY;
    },
    mouseup(e) {
      sessionStorage.mY = this.mY
      sessionStorage.mX = this.mX
      this.isSelecting = true;
      if (this.isSelecting) {
        this.isSelecting = false;
        let selectObj = document.getSelection();
        this.anchorOffset = 0;
        let temSelectObj = this.getSelectobj(selectObj);
        var tempdt = this.getColumnName(selectObj.anchorNode);
        if (tempdt != undefined && selectObj.toString() != '') {
          this.currentSelectObj = temSelectObj;
          this.currentSelectObj.color = this.currentColor;
          this.currentSelectObj.Type = 0;
          this.currentSelectObj.patentNo = this.patent.patentNo
          // rangeId（专题库id/报告id）
          this.currentSelectObj.rangeId = this.reportId
          // 创建来源（默认0/专题库1/报告2）
          this.currentSelectObj.createFrom = 2
          // this.showPizhu();
          this.currentSelectObj.remark = ''
        }
        else {
          this.currentSelectObj = {};
        }
        if (this.currentSelectObj.Id) {
          var a = JSON.parse(this.index)
          a.Id = this.currentSelectObj.Id
          a.patentNo = this.currentSelectObj.patentNo
          a.pno = this.patent.patentNo
          a.text = this.currentSelectObj.text
          a.rangeId = this.reportId
          a.scratchField = this.currentSelectObj.column
          a.position = this.currentSelectObj.index
          a.id = null
          a.remark = null
          // a.color = this.currentSelectObj.color
          a.createFrom = this.reportId?2:0
          a.Type = 0

          a.rightSort=this.currentSelectObj.rightSort
          a.evidenceFlieId = this.evidenceFlieId
          a.signPatentNo = this.signPatentNo
          a.reportType = this.reportType ?this.reportType:this.type
          a.taskId = this.taskId
          a.rightPosition = this.currentSelectObj.rightPosition
          this.$store.commit("SET_PATENT_INDEX", a)
          this.showPizhu()
        }
      }
    },
    // 打开批注框
    pizhu() {
      if (this.contrast.id == undefined) {
        this.currentSelectObj = JSON.parse(this.index)
      }
      if (this.currentSelectObj.Id != undefined || this.contrast.id != undefined) {
        // 划词进入
        // if (this.currentSelectObj.Id != undefined) {
        //   console.log(2,this.currentSelectObj);
        //   this.$store.commit('SET_PATENT_INDEX', this.currentSelectObj)
        // }
        this.currentSelectObj.Type = 2;
        this.hiddenPizhu();
        this.showPizhu2()
        this.contrast = {}
      }
    },
    showPizhu2() {//展示批注
      let dl = document.getElementsByClassName("pizhu");
      let mX = sessionStorage.mX
      let mY = sessionStorage.mY
      if ((document.body.clientWidth - mX - 380) < 0) {
        mX = document.body.clientWidth - 390;
      }
      if ((document.body.clientHeight - mY - 40) < 0) {
        mY = document.body.clientHeight - 40;
      }
      if ((document.body.clientHeight - mY) < 420) {
        mY = mY - 410
      }
      if ((document.body.clientWidth - mX) < 330) {
        mX = mX - 330
      }
      dl[0].setAttribute("style", "user-select:none;box-shadow: 10px 10px 5px #888888;display:block;position:absolute;left:" + mX.toString() + "px;top:" + mY.toString() + "px;background-color: #F7EED6;border-radius: 15px 15px;padding: 10px;width:380px;z-index: 2;");
    },
    showPizhu() {//展示菜单
      let mX = sessionStorage.mX
      let mY = sessionStorage.mY
      let dl = document.getElementsByClassName("caidan");
      if ((document.body.clientWidth - mX - 420) < 0) {
        mX = document.body.clientWidth - 420;
      }
      if ((document.body.clientHeight - mY - 40) < 0) {
        mY = document.body.clientHeight - 40;
      }
      dl[0].setAttribute("style", "opacity:0.95;box-shadow: 10px 10px 5px #888888;display:block;position:absolute;left:" + mX.toString() + "px;top:" + mY.toString() + "px;background-color: white;border-radius: 15px 15px;height:30px;display: flex;align-items: center;padding: 10px;user-select:none");
    },
    // 关闭菜单
    hiddenPizhu() {
      let dl = document.getElementsByClassName("caidan");
      dl[0].setAttribute("style", "display:none;");
    },
    getSelectobj(selectObj) {
      var temNode = selectObj.anchorNode;
      var a = temNode.parentElement
      NotIncludeDataType(a)
      function NotIncludeDataType(node) {
        if (node.getAttribute("data-type") != null) {
          temNode = node
        } else {
          if(node.parentElement){
            NotIncludeDataType(node.parentElement);
          }else{
            temNode = temNode.parentElement
          }
          
        }
      }
      var rightSort = null
      if(temNode.getAttribute("data-type") == null){
        return false
      }
      if (this.reportType == 7 && temNode.getAttribute("data-type").includes('权利要求')) {
        var node1 = null
        getRightSort(a)
        function getRightSort(node) {
          if (node.getAttribute("right-sort") != null) {
            rightSort = node.getAttribute("right-sort")
            node1 = node
          } else {
            getAttribute(node.parentElement);
          }
        }
        var rightPosition = this.getColumn(node1, selectObj)
      }
      this.getColumn(temNode, selectObj);
      this.isFirst = true
      return { "Id": this.uuid(), "column": temNode.getAttribute("data-type"), "index": this.anchorOffset, "text": selectObj.toString(), 'temNode': temNode.innerHTML,'rightSort':rightSort,'rightPosition':rightPosition };
    },
    getColumn(node, selectObj) {
      var baseNode = this.getColumnNode(node);
      var anchorNodePosition = this.getPosition(baseNode, selectObj.anchorNode, selectObj.anchorOffset);
      var focusNodePosition = this.getPosition(baseNode, selectObj.focusNode, selectObj.focusOffset);
      var num = Math.min(anchorNodePosition, focusNodePosition)
      this.anchorOffset = num
      return num;
    },
    getColumnNode(node) {
      //获取节点所在的栏位节点
      if (node != null) {
        if (node.nodeType != 3 && node.getAttribute("data-type") != null) {
          return node;
        } else {
          if (node == document.root) {
            return node;
          } else {
            return this.getColumnNode(node.parentNode);
          }
        }
      }
    },
    getNodes(baseNode, path) {
      // 拿到所有类型的节点
      var temPath = path;
      if (baseNode != null) {
        temPath.push(baseNode);
        if (baseNode.childNodes.length > 0) {
          for (let i = 0; i < baseNode.childNodes.length; i++) {
            this.getNodes(baseNode.childNodes[i], temPath);
          }
        }
      }
    },
    getPosition(baseNode, node, offset) {
      //根据节点获取给定node中offset位置在栏位中的实际位置
      let path = [];
      this.getNodes(baseNode, path);
      let retIdx = 0;
      for (let i = 0; i < path.length; i++) {
        if (path[i] == node) {
          retIdx += offset;
          return retIdx;
        } else {
          if (path[i].nodeType == 3) {
            retIdx += path[i].nodeValue.length;
          }
        }
      }
    },
    uuid() {
      var s = [];
      var hexDigits = "0123456789abcdef";
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = "-";
      var uuid = s.join("");
      return uuid;
    },
    getColumnName(el) {
      let root = el;
      if (el == undefined) {
        return undefined;
      }
      if (!(el instanceof HTMLElement)) {
        root = el.parentElement;
      }
      let dt = root.getAttribute("data-Type");
      if (dt != undefined) {
        return root;
      }
      return dt = this.getColumnName(root.parentElement);
    },
  },
}