<template>
  <!-- 权要拆分类型等 -->
  <div class="height_100">
    <el-container>
      <el-header v-if="isResult != 'noShow'" style="display: flex; justify-content: space-between;">
        <div style="display:flex;align-items:center">
          <div>
            <slot name="handleLeft"></slot>
          </div>
          <div v-if="isEdit">
            <el-button-group>
              <el-button @click="merge" :disabled="checkList.length > 1 ? false : true">合并</el-button>
              <el-button @click="split" :disabled="checkList.length > 0 ? false : true">拆分</el-button>
            </el-button-group>
          </div>
        </div>
        <div>
          <el-select v-if="isEdit" placeholder="请选择拆分类型" :value="splitType" style="margin-left: 50px;"
            @change="splitSelect($event, 'type')">
            <el-option label="仅拆主权要" value="0"></el-option>
            <el-option label="全部拆分" value="1"></el-option>
          </el-select>
          <el-select v-if="isEdit" placeholder="请选择拆分符号" :value="splitBy" style="margin-left: 10px;"
            @change="splitSelect($event, 'by')">
            <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="showType" style="margin-left: 10px;" @change="typeSelect($event)">
            <el-option label="全部显示" value="0"></el-option>
            <el-option label="仅显示主权要" value="1"></el-option>
          </el-select>
        </div>
        <div style="display:flex;align-items:center;">
          <div class="margin-right_10">
            <slot name="handleRight"></slot>
          </div>
          <div v-if="(isEdit || isResult != 2) && isResult != 9">

            <el-button @click="save" type="primary">保存</el-button>
          </div>
        </div>
      </el-header>
      <el-main>
        <el-table :data="tableData2" border ref="table" height="calc(100%)" :span-method="objectSpanMethod"
          v-loading="loading" style="width: 100%;overflow: auto;" :cell-class-name="isResult==3?checkDel:''">
          <el-table-column prop="pRightName" label="权要" align="center">
            <template slot-scope="scope">
              <!-- <el-tooltip class="item" effect="dark"
                :content="rightList.length > 0 ? rightList.filter(item => { return item.sort == scope.row.rightSort })[0].content : '暂无数据'"
                placement="top"> -->
              <el-tooltip class="item" effect="dark" :content="scope.row.pContent" placement="top">
                <span>{{ scope.row.pRightName }}</span>
              </el-tooltip>
            </template>
          </el-table-column>

          <el-table-column prop="content" label="特征" min-width="300" align="center">
            <template slot-scope="scope">
              <div v-if="isEdit">
                <el-checkbox-group v-model="checkList">
                  <el-checkbox :label="scope.row.featureId" @change="getRow(scope)"
                    style="display: flex;align-items: center;width:100%">
                    <el-input type="textarea" autosize v-model="scope.row.content">
                      {{ scope.row.content }}</el-input>
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              <div v-else-if="isResult == 9">
                <el-checkbox-group v-model="checkList">
                  <el-checkbox :label="scope.row.featureId" @change="getRow(scope)"
                    style="display: flex;align-items: center;width:100%">
                    <div v-html="scope.row.content"> </div>
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              <div v-else v-html="scope.row.content"> </div>
            </template>
          </el-table-column>

          <el-table-column prop="explainText" label="解释(可粘贴图片)" align="center">
            <template slot-scope="scope">
              <div v-if="isEdit">
                <myRichText style="text-align:left" v-model="scope.row.explainText" placeholder="请输入解释(可粘贴图片)">
                </myRichText>
              </div>
              <div v-else v-html="scope.row.explainText"></div>
            </template>
          </el-table-column>

          <!-- 父组件传递栏位 -->
          <el-table-column v-for="(item, index) in columnList" :key="index" :label="item.name"
            align="center" min-width="160px">

            <template slot-scope="scope">

              <div v-if="item.type == 'String'">
                <div v-if="isEdit || item.disabled">
                  <myRichText style="text-align:left" :value="getColumnData(scope.row, item)"
                    @input="getValue($event, scope.row, item)" :placeholder="'请输入' + item.name">
                  </myRichText>
                </div>
                <div v-else v-html="getColumnData(scope.row, item)"></div>
              </div>

              <div v-else-if="item.type == 'Array'">
                <div v-if="isEdit || item.disabled">
                  <el-select :value="getColumnData(scope.row, item)" @input="getValue($event, scope.row, item)"
                    placeholder="请选择">
                    <el-option v-for="optionItem in item.options" :key="optionItem.value" :label="optionItem.label"
                      :value="optionItem.value">
                    </el-option>
                  </el-select>
                </div>
                <div v-else v-html="getColumnData(scope.row, item)"></div>
              </div>
              <div v-if="item.type == 'btn'" >
                <span v-for="(btn, index) in item.btn" :key="index">
                  <component :is="btn.type" @click="$emit('changeResult', scope.row)">{{ btn.name }}</component>
                </span>

              </div>

            </template>
          </el-table-column>

        </el-table>
      </el-main>
    </el-container>




  </div>
</template>

<script>
export default {
  props: {
    // 信息(patentNo,reportId)
    patentNo: '',
    projectId: '',
    // 数据源
    tableData: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 是否可读
    isEdit: {
      type: Boolean,
      default: true
    },
    // 栏位参数 
    columnList: {
      type: Array,
      default: () => {
        return []
      }
    },
    //9:不显示保存且选择特征
    isResult: '',
    reportType:'',
    checkFeatures:{},
    checkData:{}
  },
  data() {
    return {
      tableData2: [],//显示数据
      splitType: '1',//拆分类型0仅拆主权要，1全部拆分
      splitBy: '2',//拆分符号0逗号拆分，1分号拆分，2逗号和分号拆分
      showType: '0',//显示类型0全部显示1仅显示主权要
      typeArr: [1],//显示权要还是全部显示
      // 表格的loading
      loading: false,
      // 表格的高度
      tableHeight: 0,
      // 勾选中的特征数据
      checkList: this.checkFeatures || [],
      // 计算表格合并行的数量
      mergeObj: {},
      // 表格合并行的栏位
      mergeArr: ['id', 'pRightName'],
      // 特征行数据
      scopeRow: this.checkData || [],
      //权要列表
      rightList: [],

    }
  },
  watch: {
    tableData: {
      handler(newVal, oldVal) {
        this.typeSelect(this.showType)
      },
      deep: true
    },
    patentNo(val){
      if(val){
        this.getRight()
      }
    },
    checkFeatures(val){
      if(val){
        this.checkList = val
      }
    },
    checkData(val){
      if(val){
        this.scopeRow = val
      }
    },
  },

  async mounted() {
    this.scopeRow = this.checkData || []
    this.checkList = this.checkFeatures || []
    //获取权要
    this.getRight()
    if (this.tableData.length > 0) {
      this.typeSelect(this.showType)
    }
  },
  methods: {
    getCheckList(){
      this.$emit('getCheckList',this.scopeRow)
    },
    // 获取数据
    getColumnData(row, field) {
      if (typeof field.value == 'string') {
        return row[field.value]
      } else {
        var str = row
        if (field.value && field.value.length > 0) {
          try {
            field.value.forEach(item => {
              if (str[item] != 0 && !str[item]) {
                throw Error();
              }
              str = str[item]
            })
          }
          catch (e) {
            return ''
          }

        }
        if (this.isEdit || field.disabled) {

        } else {
          if (field.options && field.options.length > 0) {
            let a = field.options.find(item => {
              return item.value == str
            })
            if (a) {
              return a.label
            } else {
              return ''
            }
          }
        }
        return str
      }

    },
    getValue(value, row, field) {
      if (typeof field.value == 'string') {
        row[field.value] = value
      } else {
        var str = row
        if (field.value && field.value.length > 0) {
          try {
            field.value.forEach((item, index) => {
              if (index == field.value.length - 1) {
                this.$set(str, item, value)
                return
              } else {
                if (!str[item]) {
                  this.$set(str, item, {})
                }
              }
              str = str[item]
            })
          }
          catch (e) {
            return ''
          }

        }
      }
    },
    //获取权要
    getRight() {
      
      if (this.rightList.length > 0) {
        return false
      }
      if(!this.patentNo){
        return false
      }
      let params = {
        patentNo: this.patentNo,
      }
      this.$api.getPatentRight(params).then(res => {
        if (res.code == 200) {
          this.rightList = res.data.data
        }
      })
    },
    //获取每个元素所需合并的行数
    getSpanArr(data) {

      this.scopeRow =  this.checkData || []
      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 }) {
      if (!row) {
        return false
      }

      if (this.mergeArr.indexOf(column.property) !== -1) {

        if (this.mergeObj[column.property][rowIndex]) {
          return [this.mergeObj[column.property][rowIndex], 1]
        } else {
          return [0, 0];
        }

      }
    },
    // 保存
    save() {
      this.$message.warning('正在保存中......')
      this.$emit('isSave', this.tableData2)
    },
    // 选择拆分类型或拆分符号
    splitSelect(val, type) {
      this.$confirm('重新进行拆分将会清空所有的解释以及其他栏位信息,此操作不可逆, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (type == 'type') {
          this.splitType = val
        } else {
          this.splitBy = val
        }
        var split = {
          splitBy: this.splitBy,
          splitType: this.splitType
        }
        this.$emit('splitSelect', split)
      }).catch(() => {
        this.$message.info('已取消删除');
      });

    },
    // 选择显示类型
    typeSelect(val) {
      this.typeArr = []
      if (val == 1) {
        this.typeArr.push(1)
      } else {
        this.typeArr.push(1, 0)
      }

      var data = this.tableData.filter(item => {
        return this.typeArr.includes(item.pType)
      })
      this.tableData2 = JSON.parse(JSON.stringify(data))
      this.getSpanArr(this.tableData2)
    },
    // 获取当前行的数据
    getRow(scope) {
      let Index = this.scopeRow.findIndex(item => { return item.featureId == scope.row.featureId })
      if (Index < 0) {
        scope.row.$index = scope.$index
        this.scopeRow.push(scope.row)
      } else {
        this.scopeRow.splice(Index, 1)
      }
    },
    // 将栏位值合并
    columnMerge() {
      var arr = ['content', 'explainText']
      if (this.columnList && this.columnList.length > 0) {
        this.columnList.forEach(item => {
          arr.push(item.value)
        })
      }
      return arr
    },
    // 特征等合并
    merge() {
      if (this.scopeRow.length > 1) {
        // 判断是否可以合并
        for (let i = 0; i < this.scopeRow.length - 1; i++) {
          // 跨权要不能合并特征
          if (this.scopeRow[i].rightSort != this.scopeRow[i + 1].rightSort) {
            this.$alert("不能跨权要合并特征", "提示", {
              type: 'warning',
              confirmButtonText: '确定',
            })
            return false
          } else {//不相邻特征不能合并
            let Index_rowArr = this.scopeRow.sort((a, b) => {
              return a.$index - b.$index
            })
            // console.log(this.Index_row,Index_rowArr);
            if (Index_rowArr[i + 1].$index - Index_rowArr[i].$index != 1) {
              this.$alert("非相邻不能合并特征", "提示", {
                type: 'warning',
                confirmButtonText: '确定',
              })
              return false
            }
          }
        }
        var merge = {}
        var arr = this.columnMerge()
        arr.forEach(item => {
          merge[item] = ''
        })
        let splitDisable = this.splitDisable()
        if (!splitDisable) {
          return false
        }
        // 将内容合并起来
        this.scopeRow.forEach((rowItem, rowIndex) => {
          for (let m = 0; m < arr.length; m++) {
            merge[arr[m]] = merge[arr[m]] + rowItem[arr[m]]
          }

          let Index1 = this.tableData.findIndex(item => { return rowItem.featureId == item.featureId })
          if (Index1 != -1) {
            if (rowIndex < this.scopeRow.length - 1) {
              this.tableData.splice(Index1, 1)
            } else if (rowIndex == this.scopeRow.length - 1) {
              for (let j = 0; j < arr.length; j++) {
                this.tableData[Index1][arr[j]] = merge[arr[j]]
              }
              this.tableData[Index1].ifChange = true
            }
          }


        })
        console.log(this.tableData)
        this.handleSort(this.scopeRow[0].rightSort)
        this.typeSelect(this.showType)
        this.scopeRow = []
        this.checkList = []
      }
    },
    // 拆分
    split() {
      //不能同时拆分
      if (this.scopeRow.length > 0) {
        if (this.scopeRow.length > 1) {
          this.$alert("不能同时拆分多个特征", "提示", {
            type: 'warning',
            confirmButtonText: '确定',
          })
          return false
        }
        let splitDisable = this.splitDisable()
        if (!splitDisable) {
          return false
        }
        var rowId = Math.floor((Math.random() * 9999) + 1000);
        var arr = this.columnMerge()
        this.scopeRow.forEach((rowItem, rowIndex) => {
          rowItem.ifChange=true
          // 将字段的值给到拆分新数据
          var splitAdd = JSON.parse(JSON.stringify(rowItem))
          splitAdd.featureId = rowItem.featureId + rowId + "a"
          // 将部分展示字段置为空
          for (let i = 0; i < arr.length; i++) {
            splitAdd[arr[i]] = ''
          }

          this.tableData.splice(this.scopeRow[0].$index + 1, 0, splitAdd)
        })
        this.handleSort(this.scopeRow[0].rightSort)
        this.typeSelect(this.showType)
        this.scopeRow = []
        this.checkList = []
      }
    },
    // 侵权分析或FTO有对比结果禁止进行合并、拆分操作
    splitDisable() {
      if (this.reportType == 5) {
        return true
      }
      try {
        for (var i = 0; i < this.scopeRow.length; i++){
          for (var j = 0; j < this.columnList.length; j++){
            var str = this.getColumnData(this.scopeRow[i], this.columnList[j])
            if (str != 0 && !str) {
              
            } else {
              throw Error();
            }
          }
        }
        return true
      }
      catch (e) {
        this.$message.error('您勾选的特征已填写对比结果信息，无法对勾选的特征进行合并、拆分等操作')
        return false
      }
    },
    // 拆分或合并后重新排序
    handleSort(rightSort) {
      // var data = this.tableData2.filter(item => {
      //   return item.rightSort == rightSort
      // })
      // for (var i = 0; i < data.length; i++) {
      //   data[i].sysOrder = i + 1
      // }
    },
    // 协同对比结果高亮
    checkDel({ row, rowIndex }) {
      for (let k in row.finalRecordVO) {
        if (k != 'id') {
          if (row.finalRecordVO[k] != row.currentRecordVO[k]) {
            return 'success-rowCheck'
          }
        }
      }
    }

  },
}
</script>
<style>
.success-rowCheck {
    background: #e1b0a7;
  }
</style>
<style lang="scss" scoped></style>