<template>
  <table class="kole-sumtable">
    <thead><tr><th v-for="c in columns" :key="c.key">{{ c.title }}</th></tr></thead>
    <tbody>
      <tr v-for="(row, i) in data" :key="i">
        <td v-for="c in columns" :key="c.key" :class="cellClass(row, c)">{{ fmt(row[c.key]) }}</td>
      </tr>
    </tbody>
    <tfoot>
      <tr class="kole-sumrow">
        <td v-for="c in columns" :key="c.key" :class="{ 'kole-sum-label': c.key === labelKey }">
          {{ c.key === labelKey ? labelText : (summary[c.key] ? fmt(compute(c.key, summary[c.key])) : '') }}
        </td>
      </tr>
    </tfoot>
  </table>
</template>

<script>
export default {
  name: 'KoleSummaryRowTable',
  props: {
    data: { type: Array, default: () => [] },
    columns: { type: Array, default: () => [] },
    summary: { type: Object, default: () => ({}) },
    labelKey: { type: String, default: 'name' },
    labelText: { type: String, default: '合计 / 平均' }
  },
  methods: {
    fmt(v) { return v; },
    cellClass(row, c) {
      return c.pos && row[c.key] >= c.pos ? 'is-pos' : '';
    },
    compute(key, type) {
      var arr = this.data.map(function (d) { return Number(d[key]) || 0; });
      if (!arr.length) return '';
      if (type === 'sum') return arr.reduce(function (a, b) { return a + b; }, 0);
      if (type === 'avg') return +(arr.reduce(function (a, b) { return a + b; }, 0) / arr.length).toFixed(1);
      if (type === 'max') return Math.max.apply(null, arr);
      if (type === 'min') return Math.min.apply(null, arr);
      if (type === 'count') return arr.length;
      return '';
    }
  }
};
</script>

<style src="./SummaryRowTable.css"></style>
