<template>
  <div class="gh-table" :style="tableClass">

    <div class="gh-table-content">
      <Table :data="tableData" :row-class-name="rowClassName" :loading="loading" stripe v-bind="$attrs" v-on="$listeners"></Table>
    </div>

    <div class="gh-page">
      <Page :total="total" @on-change="changePageNum" @on-page-size-change="changePageSize" :current="pageNum" show-total show-sizer show-elevator :page-size="pageSizeChild" transfer />
    </div>

  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import Table from '../table/table.vue'

export default {
  name: 'ghTable',
  props: {
    url: {
      type: String,
      required: true,
      default: '',
    },
    height: {
      type: Number,
      default: 0,
    },
    pageSize: {
      type: Number,
      default: 20,
    },
    searchParams: {
      type: Object,
    },
    data: {
      type: Array,
    },
    isStart: {
      type: Boolean,
      default: true,
    },
    isPage: {
      type: Boolean,
      default: true,
    },
    isFormData: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      pageNum: 1,
      pageSizeChild: 10,
      total: 0,
      tableData: [],
      loading: false,
    }
  },
  created() {
    this.tableData = this.data
    this.total = this.data.length
    this.pageSizeChild = this.pageSize
  },
  mounted() {
    if (this.isStart) {
      this.getTable()
    }
  },
  computed: {
    tableClass() {
      let height = this.height ? `${this.height}px` : '100%'
      return `height:${height}`
    },
  },
  watch: {
    pageSize(newVal) {
      this.pageSizeChild = newVal
    },
  },
  methods: {
    rowClassName(row, index) {
      if (index % 2 == 0) {
        return 'ivu-table-stripe-even'
      } else return 'ivu-table-stripe-odd'
    },
    changePageNum(pageNum) {
      this.pageNum = pageNum
      this.getTable()
    },
    changePageSize(pageSize) {
      this.pageSizeChild = pageSize
      this.getTable()
    },
    getTable() {
      if (!this.$axios) {
        console.error('pls setting vue.prototype.$axios')
        this.loading = false
      } else {
        let { pageNum, pageSizeChild } = this
        let pageSize = pageSizeChild
        let page = this.isPage
          ? {
              pageNum,
              pageSize,
            }
          : {}
        this.loading = true
        this.$axios({
          url: this.url,
          method: 'post',
          isFormData: this.isFormData,
          data: Object.assign({}, this.searchParams, page),
        }).then((res) => {
          this.loading = false
          this.total = res.result.total
          this.tableData = res.result.list
          this.$emit('load', this.tableData)
        })
      }
    },
    reloadTable() {
      this.pageNum = 1
      this.pageSizeChild = this.pageSize ? this.pageSize : this.pageSizeChild
      this.pageTotal = 0
      debounce(this.getTable, 100)()
    },
  },
}
</script>
