<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Kole UI · SummaryRowTable</title>
  <link rel="stylesheet" href="../.design_library/kole-ui/colors_and_type.css" />
  <link rel="stylesheet" href="./SummaryRowTable.css" />
</head>
<body>
  <div class="kole-page">
    <h2 class="kole-h2">SummaryRowTable 统计汇总表格</h2>
    <p class="kole-desc">表格底部显示汇总行（合计 / 平均值 / 最大值 / 最小值 / 计数），可配置汇总字段。</p>

    <div class="kole-demo">
      <div class="kole-demo__title">销售明细与汇总</div>
      <table class="kole-sumtable" id="sumtable">
        <thead><tr><th>产品</th><th>数量</th><th>单价</th><th>金额</th></tr></thead>
        <tbody></tbody>
        <tfoot></tfoot>
      </table>
    </div>
  </div>

  <script>
    var data = [
      { name: '基础版', qty: 10, price: 99, amount: 990 },
      { name: '标准版', qty: 6, price: 199, amount: 1194 },
      { name: '旗舰版', qty: 3, price: 499, amount: 1497 }
    ];
    // 汇总配置：字段 -> 类型
    var summary = { qty: 'sum', amount: 'sum', price: 'avg' };
    var cols = ['name', 'qty', 'price', 'amount'];

    function compute(key, type) {
      var arr = data.map(function (d) { return d[key]; });
      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 '';
    }

    var tbody = document.querySelector('#sumtable tbody');
    tbody.innerHTML = data.map(function (d) {
      return '<tr><td>' + d.name + '</td><td>' + d.qty + '</td><td>' + d.price + '</td><td class="' +
        (d.amount >= 1200 ? 'is-pos' : '') + '">¥' + d.amount + '</td></tr>';
    }).join('');

    var tfoot = document.querySelector('#sumtable tfoot');
    var cells = cols.map(function (c) {
      if (c === 'name') return '<td class="kole-sum-label">合计 / 平均</td>';
      if (summary[c]) return '<td>' + compute(c, summary[c]) + '</td>';
      return '<td></td>';
    });
    tfoot.innerHTML = '<tr class="kole-sumrow">' + cells.join('') + '</tr>';
  </script>
</body>
</html>
