<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)">{{ 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] ? compute(c.key, summary[c.key]) : '') }}
        </td>
      </tr>
    </tfoot>
  </table>
</template>

<script setup>
const props = defineProps({
  data: { type: Array, default: () => [] },
  columns: { type: Array, default: () => [] },
  summary: { type: Object, default: () => ({}) },
  labelKey: { type: String, default: 'name' },
  labelText: { type: String, default: '合计 / 平均' }
});

function cellClass(row, c) {
  return c.pos && row[c.key] >= c.pos ? 'is-pos' : '';
}
function compute(key, type) {
  const arr = props.data.map((d) => Number(d[key]) || 0);
  if (!arr.length) return '';
  if (type === 'sum') return arr.reduce((a, b) => a + b, 0);
  if (type === 'avg') return +(arr.reduce((a, b) => a + b, 0) / arr.length).toFixed(1);
  if (type === 'max') return Math.max(...arr);
  if (type === 'min') return Math.min(...arr);
  if (type === 'count') return arr.length;
  return '';
}
</script>

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