<template>
  <!-- 标的专利详情 -->
  <!-- 获取专利号，通过专利号调用拆分权要的接口返回对应数据 -->
  <div style="padding:20px">
    <div class="claims-imput-import">
      <div class="demo-input-suffix" v-if="show">
        标的专利号：<el-link type="primary"  @click="toPatentDetails(patentNo)">{{patentNo}}</el-link>
      </div>
      <!-- <div>
        <el-button @click="work" type="primary">工作协同</el-button>
        <el-button @click="tasks" type="primary">协同任务</el-button>
      </div> -->
    </div>
    <!-- table -->
    <div>
      <!-- table按钮部分 -->
      <div style="margin-top:20px;">
        <el-button-group  v-if="show" >
            <el-button @click="merge" :disabled="row.length>0?false:true">合并</el-button>
            <el-button @click="split" :disabled="row.length>0?false:true">拆分</el-button>
        </el-button-group>
        <el-select placeholder="请选择拆分类型" v-model="splitType1" style="margin-left: 50px;" @change="splitTypeSelect($event)" >
            <el-option label="仅拆主权要" value="0"></el-option>
            <el-option label="全部拆分" value="1"></el-option>
        </el-select>
        <el-select placeholder="请选择拆分符号" v-model="splitBy1" style="margin-left: 10px;" @change="splitBySelect($event)">
            <el-option label="逗号拆分" value="0"></el-option>
            <el-option label="分号拆分" value="1"></el-option>
            <el-option label="逗号和分号拆分" value="2"></el-option>
        </el-select>
        <el-select placeholder="请选择显示类型" v-model="Type" style="margin-left: 10px;" @change="TypeSelect($event)" >
            <el-option label="仅显示主权要" value="1"></el-option>
            <el-option label="全部显示" value="0"></el-option>
        </el-select>
        <el-button @click="keep" type="primary" style="float: right;">保存</el-button>
      </div>
      <!-- 表格部分 -->
      <el-table
        :data="tableData"
        ref="table"
        border
        :height="tableHeight"
        :span-method="objectSpanMethod"
        v-loading="loading"
        style="min-width: 100%; margin-top: 20px;overflow:auto">

        <el-table-column prop="pRightName" label="权要"  align="center"  width="200px">
          <template slot-scope="scope">  
            <el-tooltip class="item" effect="dark" :content="scope.row.pContent" placement="top">
              <!-- <span>{{scope.row.pContent}}</span> -->
              <span>{{scope.row.pRightName}}</span>
            </el-tooltip>     
          </template>
        </el-table-column>

        <el-table-column prop="content" label="特征" align="center" width="300px">
          <template slot-scope="scope" >
            <el-checkbox-group v-model="checkList" >

                <el-checkbox  :label="scope.row.id" @change="getFunInfo(scope.row,scope)" style="display: flex; align-items: center;">
                  <el-input type="textarea" style="width:250px" autosize v-model="scope.row.content"> {{scope.row.content}}</el-input>
                </el-checkbox>

             </el-checkbox-group>
          </template>
        </el-table-column>
        
        <el-table-column  prop="explainText" align="center" label="解释(可粘贴图片)">
          <template slot-scope="scope">   
            <!-- <div>
                <el-input type="textarea" style="width:100%" autosize v-model="scope.row.explainText"> {{scope.row.explainText}}</el-input>
            </div> -->
            <div style="width:100%;outline: #dcdfe6;border:1px solid #DCDFE6;border-radius:5px" id="preview" contenteditable="true" 
              v-html="scope.row.explainText"  @input="saveValue($event.target.innerHTML)"  @click="saveValue($event.target.innerHTML)"
              @blur="getValue(scope.row,'explainText')"  v-on:paste="handlePaste($event,scope.row,'explainText')">
              <!-- {{scope.row.explainText}} -->
            </div>
          </template>
        </el-table-column>

      </el-table>
    </div>
    <sendCollaboration ref="CollaborationDialog"></sendCollaboration>
    <taskList ref="TaskList"></taskList>
  </div>
</template>

    
<script>
import sendCollaboration from "@/views/report/components/sendCollaboration.vue"
import taskList from "@/views/report/components/taskList.vue"
import {explain} from '../../components/mixins'
import { PatentDetails } from '@/views/components/common/mixins';
export default {
  props: ['isshow', 'patentNo', "reportId",'splitType','splitBy'],
  mixins:[explain,PatentDetails],
  components: {
    sendCollaboration,
    taskList,
  },
  data() {
    return {
      show: true,
      checkList: [],
      tableData1: [],
      tableData: [],
      mergeObj: {},
      row: [],//选中特征push到row中
      mergeArr: ['id', 'pRightName'],//解释
      // patentNo:"",//专利号
      splitType1:this.$s.getSession('reportMessage1').splitType?this.$s.getSession('reportMessage1').splitType.toString():"0",//拆分类型0仅拆主权要，1全部拆分
      splitBy1: this.$s.getSession('reportMessage1').splitBy?this.$s.getSession('reportMessage1').splitBy.toString():"2",//拆分符号0 ','，1';',2','和';'
      Type: "1",//下拉框
      typeArr:[1],//显示权要还是全部显示
      // ReportId:"",//报告id
      // explainText: "",
      loading: false,
      delArr: [],
      keepSure:true,//保存标识
      tableHeight:null
    }
  },

  mounted() {
    console.log(this.$s.getSession('reportMessage1'))
    // this.splitBy1 = this.$s.getSession('reportMessage1').splitBy.toString()
    // this.splitType1 = this.$s.getSession('reportMessage1').splitType.toString()
    this.show = this.isshow == false ? this.isshow : true
    this.splitPatentRight();
    
  },
  methods: {
    setHeight() {
      const offsetTop = window.innerHeight - this.$refs.table.$el.offsetTop - 40
      const body = document.querySelector('.el-table__body')
      if (!body) {
        return false
      }
      const offsetBodyHeight = body.offsetHeight
      console.log( window.innerHeight,body,offsetBodyHeight,offsetTop)
      if (this.tableData.length && offsetBodyHeight < offsetTop) {
        this.tableHeight = offsetBodyHeight + 75
      } else if (!this.tableData.length) {
        this.tableHeight = null
      } else {
        this.tableHeight = offsetTop
      }
    },
    //选中特征
    getFunInfo(row,scope) {
      console.log("row",row,scope)
      // this.$emit('getfeatures', row)
      let Index=this.row.findIndex(item => {return item.id==row.id })
      if (Index<0) {
        row.$index = scope.$index
        this.row.push(row)
      } else {
        this.row.splice(Index,1)
      }
      console.log("getFunInfo",this.row);
    },
    //合并
    merge() {
      console.log(this.row)
      var sign = this.row[0].rightId
      var allow = true
      this.row.forEach(item => {
        if(item.rightId!=sign){
          allow = false
          return false
        }
      });
      if(!allow){
        this.$alert('不能合并不同权要的特征','提示',{
          confirmButtonText: '确定',
          type:'warning',
          callback: action => {
          }
        })
        return false;
      }

      this.keepSure=false
      var str = ''
      var strText=""
      if (this.row != []) {
        console.log(this.row);//explainText
        let row = this.row.sort((aId, bId) => {
            return aId.$index-bId.$index; 
          })
          row.sort((aId, bId) => {
            if(aId.$index - bId.$index!=1){
              allow = false
            }
          })
          if(!allow){
            this.$alert('只能合并相邻的特征','提示',{
              confirmButtonText: '确定',
              type:'warning',
              callback: action => {
              }
            })
            return false;
          }
        for (var i = 0; i < this.row.length; i++) {
          if (i < row.length - 1) {
            str = str + row[i].content + ','
            strText = strText + row[i].explainText + ','
            let Index = this.tableData1.findIndex(item => { return item.id == row[i].id })
            this.tableData1.splice(Index, 1)
          } else if (i == row.length - 1) {
            str = str + row[i].content
            strText = strText + row[i].explainText
          }
          // if (i < this.row.length - 1) {
          //   str = str + this.row[i].content + ','
          //   let Index=this.tableData1.findIndex(item => {return item.id==this.row[i].id })
          //   this.tableData1.splice(Index, 1)
          // } else if (i == this.row.length - 1) {
          //   str = str + this.row[i].content
          // }
        }
      }
      var a = this.tableData1.findIndex(item => {
        return item.id==this.row[this.row.length-1].id
      })
      this.tableData1[a].content = str
      this.tableData1[a].explainText = strText
      this.TypeSelect(this.Type)//调用显示权要
      this.row = []
      this.checkList=[]
    },
    //拆分
    split() {
      if (this.row.length > 1) {
          this.$alert('不能同时拆分多条特征','提示',{
            confirmButtonText: '确定',
            type:'warning',
            callback: action => {
            }
          })
          return false
        }
      //只对勾选的进行拆分
      this.keepSure=false
      this.checkList = []
      console.log(this.row);
      this.row.forEach(ele=>{
        var Index = this.tableData1.findIndex(item => {
          return item.id==ele.id
        })
        var a = Math.floor((Math.random()*9999)+1000);
        let tab = {
          pSignPatentNo: ele.pSignPatentNo,
          pPatentId: ele.pPatentId,
          pContent: ele.pContent,
          pRightName: ele.pRightName,
          pType: ele.pType,
          pSort: ele.pSort,
          pReportId: ele.pReportId,
          pContentOut: ele.pContentOut,

          id:ele.id+"a"+ele.$index+a,
          signPatentNo: ele.signPatentNo,
              contentOut:"" ,
              content: "",
              rightId: ele.rightId,
              isFinal: ele.isFinal,
              reportId: ele.reportId,
              explainText: "",

              rightName: ele.rightName,
              rightType: ele.rightType,
              splitBy: ele.splitBy,
        }
        // console.log(tab)
        this.tableData1.splice(Index+1,0,tab)
      })
      this.TypeSelect(this.Type)//调用显示权要
      this.row = []
      console.log(this.row);
    },
    //获取每个元素所需合并的行数
    getSpanArr(data) {
      this.row = []
      this.mergeArr.forEach((key, index1) => {
        let count = 0;
        this.mergeObj[key] = [];
        data.forEach((item, index) => {
          if (index === 0) {
            this.mergeObj[key].push(1);
          } else {
            if (item[key] === data[index - 1][key] && item[key] !== 'explainText') {
              this.mergeObj[key][count] += 1;
              this.mergeObj[key].push(0);
            } else {
              count = index;
              this.mergeObj[key].push(1);
            }
          }
        })
      })
    },
    //合并行
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // column.property=“id”  
      if (this.mergeArr.indexOf(column.property) !== -1) {
        if (this.mergeObj[column.property][rowIndex]) {
          // console.log("@@",this.mergeObj[column.property][rowIndex]);
          return [this.mergeObj[column.property][rowIndex], 1]
        } else {
          return [0, 0];
        }
      }
    },
    //弹框导入文件
    spanImprot() { },
    //工作协同
    work() { 
      this.$refs.CollaborationDialog.visibleCollaboration=true
    },
    //协同任务
    tasks() { 
      this.$refs.TaskList.showTask=true
    },
    //拆分权要
    splitPatentRight() {//patentRightVos
      this.loading=true
      let PatentRight = {
        patentNo: this.patentNo,
        splitType: this.splitType1,
        splitBy: this.splitBy1,
        ReportId: this.reportId,
      }
      console.log(PatentRight)
      this.$api.splitPatentRight(PatentRight).then(res => {
        console.log("res",res);
        if (res.code == 200) {
          // this.splitBy1= res.data.splitBy.toString()
          // this.splitType1= res.data.splitType.toString()
          // this.splitBy= res.data.splitBy.toString()
          // this.splitType= res.data.splitType.toString()
          let a=this.$s.getSession('reportMessage1')
          a.splitBy=res.data.splitBy.toString()
          a.splitType = res.data.splitType.toString()
          this.$s.setSession('reportMessage1',a)

          this.tableData1 = [];
          for (let i = 0; i < res.data.patentRightVos.length; i++){
            // if (res.data.patentRightVos[i].features.length>0) {
              for (let m = 0; m < res.data.patentRightVos[i].features.length; m++){
                res.data.patentRightVos[i].features[m].pSignPatentNo=res.data.patentRightVos[i].signPatentNo
                res.data.patentRightVos[i].features[m].pPatentId=res.data.patentRightVos[i].patentId
                res.data.patentRightVos[i].features[m].pContent=res.data.patentRightVos[i].content
                res.data.patentRightVos[i].features[m].pType=res.data.patentRightVos[i].type
                res.data.patentRightVos[i].features[m].pSort=res.data.patentRightVos[i].sort
                res.data.patentRightVos[i].features[m].pReportId=res.data.patentRightVos[i].reportId
                res.data.patentRightVos[i].features[m].pRightName=res.data.patentRightVos[i].RightName
                res.data.patentRightVos[i].features[m].pContentOut = res.data.patentRightVos[i].contentOut

                if (!res.data.patentRightVos[i].features[m].hasOwnProperty("explainText")) {//hasOwnProperty判断属性是否存在
                  res.data.patentRightVos[i].features[m].explainText=res.data.patentRightVos[i].features[m].contentOut
                } else {
                  if (res.data.patentRightVos[i].features[m].explainText=="") {//属性存在等于空
                    res.data.patentRightVos[i].features[m].explainText=res.data.patentRightVos[i].features[m].contentOut
                  }
                }

                this.tableData1.push(res.data.patentRightVos[i].features[m])
              }
            // } else {
            //   this.tableData1.push({
            //     pSignPatentNo:res.data.patentRightVos[i].signPatentNo,
            //     pPatentId:res.data.patentRightVos[i].patentId,
            //     pContent:res.data.patentRightVos[i].content,
            //     pType:res.data.patentRightVos[i].type,
            //     pSort:res.data.patentRightVos[i].sort,
            //     pReportId:res.data.patentRightVos[i].reportId,
            //     pContentOut: res.data.patentRightVos[i].contentOut,
            //     pRightName : res.data.patentRightVos[i].RightName,
            //     content : res.data.patentRightVos[i].content,
            //   })
            // }
          }
          this.TypeSelect(this.Type)//调用显示权要
          this.loading=false
        }
        // console.log("@@",this.tableData1);
      })
    },

    // 条件选择下拉框
    splitTypeSelect(event) {//拆主权要
      this.splitType1 = event;
      this.splitPatentRight()
    },
    splitBySelect(event) {//按符号拆分
      console.log(event);
      this.splitBy1 = event;
      this.splitPatentRight();
    },
    TypeSelect(event) {//显示
      this.typeArr = [];
      if (event==1) {
        this.typeArr.push(1);
      } else {
        this.typeArr.push(1, 0);
      }
      // console.log("@@",this.tableData);
      // console.log("@@",this.tableData1);
      this.tableData = this.tableData1.filter(item => {
         return this.typeArr.includes(item.pType)
      })
      // console.log("tableData",this.tableData);
      this.getSpanArr(this.tableData)
    },
    //保存
    keep() {
      let keepArr = [];
      // this.$message({
      //     message: '此次修改将覆盖之前保存的信息',
      //     type: 'warning'
      // });
      keepArr.push(
        {
          signPatentNo: this.tableData1[0].pSignPatentNo,
          patentId: this.tableData1[0].pPatentId,
          content: this.tableData1[0].pContent,
          type: this.tableData1[0].pType,
          sort: this.tableData1[0].pSort,
          reportId: this.tableData1[0].pReportId,
          contentOut: this.tableData1[0].pContentOut,
          features:[],
        }
      )
      let j = 0;
      for (let i = 0; i < this.tableData1.length; i++){
        if (keepArr.findIndex(item => { return item.contentOut == this.tableData1[i].pContentOut }) < 0) {
          console.log(this.tableData1[i]);
          j+=1
          keepArr.push(
            {
              signPatentNo: this.tableData1[i].pSignPatentNo,
              patentId: this.tableData1[i].pPatentId,
              content: this.tableData1[i].pContent,
              type: this.tableData1[i].pType,
              sort: this.tableData1[i].pSort,
              reportId: this.tableData1[i].pReportId,
              contentOut: this.tableData1[i].pContentOut,
              features:[],
            }
          )
        }
        
        // if (this.splitType==1) {
          keepArr[j].features.push(
            {
              signPatentNo: this.tableData1[i].signPatentNo,
              contentOut: this.tableData1[i].contentOut,
              content: this.tableData1[i].content,
              rightId: this.tableData1[i].rightId,
              isFinal: this.tableData1[i].isFinal,
              reportId: this.tableData1[i].reportId,
              rightName: this.tableData1[i].rightName,
              rightType: this.tableData1[i].rightType,
              splitBy: this.tableData1[i].splitBy,
              explainText: this.tableData1[i].explainText ? this.tableData1[i].explainText : "",
            }
          )
        // } else {
        //   if (keepArr[j].type==1) {
        //     keepArr[j].features.push(
        //       {
        //         signPatentNo: this.tableData1[i].signPatentNo,
        //         contentOut: this.tableData1[i].contentOut,
        //         content: this.tableData1[i].content,
        //         rightId: this.tableData1[i].rightId,
        //         isFinal: this.tableData1[i].isFinal,
        //         reportId: this.tableData1[i].reportId,
        //         explainText: this.tableData1[i].explainText ? this.tableData1[i].explainText : "",
        //       }
        //     )
        //  }
        // }
        
      }
      console.log(keepArr)
      this.$api.KeepPatentRight(keepArr).then(res => {
        console.log(res);
        if (res.code == 200) {
          this.keepSure = true;
          this.$message({
            message: '保存成功',
            type: 'success'
          });
        }
        
      })
    },

   
  },
  watch: {
    tableData(){
      this.$nextTick(() => {
        this.setHeight()
      })
    },
    patentNo(val) {
      this.patentNo = val
    },
    reportId(val) {
      this.reportId = val
    },
    keepSure(val) {
      this.$emit("isSave",val)
    }
  }
}
 

</script>
  
<style lang="less">
.claims-imput-import{
  display: flex;
  justify-content: space-between;
}
.spanImprot{
  color: #42A5F5;
  cursor :pointer;
}
.spanImprot:hover{
	cursor :pointer;
	color: red;
	text-decoration:underline;
}
  </style>