<template>
  <div class="ems-components-new page-table">
    <div
      class="run-search-bar"
      style="background:none;"
      v-if="showRunSearchBar"
    >
      <div class="search-bar">
        <slot name="search-bar"></slot>
      </div>
      <div class="handle-bar">
        <slot name="handle-bar"></slot>
      </div>
    </div>
    <div class="single-table-con">
      <div class="table-bar">
        <slot name="table-bar"></slot>
      </div>
      <Table
        ref="table"
        :loading="loading"
        :highlight-row="highlightRow"
        :data="tableData"
        :columns="tableColumns"
        size="small"
        stripe
        :max-height="maxHeight"
        @on-current-change="onCurrentChange"
        @on-selection-change="selectionChange"
        @on-sort-change="sortHandle"
        @on-row-click="rowClickHandle"
      ></Table>
      <div
        v-if="isPage"
        style="margin: 10px;overflow: hidden"
      >
        <div style="float: right;">
          <Page
            :placement="placement"
            :total="total"
            :show-total="showTotal"
            :page-size-opts="pageSizeOpts"
            :show-sizer="showSizer"
            :page-size="param.commonPageDTO.pageSize"
            :current="param.commonPageDTO.currentPage"
            :max-height="maxHeight"
            transfer
            @on-change="changePage"
            @on-page-size-change="changePageSize"
          ></Page>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="less" scoped>

</style>
<script>
import axios from '../axios.js';
export default {
  name: 'PageTable',
  components: {},
  directives: {},
  props: {
    customDataProcess: Function,
    customMapData: {
      type: null,
      default() {
        return undefined;
      }
    },
    resource: {
      type: Array,
      default() {
        return [];
      }
    },
    highlightRow: {
      type: Boolean,
      default() {
        return false;
      }
    },
    action: {
      type: String,
      default() {
        return '';
      }
    },
    'response-key': {
      type: String,
      default() {
        return 'dataResult';
      }
    },
    columns: {
      type: Array,
      default() {
        return [];
      }
    },
    columnsFn: {
      type: Function
    },
    initParam: {
      type: Object,
      default() {
        return {};
      }
    },
    autoFirst: {
      type: Boolean,
      default() {
        return true;
      }
    },
    pageSize: {
      type: Number,
      default() {
        return 10;
      }
    },
    showTotal: {
      type: Boolean,
      default() {
        return true;
      }
    },
    showSizer: {
      type: Boolean,
      default() {
        return true;
      }
    },
    pageSizeOpts: {
      type: Array,
      default() {
        return [10, 20, 50, 100];
      }
    },
    isPage: {
      type: Boolean,
      default() {
        return true;
      }
    },
    onSelectionChange: {
      type: Function
    },
    rowClickHandle: {
      type: Function,
      default: () => {}
    },
    showRunSearchBar: {
      type: Boolean,
      default: true
    },
    maxHeight: {
      type: String,
      default() {
        return '';
      }
    },
  },
  data() {
    return {
      tableData: [],
      tableColumns: [],
      total: 0,
      currentPage: 1,
      selection: [],
      loading: false,
      param: {
        commonPageDTO: {
          currentPage: 1,
          pageSize: this.pageSize
        },
        sortDTO: {
          fieldName: '',
          orderBy: ''
        }
      },
      messageJob: undefined,
      isSelectionChange: false,
      currentRow: undefined
    };
  },
  computed: {
    placement() {
      let pageTotal = 0;
      if (this.total % this.pageSize == 0) {
        pageTotal = this.total / this.pageSize;
      } else {
        pageTotal = this.total / this.pageSize + 1;
      }
      pageTotal = parseInt(pageTotal);
      return this.total % this.pageSize < 3 && this.currentPage == pageTotal
        ? 'bottom'
        : 'top';
    },
    lang() {
      return {};
    }
  },
  watch: {
    lang() {
      this.getColumns();
    },
    resource(newVal, oldVal) {
      this.resource = newVal;
    }
  },
  created: function() {
    if (!!this.action && this.autoFirst) {
      this.load(this.initParam);
    } else {
      this.loadLocal();
    }
    for (const c of this.columns) {
      if (!~'selection'.indexOf(c.type)) {
        c.ellipsis = true;
      }
    }
    this.getColumns();
  },
  beforeMount: function() {},
  mounted: function() {},
  beforeDestroy: function() {},
  destroyed: function() {},
  methods: {
    onCurrentChange(currentRow, oldCurrentRow) {
      this.currentRow = Object.assign({}, currentRow);
    },
    getHighlightRow() {
      return this.currentRow;
    },
    getColumns() {
      if (typeof this.columnsFn == 'function') {
        this.tableColumns = [].concat(this.columnsFn());
      } else {
        this.tableColumns = [].concat(this.columns);
      }
    },
    refresh() {
      this.param.commonPageDTO.currentPage = 1;
      this.$nextTick(() => {
        this.load(this.param);
      });
    },
    load(param = {}, page) {
      this.selection = [];
      this.param = {
        commonPageDTO: this.param.commonPageDTO,
        sortDTO: this.param.sortDTO,
        ...param
      };
      this.loading = true;
      if (!!page && typeof page == 'number') {
        this.param.commonPageDTO.currentPage = page;
      }
      this.param.commonPageDTO.recordCount = this.total;
      this.action ? this.loadAjax() : this.loadLocal();
    },
    loadLocal() {
      if (!this.isPage) {
        this.$nextTick(() => {
          this.tableData = [].concat(this.resource);
          this.loading = false;
        });
        return;
      }
      this.total = this.resource.length;
      const start =
          (this.param.commonPageDTO.currentPage - 1) *
          this.param.commonPageDTO.pageSize;
      let end = start + this.param.commonPageDTO.pageSize;
      end = this.resource.length > end ? end : this.resource.length;
      this.tableData = [];
      for (let i = start; i < end; i++) {
        this.tableData.push(this.resource[i]);
      }
      this.$nextTick(() => {
        this.loading = false;
      });
    },
    loadAjax() {
      axios.post(this.action, this.param).then(response => {
        const res = response.data[this.responseKey];
        this.loading = false;
        if (!res) { return; }
        if (this.customDataProcess) {
          this.customDataProcess(this, res);
          return;
        }
        if (typeof this.customMapData === 'function') {
          res.recordList = res.recordList.map(this.customMapData);
        }
        this.currentPage = res.currentPage == 0 ? 1 : res.currentPage;
        this.param.commonPageDTO.currentPage = this.currentPage;
        this.total = res.recordCount;
        this.tableData = [];
        const _list = [];
        // console.log(res.recordList)
        for (const item of res.recordList) {
          this.tableData.push(item);
          _list.push(item.userName);
        }
      });
    },
    changePage(page) {
      this.param.commonPageDTO.currentPage = page;
      this.load(this.param);
    },
    changePageSize(page) {
      this.param.commonPageDTO.pageSize = page;
      this.load(this.param);
    },
    selectionChange(selection) {
      this.isSelectionChange = true;
      this.selection = selection;
      if (typeof this.onSelectionChange == 'function') {
        this.onSelectionChange(selection);
      }
    },
    getSelectioned() {
      return this.isSelectionChange ? this.selection : undefined;
    },
    sortHandle(obj) {
      this.param.sortDTO.fieldName = obj.key;
      this.param.sortDTO.orderBy = obj.order;
      if (this.param.sortDTO.orderBy == 'normal') {
        this.param.sortDTO = {
          fieldName: '',
          orderBy: ''
        };
      }
      this.refresh();
    },
    getSortData() {
      return this.param.sortDTO;
    },
    getTableObj() {
      return this.$refs.table;
    }
  }
};
</script>
<style lang="less">
.ems-components-new.page-table {
  .run-search-bar {
    display: flex;
    padding: 10px 20px;
    min-height: 50px;

    .search-bar {
      flex: 1;
    }

    .handle-bar {
      margin-top: 5px;
      button {
        margin-left: 5px;
      }
    }
  }

  .single-table-con {
    .table-bar {
      margin-bottom: 5px;

      button {
        margin-right: 5px;
      }
    }
  }

  .run-mod-box {
    .ivu-tag-dot {
      height: 22px;
      line-height: 22px;
    }
  }
}

  .page-table {
    .table-bar {
      margin-bottom: 5px;
      >button:not(:last-child) {
        margin-right: 5px;
      }
    }
  }
</style>
