<template>
  <div class="el-table-extend">
    <el-table
      :ref="tableid"
      :data="tableData"
      :border="border"
      :size="size"
      :width="width"
      :height="height"
      :maxHeight="maxHeight"
      :fit="fit"
      :stripe="stripe"
      :rowKey="rowKey"
      :context="context"
      :showHeader="showHeader"
      :showSummary="showSummary"
      :sumText="sumText"
      :summaryMethod="summaryMethod"
      :rowClassName="rowClassName"
      :rowStyle="rowStyle"
      :cellClassName="cellClassName"
      :cellStyle="cellStyle"
      :headerRowClassName="headerRowClassName"
      :headerRowStyle="headerRowStyle"
      :headerCellClassName="headerCellClassName"
      :headerCellStyle="headerCellStyle"
      :highlightCurrentRow="highlightCurrentRow"
      :currentRowKey="currentRowKey"
      :emptyText="emptyText"
      :expandRowKeys="expandRowKeys"
      :defaultExpandAll="defaultExpandAll"
      :defaultSort="defaultSort"
      :tooltipEffect="tooltipEffect"
      :spanMethod="spanMethod"
      :selectOnIndeterminate="selectOnIndeterminate"
      @selection-change="e_handleSelectionChange"
      @cell-click="e_cellClick"
      @current-change="e_handleRowClick"
      >
      <el-table-column v-if="selection"
        type="selection"
        width="35">
      </el-table-column>
      <el-table-column v-for="item in head" :key="item.key"
        :prop="item.key"
        :label="item.label"
        :show-overflow-tooltip="item.showOverflowTooltip ? true: false"
        :width="item.width ? item.width : ''">
      </el-table-column>
      <slot name="control-column" :data="tableData"></slot>
    </el-table>
    <div class="el-table-extend__pager">
      <el-pagination
        background
        @size-change="e_handleSizeChange"
        @current-change="e_handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"        
        :current-page="currentPage"
        :page-size="pageSize"
        :page-count="pageCount"
        :total="total"
        >
      </el-pagination>
    </div>
  </div>
</template>
<script>
import ElTable from 'uke-ui/packages/table';
import ElTableColumn from 'uke-ui/packages/table-column';
import ElPagination from 'uke-ui/packages/pagination';
import Util from './util';

export default {
  name: 'ElTableExtend',
  componentName: 'ElTableExtend',
  data() {
    return {
      tableid: '',
      getTable: null
    }
  },
  props: {
    /* 扩展的参数 */

    /**
     * @augments data 后台接口的数据data
     * */
    data: {
      type: Object,
      default() {
        return {};
      }
    },

    /**
     * @augments head[{dataItem}] 表头数据
     * {
     *   key: String, // 字段名
     *   label: String, // 显示文字
     *   formatter: 'Date/Dictionary/Flow', // 格式化类型 可选
     *   formatterDic: Object // 字典对象 可选（如果formatter为Dictionary时必填）
     * }
     * */
    head: {
      type: Array,
      default() {
        return [];
      }
    },

    /**
     * @augments selection 是否多选
     */
    selection: {
      type: Boolean,
      default: false
    },

    /**
     * @augments currentChange 页码改变回调
     */
    currentChange: {
      type: Function
    },

    /**
     * @augments rowClick 点击行改变回调
     */
    rowClick: {
      type: Function
    },

    /**
     * @augments sizeChange 每页容量改变回调
     */
    sizeChange: {
      type: Function
    },

    /**
     * @augments selectionChange 选择改变回调
     */
    selectionChange: {
      type: Function
    },

    /**
     * @augments cellClick cell点击回调
     */
    cellClick: {
      type: Function
    },

    /* 原来 ElTable 参数 */

    size: String,

    width: [String, Number],

    height: [String, Number],

    maxHeight: [String, Number],

    fit: {
      type: Boolean,
      default: true
    },

    stripe: Boolean,

    border: Boolean,

    rowKey: [String, Function],

    context: {},

    showHeader: {
      type: Boolean,
      default: true
    },

    showSummary: Boolean,

    sumText: String,

    summaryMethod: Function,

    rowClassName: [String, Function],

    rowStyle: [Object, Function],

    cellClassName: [String, Function],

    cellStyle: [Object, Function],

    headerRowClassName: [String, Function],

    headerRowStyle: [Object, Function],

    headerCellClassName: [String, Function],

    headerCellStyle: [Object, Function],

    highlightCurrentRow: Boolean,

    currentRowKey: [String, Number],

    emptyText: String,

    expandRowKeys: Array,

    defaultExpandAll: Boolean,

    defaultSort: Object,

    tooltipEffect: String,

    spanMethod: Function,

    selectOnIndeterminate: {
      type: Boolean,
      default: true
    }

    /* 暂不支持 ElTableColumn 参数*/

  },
  computed: {
    tableData() {
      const tableData = this.data.dataList ? this.getTableFun(this.data.dataList) : [];
      return tableData;
    },
    pageSize() {
      return this.data.perPageCount;
    },
    total() {
      return this.data.totalCount;
    },
    pageCount() {
      return this.data.perPageCount;
    },
    currentPage() {
      return this.data.currentPage;
    }
  },
  components: {
    ElTable,
    ElTableColumn,
    ElPagination
  },
  methods: {
    setCurrentRow (index) {
      const row = this.tableData[index]
      this.$refs[this.tableid].setCurrentRow(row)
    },
    e_cellClick(row, column, cell, event) {
      let columnKey = column.type; // default/selection
      if (column.type === 'default') {
        columnKey = column.property
      }
      
      this.cellClick && this.cellClick(row, columnKey)
    },
    e_handleSelectionChange(data) {
      this.selectionChange && this.selectionChange(data)
    },
    e_handleSizeChange(data) {
      this.sizeChange && this.sizeChange(data);
    },
    e_handleCurrentChange(data) {
      this.currentChange && this.currentChange(data);
    },
    e_handleRowClick(row, oldRow) {
      this.rowClick && this.rowClick(row, oldRow)
    },
    getTableFun(dataList) {
      if (!this.getTable) {
        this.getTable = this._getTable();
      }
      return this.getTable(dataList);
    },
    _getTable() {
      const that = this;
      const formatterMap = {};
      const formatterFun = {
        'Date': function(data, formatter) {
          return Util.dateFomatter(data);
        },
        'Dictionary': function(data, formatter) {
          return formatter.formatterDic[data];
        }
      };
      return function(dataList) {
        const result = [];

        if (!dataList || dataList.length === 0) return result;

        if (Util.objectIsEmpty(formatterMap)) {
          if (that.head.length === 0) return result;
      
          that.head.map((item, index) => {
            if (!item.formatter) return;
            formatterMap[item.key] = {
              formatter: item.formatter,
              formatterDic: item.formatterDic ? item.formatterDic : undefined
            };
          })
        }
        dataList.map((data, index) => {
          for (const key in data) {
            const thisFormatter = formatterMap[key];
            if (thisFormatter && typeof thisFormatter.formatter == 'string') {
              dataList[index][key] = formatterFun[thisFormatter.formatter](data[key], thisFormatter);
            } else if (thisFormatter && typeof thisFormatter.formatter == 'function') {
              dataList[index][key] = thisFormatter.formatter(data[key]);
            } else {
              dataList[index][key] = data[key];
            }
          }
          result.push(dataList[index]);
        })

        return result;
      }
    }
  },
  mounted() {
    this.tableid = `${Date.now().toString().substr(-4)}-table`;
  }
}

</script>