<template>
  <div class="ems-components-new base-page-table">
    <div
      class="run-search-bar"
      style="background:none;"
    >
      <div
        class="search-bar"
        :class="{'expand': expandMore}"
      >
        <slot name="search-bar"></slot>
        <slot name="search-handle-bar"></slot>
      </div>
      <div class="handle-bar">
        <slot name="handle-bar"></slot>
        <div
          v-if="isShowSearchMore"
          class="search-form-more"
          @click="expandMoreSearch"
        >
          <a href="javascript:;">{{ !expandMore ? "更多条件" : "隐藏条件" }}</a>
        </div>
      </div>
    </div>
    <div class="single-table-con">
      <Table
        ref="table"
        v-bind="$attrs"
        :loading="loading"
        :highlight-row="highlightRow"
        :data="tableData"
        :columns="tableColumns"
        size="small"
        stripe
        @on-current-change="onCurrentChange"
        @on-selection-change="selectionChange"
        @on-sort-change="sortHandle"
        @on-row-click="rowClickHandle"
      ></Table>
      <div style="margin: 10px; overflow: hidden">
        <div
          class="page-handle-bar"
          style="float: left"
        >
          <slot name="page-handle-bar"></slot>
        </div>
        <div
          v-if="isPage"
          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"
            size="small"
            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: {
      type: Function,
      default: null
    },
    customMapData: {
      type: null,
      default() {
        return undefined;
      }
    },
    resource: {
      type: Array,
      default() {
        return [];
      }
    },
    highlightRow: {
      type: Boolean,
      default() {
        return false;
      }
    },
    action: {
      type: String,
      default() {
        return '';
      }
    },
    responseKey: {
      type: String,
      default: 'dataResult'
    },
    columns: {
      type: Array,
      default() {
        return [];
      }
    },
    columnsFn: {
      type: Function,
      default: null
    },
    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,
      default: null
    },
    rowClickHandle: {
      type: Function,
      default: () => {}
    },
    border: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tableData: [],
      tableColumns: [],
      total: 0,
      currentPage: 1,
      selection: [],
      loading: false,
      expandMore: false,
      isShowSearchMore: 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() {
    this.showSearchMore();
  },
  beforeDestroy: function() {},
  destroyed: function() {},
  methods: {
    // 展开更多搜索选项
    expandMoreSearch() {
      this.expandMore = !this.expandMore;
    },
    showSearchMore() {
      if (this.$slots['search-bar']) {
        const h = this.$slots['search-bar'][0].elm.getBoundingClientRect().height;
        if (h > 55) {
          this.isShowSearchMore = true;
        }
      }
    },
    onCurrentChange(currentRow, oldCurrentRow) {
      this.currentRow = Object.assign({}, currentRow);
    },
    getHighlightRow() {
      return this.currentRow;
    },
    getColumns() {
      if (this.columnsFn && 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 => {
        if (response.data.statusCode !== '0') {
          this.$Message.error(response.data.msg || '网络错误！');
          return;
        }
        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 = [];
        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 (this.onSelectionChange && 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">
.base-page-table {
  .run-search-bar {
    padding: 10px 20px;
    min-height: 50px;
    .handle-bar {
      position: relative;
      margin-top: 5px;

      button {
        margin-right: 5px;
      }
    }
    .search-bar {
      height: 30px;
      margin-bottom: 10px;
      overflow: hidden;

      &.expand {
        height: auto !important;
      }
    }
  }
  .page-handle-bar {
    button {
      margin-right: 5px;
    }
  }
  .run-mod-box {
    .ivu-tag-dot {
      height: 22px;
      line-height: 22px;
    }
  }
  .search-form-more {
    color: #ffa329;
    position: absolute;
    right: 0;
    top: 2px;
    font-size: 13px;
  }
}

</style>
