<template>
  <!-- 权要拆分类型等 -->
  <div class="height_100">
    <el-container>
      <el-header 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>
            <slot name="handleRight"></slot>
          </div>
          <div v-if="isEdit">
            <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%">
          <el-table-column prop="pRightName" label="权要" width="180" 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="特征" 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;">
                    <el-input type="textarea" style="width:250px" autosize v-model="scope.row.content">
                      {{ scope.row.content }}</el-input>
                  </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 in columnList" :key="item.value" :prop="item.value" :label="item.name"
            align="center">
            <template slot-scope="scope">
              <div v-if="isEdit">
                <myRichText style="text-align:left" v-model="scope.row[item.value]" :placeholder="'请输入' + item.name">
                </myRichText>
              </div>
              <div v-else v-html="scope.row[item.value]"></div>
            </template>
          </el-table-column>

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




  </div>
</template>

<script>
export default {
  props: {
    // 信息(patentNo,reportId)
    word: {
      type: Object,
      default: () => {
        return {
          patentNo: '',
          projectId: ''
        }
      }
    },
    // 数据源
    tableData: {
      type: Array,
      default: () => {
        return []
      }
    },
    // 是否可读
    isEdit: {
      type: Boolean,
      default: true
    },
    // 栏位参数 
    columnList: {
      type: Array,
      default: () => {
        return []
      }
    },

  },
  data() {
    return {
      tableData2: [],//显示数据
      splitType: '1',//拆分类型0仅拆主权要，1全部拆分
      splitBy: '2',//拆分符号0逗号拆分，1分号拆分，2逗号和分号拆分
      showType: '0',//显示类型0全部显示1仅显示主权要
      typeArr: [1],//显示权要还是全部显示
      // 表格的loading
      loading: false,
      // 表格的高度
      tableHeight: 0,
      // 勾选中的特征数据
      checkList: [],
      // 计算表格合并行的数量
      mergeObj: {},
      // 表格合并行的栏位
      mergeArr: ['id', 'pRightName'],
      // 特征行数据
      scopeRow: [],
      //权要列表
      rightList: [],

    }
  },
  watch: {
    tableData: {
      handler(newVal, oldVal) {
        this.typeSelect(this.showType)
      },
      deep: true
    },
  },

  async mounted() {
    //获取权要
    this.getRight()
  },
  methods: {
    // 查询拆分信息
    // async getSplitMessage() {
    //   let params = {
    //     ...this.word,
    //   }

    //   await this.$api.getSplitMessage(params).then(res => {
    //     if (res.code == 200) {
    //       this.splitType = res.data.data.splitType.toString()
    //       this.splitBy = res.data.data.splitBy.toString()
    //       let obj = {
    //         splitType: this.splitType,
    //         splitBy: this.splitBy
    //       }
    //       this.$emit('splitSelect', obj)
    //     }
    //   }).catch(error => {
    //     this.splitType = ''
    //     this.splitBy = ''
    //     this.showType = '0'
    //   })
    // },

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

      this.scopeRow = []
      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] = ''
        })
        // 将内容合并起来
        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.id == item.id })
          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.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
        }
        var rowId = Math.floor((Math.random() * 9999) + 1000);
        var arr = this.columnMerge()
        this.scopeRow.forEach((rowItem, rowIndex) => {
          // 将字段的值给到拆分新数据
          var splitAdd = JSON.parse(JSON.stringify(rowItem))
          splitAdd.id = rowItem.id + 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 = []
      }
    },
    // 拆分或合并后重新排序
    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
      }
    },
  },
}
</script>

<style lang="scss" scoped></style>