<template>
  <div class="v-table">
    <a-spin :spinning="localLoading" tip="Loading...">
      <ve-table
        ref="tableRef"
        style="width:100%"
        :max-height="scroll.y"
        :scroll-width="scroll.x"
        :columns="veColumns"
        :table-data="localDataSource"
        :row-key-field-name="rowKeyName"
        :border-x="true"
        :border-y="bordered"
        :border-around="bordered"
        :column-width-resize-option="columnWidthResizeOption"
        :columnHiddenOption="columnHiddenOption"
        :row-style-option="{clickHighlight: true}"
        :cellSelectionOption="{enable: false}"
        :virtual-scroll-option="{enable: true}"
        :sort-option="sortOption"
      />
      <div v-show="localDataSource.length==0" :style="{height:scroll.y+'px'}" class="empty-data"><a-empty description="暂无数据" :image="simpleImage"/></div>
      <div class="ve-pagination" :class="'ve-pagination-align-'+pageAlign">
        <div class="ve-page-left" v-if="pageAlign=='left'"><slot name="page"></slot></div>
        <a-pagination
          v-show="showPagination"
          size="small"
          :total="localPagination.total"
          v-model="localPagination.current"
          :pageSize="localPagination.pageSize"
          :showTotal="total => `共 ${total} 条记录`"
          :pageSizeOptions="localPagination.pageSizeOptions"
          :show-quick-jumper="localPagination.showQuickJumper"
          @change="paginationChange"
          show-size-changer
          @showSizeChange="paginationShowSizeChange"
        />
        <div class="ve-page-right" v-if="pageAlign=='right'"><slot name="page"></slot></div>
      </div>
    </a-spin>
  </div>
</template>

<script>
import { Empty } from 'ant-design-vue'
export default {
  name: 'VTable',
  props: {
    // 列
    columns: {
      type: Array,
      default: () => []
    },
    // load data function
    data: {
      type: Function,
      required: true
    },
    // 默认是否加载表格数据
    defaultLoadData: {
      type: Boolean,
      default: true
    },
    // 表格宽度和高度
    scroll: {
      type: Object,
      default: () => ({ x: 0, y: 400 })
    },
    // 是否显示边框
    bordered: {
      type: Boolean,
      default: true
    },
    // 表格默认key name
    rowKeyName: {
      type: String,
      default: 'id'
    },
    // 默认隐藏的列，传 filed 值
    defaultHiddenColumnKeys: {
      type: Array,
      default: () => []
    },
    // 分页配置
    pagination: {
      type: Object
    },
    // 是否显示分页
    showPagination: {
      type: Boolean,
      default: true
    },
    // 分页对齐方式，left ，center，right
    pageAlign: {
      type: String,
      default: 'center'
    }
  },
  computed: {
    veColumns () {
      return this.convertColumns(this.columns)
    }
  },
  data () {
    return {
      localLoading: false,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      localDataSource: [],
      sortObj: null,
      isSucceed: true, //  是否请求成功
      // 拖到列宽
      columnWidthResizeOption: {
        // default false
        enable: true,
        // column resize min width
        minWidth: 30,
        // column size change
        sizeChange: ({ column, differWidth, columnWidth }) => {}
      },
      columnHiddenOption: {
        // default hidden column keys
        defaultHiddenColumnKeys: this.defaultHiddenColumnKeys
      },
      // 排序
      sortOption: {
        // sort always
        sortAlways: false,
        sortChange: (params) => {
          this.sortChange(params)
        }
      },
      // 分页
      localPagination: Object.assign({
        current: 1,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: false
      }, this.pagination)
    }
  },
  created () {
    if (this.defaultLoadData) {
      this.loadData()
    }
  },
  methods: {
    // 转换colums数据结构，兼容老页面
    convertColumns (columns) {
      const ret = []
      const _this = this
      for (let i = 0; i < columns.length; i++) {
        const item = columns[i]
        ret.push({
          field: item.field || item.dataIndex,
          key: item.key || 'col-' + i,
          title: item.title,
          // 自定义头部单元格表头
          renderHeaderCell: ({ column }, h) => {
            if (item.slots) {
              return _this.$scopedSlots[item.slots.title]()
            }
            if (item.align != 'center') {
              return (
                <div style="text-align:center;">{column.title}</div>
              )
            }
            return h('span', column.title)
          },
          width: item.width.indexOf('%') >= 0 ? item.width.replace('%', '') * 12 : item.width, // 百分比转数字
          align: item.align,
          fixed: item.fixed,
          sortBy: item.sortBy || item.sorter ? '' : undefined,
          children: item.children ? _this.convertColumns(item.children) : undefined,
          // 自定义单元格
          scopedSlotsKey: item.scopedSlots && item.scopedSlots.customRender,
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            const text = row[column.field]
            if (column.scopedSlotsKey) {
              return _this.$scopedSlots[column.scopedSlotsKey](text, row, rowIndex, column)
            }
            if (item.ellipsis && column.field) {
              return (
                <a-tooltip placement="right">
                  <template slot="title">
                    <span>{text}</span>
                  </template>
                  <span style="width:100%;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">{text}</span>
                </a-tooltip>
              )
            }
            return item.customRender ? h('span', item.customRender(text)) : h('span', text || '--')
          }
        })
      }
      return ret
    },
    // hidden columns
    hideColumns (keys) {
      this.$refs['tableRef'].hideColumnsByKeys(keys)
    },
    // show cloumns
    showColumns (keys) {
      this.$refs['tableRef'].showColumnsByKeys(keys)
    },
    /**
     * 加载数据方法
     * @param {Object} pagination 分页选项器
     * @param {Object} filters 过滤条件
     * @param {Object} sorter 排序条件
     */
    loadData (pagination, filters, sorter) {
      this.localLoading = true
      const parameter = Object.assign({
        pageNo: this.showPagination && this.localPagination.current || 1,
        pageSize: this.showPagination && this.localPagination.pageSize || 10
      },
      this.sortObj && { sortField: this.sortObj.field, sortOrder: this.sortObj.order } || {}
      )
      const result = this.data(parameter)
      // 对接自己的通用数据接口需要修改下方代码中的 r.pageNo, r.count, r.data
      if ((typeof result === 'object' || typeof result === 'function') && typeof result.then === 'function') {
        result.then(r => {
          const list = r.list || r.data || r || []
          this.isSucceed = !!r
          this.localPagination = this.showPagination && Object.assign({}, this.localPagination, {
            current: r.pageNo || 1, // 返回结果中的当前分页数
            total: Number(r.count) || 0, // 返回结果中的总记录数
            pageSize: r.pageSize || this.localPagination.pageSize
          }) || false

          // 为防止删除数据后导致页面当前页面数据长度为 0 ,自动翻页到上一页
          if (list.length === 0 && this.showPagination && this.localPagination.current > 1) {
            this.localPagination.current--
            this.loadData()
            return
          }

          // 这里用于判断接口是否有返回 r.count 且 this.showPagination = true 且 pageNo 和 pageSize 存在 且 count 小于等于 pageNo * pageSize 的大小
          // 当情况满足时，表示数据不满足分页大小，关闭 table 分页功能
          try {
            if ((['auto', true].includes(this.showPagination) && r.count <= (r.pageNo * this.localPagination.pageSize))) {
              // this.localPagination.hideOnSinglePage = true
            }
          } catch (e) {
            this.localPagination = false
          }
          this.localDataSource = list // 返回结果中的数组数据
          this.localLoading = false
        }).catch(err => {
          this.clearTable()
        })
      }
    },
    // 页码变更
    paginationChange (pageNumber) {
      this.localPagination.current = pageNumber
      this.loadData()
    },
    paginationShowSizeChange (current, pageSize) {
      this.localPagination.current = current
      this.localPagination.pageSize = pageSize
      this.loadData()
    },
    // 排序
    sortChange (params) {
      this.sortObj = null
      for (const a in params) {
        if (params[a]) {
          this.sortObj = {
            field: a,
            order: params[a] + 'end'
          }
        }
      }
      this.loadData()
    },
    /**
     * 表格重新加载方法
     * 如果参数为 true, 则强制刷新到第一页
     * @param Boolean bool
     */
    refresh (bool = false) {
      bool && (this.localPagination = Object.assign({}, {
        current: 1, pageSize: this.localPagination.pageSize
      }))
      this.loadData()
    },
    // 重置表格为空
    clearTable () {
      this.localLoading = false
      this.localDataSource = []
      this.sortObj = null
      this.clearSelected()
      this.localPagination = Object.assign({}, {
        current: 1, pageSize: this.localPagination.pageSize, total: 0
      })
    },
    /**
     * 清空 table 已选中项
     */
    clearSelected () {
      if (this.rowSelection) {
        this.selectedRows = []
        this.selectedRowKeys = []
        this.updateSelect()
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .v-table {
    width: 100%;
    > div{
      height: 100%;
    }
    .ant-spin-container{
      height: 100%;
    }
    .empty-data{
        color: #999;
        text-align: center;
        position: absolute;
        bottom: 0;
        width: 100%;
        display: flex;
        align-items: center;
        flex-direction: column;
        justify-content: center;
    }
    .ve-pagination{
      display:flex;
      align-items: center;
      padding: 20px 0 10px 0;
    }
    .ve-pagination-align-right{
      justify-content: flex-end;
    }
    .ve-pagination-align-left{
      justify-content: flex-start;
    }
    .ve-pagination-align-center{
      justify-content: center;
    }
    /deep/ .ve-table .ve-table-container .ve-table-content-wrapper table.ve-table-content tbody.ve-table-body tr.ve-table-body-tr td.ve-table-body-td,
    .ve-table .ve-table-container .ve-table-content-wrapper table.ve-table-content tbody.ve-table-body tr.ve-table-expand-tr td.ve-table-body-td{
      div:empty::before {
        content:'--'
      }
    }
  }
</style>
