<template>
  <div>
    <div class="page-table-list" v-if="isSearch">
      <Row :gutter="8">
        <Col span="19">
          <div>
            <slot name="search-bar"></slot>
          </div>
        </Col>
        <Col span="5">
          <div class="page-table-lis">
            <div v-if="isShowToggle" class="page-table-list-isShow" @click="handleToggle">
              {{isShow ? '收起' : '展开'}}<i class="ivu-icon ivu-icon-ios-arrow-down page-table-list-isShow-icon" :style="{transform: isShow ? 'translateY(-50%) rotate(180deg)' : 'translateY(-50%)'}"></i>
            </div>
            <slot name="handle-bar"></slot>
          </div>
        </Col>
      </Row>
      <div class="div-box-10"></div>
      <div class="table-bar">
        <Row>
          <Col :span="tableBarNum">
            <div class="table-bar-left">
              <span class="placeholder"></span>
              <slot name="table-bar-left"></slot>
            </div>
          </Col>
          <Col :span="24 - tableBarNum">
            <slot name="table-bar"></slot>
          </Col>
        </Row>
      </div>
    </div>
    <div class="single-table-con full-screen" ref="pageTable">
<!--      <div v-if="isShowFull" class="full-screen-btn">
        <Tooltip v-if="isFull" content="全屏" placement="top">
          <a @click="handleFullScreen"><Icon type="md-expand" size="20"/></a>
        </Tooltip>
        <Tooltip v-else content="退出全屏" placement="top">
          <a @click="handleExitFullscreen"><Icon type="md-contract" size="20"/></a>
        </Tooltip>
      </div>-->
      <Table ref="table" :loading="loading" :highlight-row="highlightRow" :data="tableData" :columns="tableColumns" :height="tableH"
             @on-current-change="onCurrentChange" @on-selection-change="selectionChange" @on-sort-change="sortHandle" @on-row-click="rowClickHandle"></Table>
      <div class="pageTable-page" style="margin-top: 16px;overflow: hidden" v-if="isPage">
        <div class="total-div" v-if="isPageLeft">
          {{ `显示第 ${currentPage > 1 ? (currentPage - 1) * param.commonPageDTO.pageSize : 1} 条到 ${currentPage * param.commonPageDTO.pageSize} 条记录，一共` }}
          <span>{{ total }}</span>
          条
        </div>
        <div style="float: right;">
          <Page :placement="placement" :total="total" :page-size-opts="pageSizeOpts" :show-sizer="showSizer" :page-size="param.commonPageDTO.pageSize" :current="param.commonPageDTO.currentPage"
                @on-change="changePage" @on-page-size-change="changePageSize" transfer="true"></Page>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import FullScreen from './FullScreen'
export default {
  name: "PageTable",
  mixins: [FullScreen],
  components: {},
  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 "";
      }
    },
    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;
      }
    },
    isPageLeft: {
      type: Boolean,
      default() {
        return true
      }
    },
    onSelectionChange: {
      type: Function
    },
    rowClickHandle: {
      type: Function,
    },
    isSearch: {
      type:Boolean,
      default() {
        return true
      }
    },
    //是否开启表格高度，默认开启
    isTableHeight: {
      type: Boolean,
      default: true
    },
    //是否开启展开收起按钮
    isShowToggle: {
      type: Boolean,
      default: true
    },
    //展开收起的过渡时间
    transitionTime: {
      type: Number,
      default: 600
    },
    //table-bar 左边的宽度 右边根据左边计算出来
    tableBarNum: {
      type: Number,
      default: 18
    }
  },
  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,
      isShow: false,
      tableH: 200,  //表格高度
      timer: null,  //定时器
      bodyH: 0, //页面可见高度
      isShowFull: true,  //浏览器是否支持全屏显示
      isFull: true,  //是否可以开启全屏   true：可以
    };
  },
  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 $store.state.lang;
    }
  },
  created: function() {
    if (!!this.action && this.autoFirst) {
      this.load(this.initParam);
    } else {
      this.loadLocal();
    }
    for (let c of this.columns) {
      if (!~"selection".indexOf(c.type)) {
        c.ellipsis = true;
      }
    }
    this.getColumns();
  },
  beforeMount: function() {},
  mounted(){
    if (this.isTableHeight) {
      let bodyH = document.body.offsetHeight;
      this.timer = setInterval(() => {
        //页面高度变化才需要重新计算
        if (bodyH !== this.bodyH) {
          this.bodyH = bodyH;
          this.getTableHeight();
        }
      },300);
    }
  },
  beforeDestroy: function() {},
  destroyed() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  },
  methods: {
    handleToggle() {
      this.isShow = !this.isShow;
      //用于第二行之后的隐藏显示
      this.$emit('handleHideRow',this.isShow);
      if (this.isShow) {
        this.$nextTick(() => {
          this.getTableHeight();
        })
      }else {
        //收起的时候有过渡效果，需要时间,默认600
        setTimeout(() => {
          this.getTableHeight();
        },this.transitionTime)
      }
    },
    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 = [];
      // for (let p in param) {
      //   this.param[p] = param[p];
      // }
      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;
      let 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() {
      $store.dispatch(this.action, this.param).then(res => {
        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 = [];
        let _list = [];
        // console.log(res.recordList)
        for (let item of res.recordList) {
          this.tableData.push(item);
          _list.push(item.userName);
        }
        this.$emit('tableResponse',res)
      });
    },
    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;
      return {}
    },
    getTableObj(){
      return this.$refs["table"];
    },
    getTableHeight() {
      //页面可见高度
      let bodyH = this.bodyH;
      //顶部高度
      let topH = document.getElementsByClassName('main-div-box')[0].scrollHeight;
      //搜索条件加按钮的高度
      let searchH = document.getElementsByClassName('page-table-list') && document.getElementsByClassName('page-table-list')[0] ? document.getElementsByClassName('page-table-list')[0].scrollHeight : 0;
      //页数高度
      let pageH = document.getElementsByClassName('pageTable-page') && document.getElementsByClassName('pageTable-page')[0] ? document.getElementsByClassName('pageTable-page')[0].scrollHeight : 0;
      //版权高度
      let copyrightH = document.getElementsByClassName('copyright')[0].scrollHeight;
      //表头高度
      let tableHeader = document.getElementsByClassName('ivu-table-header')[0].scrollHeight;
      //padding宽度
      let pdH = -5;
      this.tableH = bodyH - topH - searchH - pageH - copyrightH - tableHeader - pdH;
    },
    //全屏
    handleFullScreen() {
      this.Fullscreen(this.$refs.pageTable);
    },
    //退出全屏
    handleExitFullscreen() {
      this.exitFullscreen();
    },
    //进入全屏
    enterFull() {
      //页数高度
      let pageH = document.getElementsByClassName('pageTable-page') && document.getElementsByClassName('pageTable-page')[0] ?
        document.getElementsByClassName('pageTable-page')[0].scrollHeight : 0;
      //设置表格高度
      this.tableH = this.$refs.pageTable.offsetHeight - 48 - pageH;
    },
    //退出全屏
    quitFull() {
      this.getTableHeight();
    }
  },
  watch: {
    lang() {
      this.getColumns();
    },
    resource(newVal, oldVal) {
      this.resource = newVal;
    }
  },
  directives: {}
};
</script>
<style lang="less" scoped>
.total-div {
  float: left;
  line-height: 32px;
  font-size: 14px;
  span {
    color: #F99C34;
  }
}
.div-box-10 {
  width: 100%;
  height: 8px;
  background: #F7F8FC;
}
.full-screen {
  position: relative;
  .full-screen-btn {
    position: absolute;
    top: 16px;
    right: 16px;
    z-index: 1;
  }
}
</style>