<template>
<div class="honjo-data-table" :class="[typeCls]" v-loading="loading" @dblclick="onDbClick">
  <el-table @selection-change="onSelectionChange" @sort-change="onSortChange" :data="rows" :row-key="rowKey" ref="table" v-bind="props" size="medium">
    <slot>
      <template v-for="column in renderedColumns">
        <template v-if="$scopedSlots[column.prop]">
          <el-table-column :key="column.prop" v-bind="column">
            <slot :name="column.prop" :row="row" :column="column" slot-scope="{row}"></slot>
          </el-table-column>
        </template>
        <el-table-column :key="column.prop" v-bind="column" v-else>
          <template v-slot:header="" v-if="column.tooltip">
            <span>{{column.label}}</span>
              <el-tooltip effect="dark" placement="top">
                <div slot="content">
                  <span v-html="column.tooltip"></span>
                </div>
                <el-link :underline="false" style="line-height: 28px; margin-left: 4px;" class="el-icon-question"></el-link>
              </el-tooltip>
          </template>
        </el-table-column>
      </template>
    </slot>
  </el-table>
  <el-pagination
    v-if="pageable"
    class="honjo-data-table__pagination"
    background
    layout='prev, pager, next, jumper, sizes, total'
    :page-sizes="pageSizes"
    :total="total"
    :page-size="size"
    :current-page="page"
    @size-change="onSizeChange"
    @current-change="onPageChange"/>
</div>
</template>

<script lang="ts">

import { Vue, Component, Prop, Emit, Ref, Watch, Provide } from 'vue-property-decorator'
import { mixins } from 'vue-class-component'
import DataIterator from './DataIterator'
import { TableColumnDef } from './type'
import { bubble, copyToClipboard } from '../../utils/copy'

@Component
export default class HonjoDataTable extends mixins(DataIterator) {
  @Prop(Array) columns!: TableColumnDef[]
  @Prop({ type: Array, default: [5, 10, 20, 30, 40, 50, 100] }) pageSizes!: any[]

  @Prop({ type: String, default: 'admin' }) type!: 'admin' |'client'

  @Prop({ type: Object, default: () => Object.create(null) }) options: any

  // 多选相关
  @Prop(Array) checkedRows!: any[]

  @Prop(String) rowKey!: string

  @Emit('update:checkedRows') updateCheckedRows (rows: any[]) {}

  // 合计相关
  @Prop(Boolean) showSummary!: boolean

  @Prop(String) sumText!: string

  @Prop(Function) cellClassName!: (data: any) => void

  @Prop(Function) summaryMethod!: (args: { columns: any[]; data: any[] }) => string[]

  @Prop(Function) sizeChange!: (data: any) => void

  @Prop(Function) pageChange!: (data: any) => void

  @Prop(Function) spanMethod!: any

  @Prop(String) height!: string

  @Prop(String) maxHeight!: string

  @Prop({ type: Boolean, default: true }) copiable!: boolean

  @Ref() table!: any

  localCheckedRows: any[] = []

  updating = false

  get actualCheckedRows () {
    return this.checkedRows || this.localCheckedRows
  }

  set actualCheckedRows (rows: any[]) {
    this.localCheckedRows = rows
    if (!this.updating) this.updateCheckedRows(rows)
  }

  get renderedColumns () {
    return (this.columns || []).map(v => Object.assign(new TableColumnDef(), v))
  }

  get typeCls () {
    return `honjo-data-table--${this.type}`
  }

  get props () {
    return {
      ...this.options,
      stripe: true,
      border: true,
      showSummary: this.showSummary,
      sumText: this.sumText,
      summaryMethod: this.summaryMethod,
      cellClassName: this.cellClassName,
      spanMethod: this.spanMethod,
      height: this.height,
      maxHeight: this.maxHeight
    }
  }

  onPageChange (page: number) {
    this.pageChange && this.pageChange(page)
    this.load(this.params, page, this.size)
  }

  onSizeChange (size: number) {
    this.page = 1
    this.sizeChange && this.sizeChange(size)
    this.load(this.params, this.page, size)
  }

  onSelectionChange (val: any[]) {
    this.actualCheckedRows = val || []
  }

  onSortChange ({ column, prop, order }: any) {
    if (order === 'ascending') {
      this.sorter = { prop, asc: true }
    } else if (order === 'descending') {
      this.sorter = { prop, asc: false }
    } else {
      this.sorter = null
    }
    this.load(this.params, 1, this.size)
  }

  onDbClick (evt: any) {
    if (!this.copiable) return
    const source = evt.target || evt.srcElement
    if (!source) return
    if (!source.classList.contains('cell') || source.children.length > 0) return
    const text = source.textContent
    if (!text) return
    copyToClipboard(text)
    bubble(evt, '复制成功')
  }

  @Watch('checkedRows', { immediate: true }) checkedRowsChange () {
    if (!this.checkedRows || !this.table || this.updating) return
    if (this.checkedRows !== this.localCheckedRows) {
      this.updating = true
      const items = this.checkedRows.slice()
      this.table.clearSelection()
      items.forEach((v: any) => {
        this.table.toggleRowSelection(v, true)
      })
      this.updating = false
    }
  }
}
</script>

<style lang="scss" scoped>
@import "./style/index.scss";
.honjo-data-table__pagination ::v-deep .el-input__inner {
  width: 100px !important;
}
.honjo-data-table__pagination ::v-deep .el-input--mini {
    width: 100px !important;
}

</style>
