<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="allQty" label="任务总个数"> </el-table-column>
    <el-table-column prop="used" label="已用个数"> </el-table-column>
    <el-table-column prop="qty" label="任务个数">
      <template slot-scope="scope">
        <el-input-number
          :precision="0"
          v-model="scope.row.qty"
          @change="value => handleChange(scope.row, value)"
          @blur="handleBlur(scope.row)"
          :min="0"
          :max="scope.row.allQty - scope.row.used"
        ></el-input-number
      ></template>
    </el-table-column>
    <el-table-column prop="subtotal" label="任务积分值"></el-table-column>
  </el-table>
</template>

<script>
export default {
  props: ['propsTableData'],
  data() {
    return {
      tableData: []
    };
  },

  methods: {
    init() {
      this.tableData = [];
    },
    setData(data, planScore) {
      this.tableData = [...data];
      this.tableData.forEach((item, index) => {
        item.index = index;
        item.score = item.price;
        item.subtotal = 0;
        item.baseId = item.taskTypeName;
        item.allQty = item.qty;
        item.qty = 0;
      });
    },
    calculatePercentage(part, total) {
      if (total === 0) return 0; // 避免除以0错误
      return Number(((part / total) * 100).toFixed(2));
    },

    handleChange(row, value) {
      if (!value) {
        value = 0;
      }
      const subtotal = row.price * value;
      this.$set(this.tableData[row.index], 'subtotal', subtotal);
      this.$forceUpdate();
      const allTotal = this.tableData.reduce((prev, curr) => {
        return prev + curr.subtotal;
      }, 0);
      this.$emit('updateScope', allTotal);
    },
    handleBlur(row) {
      if (!row.qty) {
        this.$set(this.tableData[row.index], 'qty', 0);
        this.$forceUpdate();
      }
    },
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计';
        } else if (index === 6 || index === 7) {
          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];
      }
    },
    getDetail() {
      return this.tableData;
    }
  }
};
</script>
<style lang="scss" scoped>
.error {
  color: #f78989;
}
</style>
