<template>
  <div class="v-table">
    <a-spin :spinning="localLoading" tip="Loading...">
      <ve-table
        ref="tableRef"
        style="width:100%;word-break:break-all;"
        :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"
        :cell-style-option="cellStyleOption"
        :row-style-option="{clickHighlight: true}"
        :cellSelectionOption="{enable: false}"
        :virtual-scroll-option="{enable: !showPagination}"
        :sort-option="sortOption"
        :checkbox-option="checkboxOption"
        :event-custom-option="eventCustomOption"
      />
      <div v-show="localDataSource.length==0" :style="{height:(showPagination?scroll.y-35:scroll.y)+'px',position:!showPagination?'absolute':'relative',top:!showPagination?0:''}" class="empty-data"><a-empty description="暂无数据" :image="simpleImage"/></div>
      <div class="v-pagination" :class="'v-pagination-align-'+pageAlign">
        <div class="v-page-left" v-if="pageAlign=='right'"><slot name="page"></slot></div>
        <div class="v-page-no" v-if="showPagination&&localPagination.total">
          <a-pagination
            size="small"
            :total="localPagination.total"
            v-model="localPagination.current"
            :pageSize="localPagination.pageSize"
            :showTotal="total => `共 ${total} 条记录`"
            :pageSizeOptions="['10', '20', '30', '40', '50', '100', '300', '500']"
            :show-quick-jumper="localPagination.showQuickJumper"
            @change="paginationChange"
            show-size-changer
            @showSizeChange="paginationShowSizeChange"
          />
        </div>
        <div class="v-page-right" v-if="pageAlign=='left'"><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: false
    },
    // 数据
    dataSource: {
      type: Array,
      default: () => []
    },
    // 默认是否加载表格数据
    defaultLoadData: {
      type: Boolean,
      default: true
    },
    // 表格宽度和高度
    scroll: {
      type: Object,
      default: () => { return { x: 0, y: 400 } }
    },
    // 是否显示边框
    bordered: {
      type: Boolean,
      default: true
    },
    // 表格默认key name
    rowKeyName: {
      type: String,
      default: 'id'
    },
    // 分页配置
    pagination: {
      type: Object
    },
    // 是否显示分页
    showPagination: {
      type: Boolean,
      default: true
    },
    // 分页对齐方式，left ，center，right
    pageAlign: {
      type: String,
      default: 'center'
    },
    // 是否开启多选
    rowSelection: {
      type: Object,
      default: () => null
    },
    disableSelectedRowKeys: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    veColumns () {
      return this.convertColumns(this.columns)
    },
    // 表格复选框设置
    checkboxOption () {
      return {
        disableSelectedRowKeys: this.disableSelectedRowKeys,
        selectedRowKeys: this.selectedRowKeys,
        // 行选择改变事件
        selectedRowChange: ({ row, isSelected, selectedRowKeys }) => {
          this.selectedRowChange({ row, isSelected, selectedRowKeys })
        },
        // 全选改变事件
        selectedAllChange: ({ isSelected, selectedRowKeys }) => {
          this.selectedAllChange({ isSelected, selectedRowKeys })
        }
      }
    }
  },
  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 }) => {}
      },
      // 单元格样式
      cellStyleOption: {
        bodyCellClass: ({ row, column, rowIndex }) => {}
      },
      // 排序
      sortOption: {
        // sort always
        sortAlways: false,
        sortChange: (params) => {
          this.sortChange(params)
        }
      },
      // 分页
      localPagination: Object.assign({
        current: 1,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: false
      }, this.pagination),
      // 选中的项
      selectedRowKeys: [],
      selectedRows: [],
      eventCustomOption: {
        bodyRowEvents: ({ row, column, rowIndx }) => {
          return {
            click: (event) => {
              this.$emit('rowClick', event, row, rowIndx)
            },
            dblclick: (event) => {
              this.$emit('dblRowClick', event, row, rowIndx)
            },
            contextmenu: (event) => {},
            mouseenter: (event) => {},
            mouseleave: (event) => {},
            mousemove: (event) => {},
            mouseover: (event) => {},
            mousedown: (event) => {},
            mouseup: (event) => {}
          }
        }
      }
    }
  },
  created () {
    if (this.defaultLoadData && this.data) {
      this.loadData()
    }
    if (!this.data) {
      this.localDataSource = this.dataSource
    }
  },
  watch: {
    dataSource: {
      handler () {
        this.localDataSource = this.dataSource
      },
      deep: true
    }
  },
  methods: {
    // 选择单元格
    selectedRowChange ({ row, isSelected, selectedRowKeys }) {
      console.log(isSelected, selectedRowKeys)
      // 选中
      if (isSelected) {
        this.selectedRows.push(row)
      } else {
        // 取消
        this.selectedRows = this.selectedRows.filter(item => item[this.rowKeyName] !== row[this.rowKeyName])
      }
      this.selectedRowKeys = selectedRowKeys
      this.onRowSelection()
      this.$emit('selectRowChange', { row, isSelected, selectedRowKeys })
    },
    // 全选或取消本页行
    selectedAllChange ({ isSelected, selectedRowKeys }) {
      console.log(isSelected, selectedRowKeys)
      // 全选
      if (isSelected) {
        // 合并数组，并去重
        this.selectedRows = this.selectedRows.concat(this.localDataSource).reduce((prev, next) => {
          if (!prev.find(item => item[this.rowKeyName] === next[this.rowKeyName])) {
            prev.push(next)
          }
          return prev
        }, [])
      } else {
        // 取消全选，删除当前页选项
        const changeRowKeys = this.localDataSource.map(item => item[this.rowKeyName])
        this.selectedRows = this.selectedRows.filter(item => !changeRowKeys.includes(item[this.rowKeyName]))
      }
      this.selectedRows = this.selectedRows.filter(item => !this.disableSelectedRowKeys.includes(item[this.rowKeyName]))
      this.selectedRowKeys = selectedRowKeys
      this.onRowSelection()
      this.$emit('selectAllRowChange', { isSelected, selectedRowKeys })
    },
    // 触发已选项事件
    onRowSelection () {
      // console.log(this.selectedRows)
      const result = this.selectedRows
      const selectedRowKeys = result.map(item => item[this.rowKeyName])
      this.$emit('rowSelection', { selectedRows: result, selectedRowKeys: selectedRowKeys })
    },
    // 页码改变的时候设置新页的已选项
    setCheckedRows () {
      const list = this.selectedRows.map(item => item[this.rowKeyName])
      this.selectedRowKeys = this.localDataSource.filter(item => list.includes(item[this.rowKeyName])).map(item => item[this.rowKeyName])
    },
    /**
     * 清空 table 已选中项
     */
    clearSelected () {
      this.selectedRowKeys = []
      this.selectedRows = []
      this.onRowSelection()
    },
    // 设置 table 已选中项
    setTableSelected (selectedRowKeys) {
      this.selectedRows = selectedRowKeys.map(item => { const obj = {}; obj[this.rowKeyName] = item; return obj })
      this.setCheckedRows()
    },
    // 通过key.key...获取属性值
    getNestedPropertyValue (obj, path) {
      return path.split('.').reduce(function (o, p) {
        if (!o) return
        return o[p]
      }, obj || {})
    },
    // 转换colums数据结构，兼容老页面
    convertColumns (columns) {
      const ret = []
      const _this = this
      for (let i = 0; i < columns.length; i++) {
        const item = columns[i]
        const windowWidth = window.innerWidth - 200
        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: String(item.width).indexOf('%') >= 0 ? Number(String(item.width).replace('%', '') * windowWidth / 100) : Number(String(item.width).replace('px', '')), // 百分比转数字
          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,
          hasEllipsis: item.ellipsis,
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            // 如果field 是obj.objkey.objkey...形式
            const text = column.field ? (column.field.indexOf('.') >= 0 ? _this.getNestedPropertyValue(row, column.field) : row[column.field]) : null
            // 有自定义单元格
            if (column.scopedSlotsKey) {
              return _this.$scopedSlots[column.scopedSlotsKey](text, row, rowIndex, column)
            }
            // 省略字符
            if (item.ellipsis && column.field && text) {
              return (
                <a-tooltip placement="right">
                  <template slot="title">
                    <span>{text}</span>
                  </template>
                  <span class="ve-table-body-td-span-ellipsis" style="-webkit-line-clamp: 1;">{text || '--'}</span>
                </a-tooltip>
              )
            }
            return item.customRender ? item.customRender(text) : text || '--'
          }
        })
      }
      // 判断是否开启多选框
      const hasCheckbox = ret.find(item => item.type == 'checkbox')
      // 兼容老版本表格
      if (!hasCheckbox && this.rowSelection) {
        ret.unshift({ title: '', field: 'checkbox', key: 'checkbox', width: 20, type: 'checkbox', align: 'center' })
      }
      return ret
    },
    /**
     * 加载数据方法
     * @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.setCheckedRows()
          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
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .v-table {
    width: 100%;
    > div{
      height: 100%;
    }
    .ant-spin-container{
      height: 100%;
    }
    .empty-data{
        color: #999;
        text-align: center;
        width: 100%;
        display: flex;
        align-items: center;
        flex-direction: column;
        justify-content: center;
    }
    .v-pagination{
      display:flex;
      align-items: center;
    }
    .v-pagination-align-right{
      justify-content: space-between;
    }
    .v-pagination-align-left{
      justify-content: space-between;
    }
    .v-pagination-align-center{
      justify-content: center;
    }
    .v-page-no{
      padding: 10px 0;
    }
    /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>
