
import { getTableHeight } from '@/views/components/mixins'
import fields from '@/views/components/dialog/fields.vue';
import addStatute from './components/addStatute.vue';
export default {
    components: {
      fields,
      addStatute
    },
    mixins:[getTableHeight],
    props: {
        projectId:{
            default:null
        },
        projectName:{

        },
        projectType:{
    
        },
        reportType:{
            default:0
        },
        patentNo:{
            default:''
        }
    },
    data() {
      return {
          tableData:[],
          claims:[],
          compareLiterature:[],
          loading:false,
          editMessage:{},
          cell:{
            rowId:'',
            columnId:''
          }

      };
    },
    watch: {},
    computed: {
        provisions(){
            return this.$store.state.dictMessage.dictMessage.STATUTE || []
        }
      },
    created() {},
    async mounted() {
      this.column = await this.$commonJS.getCustomField(this.type,{ projectId: this.projectId })
      this.init()
      this.getClaims()
      // this.getCompareLiterature()
    },
    methods: {
      //显示栏位管理
      showField(){
        this.$refs.field.open(this.column)
      },
      // 显示栏位管理组件返回数据
      getFieldList(val) {
        this.column = []
          this.$nextTick(()=>{
              this.column = val
          })
      },
      //获取数据
      async init(){
      //   this.tableData = [
      //     {
      //         "id":1,
      //         "statuteId":"2", 
      //         "claim":{
      //             id:1255,
      //             order:0,
      //             content:'1.一种骨传导扬声器，其特征在于，包括：磁路组件，用于提供磁场；振动组件，所述振动组件的至少一部分位于所述磁场中，将输入至所述振动组件的电信号转化为机械振动信号；壳体，所述壳体容纳所述振动组件；以及耳机固定组件，所述耳机固定组件与所述壳体固定连接，用于保持所述骨传导扬声器与人体的接触，其中，所述壳体具有面向人体一侧的外壳面板和与所述外壳面板相对的外壳背面，以及位于所述外壳面板和所述外壳背面之间的外壳侧面，所述振动组件导致所述外壳面板和外壳背面振动。'
      //         },
      //         featureContent:'特征1',
      //         featureOrder:1,
      //         invalidReason:'D1公开了...',
      //         presentOpinions:'D1...',
      //         "rbDecision":"复审委意见" ,
      //         "courtOpinions1":"基于原权要维持有效", 
      //         "courtOpinions2":"基于原权要维持有效 ", 
      //     },
      //     {
      //         "id":2,
      //         "statuteId":"2", 
      //         "claim":{
      //             id:1255,
      //             order:0,
      //             content:'1.一种骨传导扬声器，其特征在于，包括：磁路组件，用于提供磁场；振动组件，所述振动组件的至少一部分位于所述磁场中，将输入至所述振动组件的电信号转化为机械振动信号；壳体，所述壳体容纳所述振动组件；以及耳机固定组件，所述耳机固定组件与所述壳体固定连接，用于保持所述骨传导扬声器与人体的接触，其中，所述壳体具有面向人体一侧的外壳面板和与所述外壳面板相对的外壳背面，以及位于所述外壳面板和所述外壳背面之间的外壳侧面，所述振动组件导致所述外壳面板和外壳背面振动。'
      //         },
      //         featureContent:'特征2',
      //         featureOrder:2,
      //         invalidReason:'D2公开了...',
      //         presentOpinions:'D2...',
      //         "rbDecision":"复审委意见" ,
      //         "courtOpinions1":"基于原权要维持有效", 
      //         "courtOpinions2":"基于原权要维持有效 ", 
      //     },
      //     {
      //         "id":5,
      //         "statuteId":"2", 
      //         "claim":{
      //             id:1256,
      //             order:1,
      //             content:'2.根据权利要求1所述的骨传导扬声器，其特征在于，所述外壳背面和所述外壳侧面为一体成型结构；所述外壳面板与所述外壳侧面之间通过胶水、卡接、焊接或螺纹连接中的一种或任意几种的组合进行连接。'
      //         },
      //         featureContent:'',
      //         featureOrder:1,
      //         invalidReason:[],
      //         presentOpinions:[],
      //         "rbDecision":"" ,
      //         "courtOpinions1":"", 
      //         "courtOpinions2":"", 
      //     },
      //     {
      //         "id":3,
      //         "statuteId":"3", 
      //         "claim":{
      //             id:1256,
      //             order:1,
      //             content:'2.根据权利要求1所述的骨传导扬声器，其特征在于，所述外壳背面和所述外壳侧面为一体成型结构；所述外壳面板与所述外壳侧面之间通过胶水、卡接、焊接或螺纹连接中的一种或任意几种的组合进行连接。'
      //         },
      //         featureContent:'特征1',
      //         featureOrder:1,
      //         invalidReason:'',
      //         presentOpinions:'',
      //         "rbDecision":"复审委意见" ,
      //         "courtOpinions1":"基于原权要维持有效", 
      //         "courtOpinions2":"基于原权要维持有效 ", 
      //     },
      //     {
      //         "id":4,
      //         "statuteId":"3", 
      //         "claim":{
      //             id:1256,
      //             order:1,
      //             content:'2.根据权利要求1所述的骨传导扬声器，其特征在于，所述外壳背面和所述外壳侧面为一体成型结构；所述外壳面板与所述外壳侧面之间通过胶水、卡接、焊接或螺纹连接中的一种或任意几种的组合进行连接。'
      //         },
      //         featureContent:'特征2',
      //         featureOrder:2,
      //         invalidReason:'',
      //         presentOpinions:'',
      //         "rbDecision":"复审委意见" ,
      //         "courtOpinions1":"基于原权要维持有效", 
      //         "courtOpinions2":"基于原权要维持有效 ", 
      //     },
      // ]
      // if(this.statueType == 1){
      //   this.getSpanArr(this.tableData)
      // }
      
         var params = {
            projectId:this.projectId,
            statueType:this.statueType
         }
         this.loading = true
         this.$api.getInvalidReasonClaims(params).then(res=>{
            if(res.code == 200){
                this.tableData = res.data
                if(this.statueType == 1){
                  this.getSpanArr(this.tableData)
                }
                this.loading = false
            }
         }).catch(error=>{
            this.tableData = []
            this.loading = false
         })
      },
      //获取权利要求
      getClaims(){
        var params = {
            projectId:this.projectId
        }
        this.$api.getVersionClaims(params).then(response=>{
            if(response.code == 200){
                this.claims = response.data
            }
        }).catch(error=>{
            this.claims = []
        })
      },
      //获取证据文献
      getCompareLiterature(){
        this.$api.queryCompareLiterature({projectId:this.projectId}).then(response=>{
            if(response.code == 200){
                this.compareLiterature = response.data.data.sort((a,b)=>{
                    return a.sysOrder - b.sysOrder
                })
            }
        }).catch(error=>{
            this.compareLiterature = []
        })
      },
      //同步
      synchronization(){
        var params = {
            id:this.projectId
        }
        this.$api.importFinalInvalidStatues(params).then(res=>{
            if(res.code == 200){
                this.init()
            }
        })
      },
      getData(row,fieldObj,value){
        var field = fieldObj.field
        var fieldArray = this.getFieldArray(field)
        let current = row;  
        // 遍历路径中的每一部分，直到最后一个属性的父对象  
        for (let i = 0; i < fieldArray.length - 1; i++) {  
            // 确保当前对象有下一个属性，否则创建一个空对象（或你需要的任何默认值）  
            if (!current.hasOwnProperty(fieldArray[i])) {  
                current[fieldArray[i]] = {};  
            }  
            current = current[fieldArray[i]];  
        }  
        
        // 给最后一个属性赋值  
        current[fieldArray[fieldArray.length - 1]] = value;  
      },
      //获取栏位数据
      getColumnData(row,fieldObj){
        var field = fieldObj.field
        if(fieldObj.type == 'array'){
          
          return
        }
        const parts = this.getFieldArray(field) 
        let current = row;  
          
        for (let i = 0; i < parts.length; i++) {  
            if (current && current.hasOwnProperty(parts[i])) {  
                current = current[parts[i]];  
            } else {  
                // 如果路径中的某一部分不存在，则返回undefined或自定义的默认值  
                return ''; // 或者你可以返回null、默认值等  
            }  
        }  
        if(parts[parts.length-1] == 'statuteId'){
            var obj = this.provisions.find(item=>{
                return item.value == current
            })
            if(obj){
                return obj.simpleLabel || obj.label
            }
        }
        if(field == 'invalidReasonDTO.claimSort'){
          return `权要${Number(current) + 1}`
        }
        return current+''; 
      },
      getFieldArray(field){
        return field.split('.')
      },

      //单元格样式
      cellStyle({row, column, rowIndex, columnIndex}){
        if(this.cell.columnId == column.id && this.cell.rowId == row.proofGroupId){
          return  { backgroundColor: '#f0f9eb' }
        }
        return {}
      },
      //双击单元格进行编辑
      cellDblclick(row, column, cell, event){
       
        var key = column.property
        var item = this.column.find(item=>{
            return item.field == key
        })
        this.edit(item,row,column)
      },
       //编辑
       async edit(item,row,column){
          if(item.field && row){
            if(this.editMessage.field){
              return
            }
            if(!item.editable){
              // this.$message.warning('该栏位不可编辑')
              return
            }
            this.cell={
              rowId:row.proofGroupId,
              columnId:column.id
            }
            this.editMessage = {
              field:item,
              data: JSON.parse(JSON.stringify(row))
            }
            // this.openEditDialog(item,row)
            return
          }
      },
      //打开弹窗(取消该方法)
      openEditDialog(item,row){
        var title = '编辑'+item.label
        var field1 = ['courtOpinions1','courtOpinions2','statuteId','claim.order','claim.content']
        var field3 = ['invalidReason','presentOpinions']
        var type = 2
        var data = {}
        var prop = null
        if(field3.indexOf(item.field)!=-1){
          type = 3
        }
        if(field1.indexOf(item.field)!=-1){
          type = 1
          if(['courtOpinions1','courtOpinions2'].indexOf(item.field)!=-1){
            data.options = [
              {
                label:'基于原权要维持有效',
                value:'基于原权要维持有效'
              },
              {
                label:'基于修改后权要维持有效',
                value:'基于修改后权要维持有效'
              },
              {
                label:'全部无效',
                value:'全部无效'
              },
            ]
          }else if(['claim.order','claim.content'].indexOf(item.field)!=-1){
            data.options = this.claims
            prop = {
              label:(claim)=>{return `权要${Number(claim.sysOrder)+1}`},
              value:'id'
            }
          }
          else if(['statuteId'].indexOf(item.field)!=-1){
            data.options = this.provisions
          }
        }
        if(type == 3){
          data.value = row[item.field] ?JSON.parse(JSON.stringify(row[item.field])):''
          data.options = this.compareLiterature
          prop = {
            label:(d)=>{return `D${d.sysOrder}(${d.publicNo || d.name})`},
            value:'id'
          }
        }else{
          if(item.field == 'statuteId'){
            data.value = row[item.field]
          }else if(item.field == 'claim.order' || item.field == 'claim.content' ){
            data.value = row.claim?.id
          }
          else{
            data.value = this.getColumnData(row,item)
          }
        }
        this.editMessage.type = type
        this.$refs.editDialog.open(title,type,data,prop)
      },

      //查看证据文献详情（取消该方法）
      checkDetails(row,index){
        var search = {
            location: index + 1
        }
        this.$s.setSession('search', search)
        this.$router.push(
            {
            path: '/patentDetails/' + row.literatureNo,
            query: {
                projectId: this.projectId,
                reportType: this.reportType,
                evidenceType:row.type,
                evidence:JSON.stringify(row),
                signPatentNo:this.patentNo,
                projectName: this.projectName,
                projectType: this.projectType,
            }
            }
        )
      },
      //单击单元格取消编辑
      cellClick(row, column, cell, event){
        
        if(this.editMessage && this.editMessage.field){
            // var parts = this.getFieldArray(this.editField)
            // if(!(parts.length>1 && parts[parts.length - 1]!='claimText'+row.id)){
            //   return  
            // }
            // if(['courtOpinions1','courtOpinions2'].indexOf(this.editMessage.field.field)!=-1){
            //   this.closeEdit()
            // }
        }
        // this.editField = null
      },
      //关闭编辑
      closeEdit(){
        this.editMessage = {}
        this.cell = {}
      },
      //修改数据
      changeMessage(field,row,value){
        var value1 = this.getColumnData(this.editMessage.data,field)
        if(value == value1){
          this.closeEdit()
          return
        }
        var params = {}
        var api = ''
        var sign = false

        var parts = this.getFieldArray(field.field) 
        var part = parts[parts.length-1]
        if(field.field.indexOf('invalidReasonDTO') !=-1){
          params = {
            ...row.invalidReasonDTO
          }
          params[part] = value
          api = 'editInvalidReason'
          sign = true
        }else{
          params = {
            ...row
          }
          params[part] = value
          api = 'editFeature'
        }
        var message = this.$message({
          message: '信息保存中...',
          type: 'warning',
          duration:0
        });
        this.$api[api](params).then(response=>{
          if(response.code == 200){
            message.close()
            this.$message.success('编辑成功')
            
            if(sign){
              this.init()
            }else{
              this.getData(row,field,value)
            }
            this.closeEdit()
            
          }
        }).catch(error=>{
          message.close()
          this.$message.error('编辑失败')
          if(this.$refs[field.field+row.proofGroupId] && this.$refs[field.field+row.proofGroupId][0]){
            this.$refs[field.field+row.proofGroupId][0].setFocus()
          }
        })
      },
      //添加特征
      addFeature(scope,type){
        var row = scope.row
        var index = scope.$index
        var featureSort = row.featureSort
        var obj = {
            projectId:this.projectId,
            invalidStatueId:row.invalidStatueId,
            featureContent:'',
        }
        if(type == 'up'){
          obj.featureSort = Number(featureSort)
        }else{
          obj.featureSort = Number(featureSort) + 1
        }
        this.loading = true
        var that = this
        this.$api.addFeature(obj).then(response=>{
          if(response.code == 200){
            that.loading = false
            var data = {
              invalidReasonDTO:row.invalidReasonDTO,
              ...obj,
              proofGroupId:response.data,
            }
            that.updateSort(obj.featureSort,obj.invalidStatueId,'add')
            if(type == 'up'){
              that.tableData.splice(index,0,data)
            }else{
              that.tableData.splice(index+1,0,data)
            }
            that.getSpanArr(this.tableData)
          }
        }).catch(error=>{
          this.loading = false
        })
      },
      //更新序号
      updateSort(sort,invalidStatueId,type){
        var arr = this.tableData.filter(item=>{
          return item.invalidReasonDTO.invalidStatueId == invalidStatueId
        })
        for(var i = 0;i<arr.length;i++){
          var featureSort = Number(arr[i].featureSort)
          if(featureSort>= sort){
            if(type == 'add'){
              arr[i].featureSort = featureSort+1
            }else if(type == 'del'){
              arr[i].featureSort = featureSort-1
            }
          }
        }
        return true
      },
      //删除无效理由
      delInvalidStatue(scope){
        this.$confirm('确认删除本条数据吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          var row = scope.row
          var params = {
            invalidStatueId:row.invalidReasonDTO.invalidStatueId
          }
          this.loading = true
          this.$api.delInvalidReason(params).then(response=>{
              if(response.code == 200){
                  this.$message.success('删除成功')
                  this.loading = false
                  this.init()
              }
          }).catch(error=>{
            this.loading = false
          })
        })
        
      },
      //打开添加无效理由弹窗
      addInvalidStatueDialog(){
        this.$refs.addStatute.open()
      },
      //添加无效理由
      save(invalidStatueId){
        // this.addFeature({row:{invalidStatueId:invalidStatueId,}})
          // var params = {
          //   projectId:this.projectId,
          //   invalidStatueId:invalidStatueId,
          //   featureSort:1,
          //   featureContent:'',
          // }
          // this.loading= true
          // this.$api.addFeature(params).then(response=>{
          //   if(response.code == 200){
          //     this.init()
          //   }
          // })
        this.init()
      }
    },
  };