// stat_total	计算列中所有值的和
// stat_multi_total	计算2列合计的乘积
// stat_max	显示列中的最大值
// stat_min 显示列中的最小值
// stat_average	计算列中所有值的平均值
// stat_count	计算列中的行数
              //  Math.round((~~count + ~~obj[key] + Number.EPSILON) * 1000) / 1000

const total = (key, currentPageData) => {
  return currentPageData.reduce((pre, cur) => isFinite(+cur[key]) ? +cur[key] + pre : pre, 0)
}
const average = (key, currentPageData) => {
  const len = currentPageData.length
  return len === 0 ? 0 : total(key, currentPageData) / len
}
const statFns = {
  total,
  average
}
export function createFooting(props, currentPageData) {
  let h = this._c;

  let { attachFooter, columns, bordered, rowKey, scroll } = props;
  let rowSelection = { ...props.rowSelection };
  delete rowSelection.onSelect;
  delete rowSelection.onChange;
  delete rowSelection.onSelectAll;
  delete rowSelection.selectedRowKeys;
  let sColumns = columns.map(item => {
    let el = { ...item }
    delete el.scopedSlots
    delete el.customRender
    return el
  });


  let dataSource = {key:0};
  /**@ stat
   * stat.total 计算总和
   * stat.average 平均值
   */

  if (attachFooter) {

    if (Array.isArray(attachFooter)) {
      attachFooter = attachFooter.reduce((obj, { key, ...attrs }) => {
        return key ? { ...obj, [key]: attrs } : obj
      }, {})
    }
    for (let key of Object.keys(attachFooter)){
      const col = attachFooter[key]
      const statFn = statFns[col.stat] || total
      let statResult = statFn(key, currentPageData)
      statResult=Math.round((statResult + Number.EPSILON) * 10000) / 10000
      dataSource[key] = (col.prefixUnit || '') + statResult + (col.unit || '')

                    //  Math.round((~~count + ~~obj[key] + Number.EPSILON) * 1000) / 1000

      this._l(sColumns, (item, index) => {
        let _key = item.dataIndex || item.key
        if (key === _key) {
          sColumns[index] = { ...item, ...col }
          delete sColumns[index].stat
        }
      });
    }
  }

  let transformCellText = ({ text, column, record, index }) => {
    if (column.key == 'selection-column') {
      text = '';
    }
    if (column.key == this.defaultCountKey) {
      if (attachFooter[column.key]?.customRender) {
        return text;
      }
      text = '合计';
    }
    return text;
  };

  //  sColumns[1].colSpan =0

  let config = {
    transformCellText,
    rowKey:'key',
    columns: sColumns,
    rowSelection,
    scroll: {
      x:scroll.x
    },
    attachFooter: false,
    showHeader: false,
    dataSource: [dataSource],
    pagination: false,
    bordered,
    // rowSelectType: 0,
    // rowSelectFixed:false

    // bodyStyle: {overflow: "hidden"}
  };

  if (!props.rowSelectType) {
    delete config.rowSelection;
  }


  return h('a-table', { class: 't-attach-footer-table', attrs: config, directives: [{ name: 'show', value: this.dataSource?.length>0 }] });
}

export default createFooting;
