<template>
  <el-table
    :data="tableData"
    style="width: 100%"
    max-height="400"
    border
    show-summary
    :summary-method="getSummaries"
    :span-method="spanMethod"
  >
    <el-table-column type="index" label="序号" width="50"> </el-table-column>
    <el-table-column prop="baseId" label="上级服务类型"></el-table-column>
    <el-table-column prop="percentage" label="占比（%）" width="100">
      <template slot-scope="scope">
        <span
          :class="{
            error:
              scope.row.score != 0 &&
              (scope.row.percentage < 25 || scope.row.percentage > 50)
          }"
          >{{ scope.row.percentage }}</span
        >
      </template>
    </el-table-column>
    <el-table-column prop="taskTypeName" label="任务类型"></el-table-column>
    <el-table-column prop="score" label="积分值"></el-table-column>
    <el-table-column prop="qty" label="任务个数"> </el-table-column>
    <el-table-column prop="subtotal" label="任务积分值"></el-table-column>
  </el-table>
</template>

<script>
export default {
  props: ["propsTableData", "planScore"],
  data() {
    return {
      tableData: []
    };
  },
  watch: {
    propsTableData(newVal, oldVal) {
      this.tableData = [...newVal];
      let arr = this.tableData.map(item => item.baseId);
      arr = [...new Set(arr)];
      for (let currBaseId of arr) {
        const allSubtotal = this.tableData.reduce(
          (accumulator, currentValue) => {
            if (currentValue.baseId === currBaseId) {
              return accumulator + currentValue.subtotal;
            }
            return accumulator;
          },
          0
        );
        const percentage = this.calculatePercentage(
          allSubtotal,
          this.planScore
        );
        this.tableData.forEach(item => {
          if (item.baseId === currBaseId) {
            item.percentage = percentage;
          }
        });
      }
    }
  },

  methods: {
    calculatePercentage(part, total) {
      if (total === 0) return 0; // 避免除以0错误
      return Number(((part / total) * 100).toFixed(2));
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总计";
        } else if (index === 5 || index === 6) {
          const values = data.map(item => Number(item[column.property]));
          sums[index] = values.reduce((prev, curr) => prev + curr, 0);
          sums[index] = sums[index].toFixed(); // 保留整数
        } else {
          sums[index] = "--";
        }
      });
      return sums;
    },
    spanMethod({ row, column, rowIndex, columnIndex }) {
      // 只对 baseId (第二列) 和 percentage (第三列) 进行合并
      if (columnIndex === 1 || columnIndex === 2) {
        const currentBaseId = this.tableData[rowIndex].baseId;

        // 确定从当前行开始有多少行需要合并
        let rowspan = 1;
        for (let i = rowIndex + 1; i < this.tableData.length; i++) {
          if (this.tableData[i].baseId === currentBaseId) {
            rowspan++;
          } else {
            break;
          }
        }
        // 如果是需要显示的合并单元格
        if (
          rowIndex === 0 ||
          this.tableData[rowIndex - 1].baseId !== currentBaseId
        ) {
          return [rowspan, 1]; // rowspan 表示合并的行数, colspan 为 1
        }
        // 如果是已经合并的行，返回 [0, 0]
        return [0, 0];
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.error {
  color: #f78989;
}
</style>
