<template>
  <div class="m-table-list">

    <slot name="operation"></slot>
    <div>
      <div class="m-table-list-selection" v-if="multipleSelect">
        <span class="desc">已选中{{isSelectAll? listConfig.total: count}}条/共{{listConfig.total}}条</span>
        <c-button type="text" @click="handleSelectAll">{{isSelectAll?'取消全选': '全选'}}</c-button>
      </div>
      <c-table
        v-bind="listConfig"
        :loading="loading"
        ref="tablelist"
        :default-sort="listConfig.sort ? {prop: listConfig.sort, order: listConfig.order}: {}"
        @selection-change="handleSelectionChange"
        @current-change="handleCurrentChange"
        @sort-change="handleSortChange"
		    v-on="$listeners"
        :tableRowClassName="tableRowClass"
        :maxHeight="maxHeight"
        :outerHeight="outerHeight"
        :row-key="getRowKey"
      >
        <slot></slot>
      </c-table>
    </div>
  </div>
</template>

<script>
import Request from '~/utils/request'

export default {
  props: {
    columnsConfig: { // 列配置项
      type: Array,
      default: []
    },
    params: { // 搜索查询参数
      type: Object,
      default: ()=>{}
    },
    pageSize: { // 每页限制展示数目
      type: Number,
      default: 20
    },
    url: { // 拉取列表接口名称
      type: String
    },
    method: { // 拉取列表接口方法，默认 post
      type: String,
      default: 'post'
    },
    defaultSort: { // 默认首次加载排序字段名称
      type: String,
      default: ""
    },
    defaultOrder: { // 默认首次加载排序顺序
      type: String,
      default: "ascending"
    },
    multipleSelect: { // 是否要展示多项选择框
      type: Boolean,
      default: false
    },
    loadDataFirstRender: {
      type: Boolean,
      default: true
    },
    tableRowClassName: {
      type: Function
    },
	  watchCurrentChg:{
	    type: Boolean,
	    default: true
    },
    maxHeight:{
      type:String,
      default:undefined
    },
    outerHeight: {
      type: Number,
      default: undefined
    },

	},
  data(){
    return{
      listConfig: {
        list: [],
        total: 0,
        current: 1,
        limit: this.pageSize,
        columnsConfig: this.columnsConfig,
        sort: this.defaultSort,
        order: this.defaultOrder,
      },
      count: 0,
      isSelectAll: false,
      selection: [],
      loading: false,
      isMounted: false
    }
  },
  computed: {
    'searchParams': function () {
      console.log('computed searchParams')
	  let params = {}
	  if(this.watchCurrentChg){
		params = {
          current: this.listConfig.current,
          size: this.pageSize,
          data: this.params
        }
	  }else{
	    params = {
          size: this.pageSize,
          data: this.params
        }
	  }
      if (this.listConfig.sort && this.listConfig.order) {
        params.orders = [
          {
            column: this.listConfig.sort,
            asc: this.listConfig.order == 'ascending'
          }
        ]
      }
      return params
    }
  },
  watch: {
    'params': function () {
      // 更改搜索条件需要重置为 0
      this.listConfig.current = 1
    },
    'searchParams': function () {
      if (this.isMounted) {
        this.getList()
      }
    }
  },
  created() {
    if (this.multipleSelect &&
      this.listConfig.columnsConfig &&
      this.listConfig.columnsConfig[0].type !== 'selection') {
      this.listConfig.columnsConfig.unshift({
        type: "selection",
        width: "55",
        fixed: "left"
      })
    }
    
  },
  mounted () {
    if (this.loadDataFirstRender) {
      this.getList()
    }
    this.isMounted = true
  },
  methods: {
    handleSelectionChange: function (selection) {
      this.count = selection.length
      this.selection = selection
      this.isSelectAll = false
      this.$emit('selection-change', selection)
    },
    handleCurrentChange: function (current) {
      this.listConfig.current = current
      this.$emit('current-change',current)
    },
    handleSortChange: function ({column, prop, order}) {
      this.listConfig.sort = column.columnKey || prop
      if (order == 'ascending') {
        this.listConfig.order = 'ascending'
      } else {
        this.listConfig.order = 'descending'
      }
      this.listConfig.current = 1
    },
    getList() {
      if (this.url && this.method == 'post') {
        let self = this
        self.loading = true
        Request.post(this.url, this.searchParams).then(res => {
          if (res.code === SUCCESS) {
			  
            self.listConfig.list = res.data || []
            self.listConfig.total = res.pageInfo && res.pageInfo.total || 0
            self.$emit('update-list', self.listConfig.list, self.listConfig.total, res)
          } else {
            self.listConfig.list = []
            self.listConfig.total = 0
          }
          self.loading = false
        }).catch(err=> {
          self.loading = false
        })
      }
    },
    handleSelectAll: function() {
      let currentSelectAll = !this.isSelectAll
      if (currentSelectAll) {
        // 全选
        this.$refs["tablelist"].$refs["table"].clearSelection()
        this.listConfig.list.forEach(row => {
          this.$refs["tablelist"].$refs["table"].toggleRowSelection(row)
        })
        this.selection = []
        this.count = this.listConfig.total
        this.$emit('selection-change', this.selection, currentSelectAll)
      } else {
        // 取消全选
        this.$refs["tablelist"].$refs["table"].clearSelection()
        this.selection = []
        this.count = 0
        this.$emit('selection-change', this.selection, currentSelectAll)
      }
      this.isSelectAll = currentSelectAll
    },
    tableRowClass: function ({row, rowIndex}) {
      if (this.tableRowClassName) {
        return this.tableRowClassName({row, rowIndex})
      } else {
        return ''
      }
    },
    getRowKey(row){
      let key = null
      this.$emit('getRowKey',row,val => {key = val})
      return key
    }
  },
}
</script>

<style>
.eContainer-table-block .paginationLable{
  font-size: 12px;
  color: #808080;
  height: 26px;
  line-height: 26px;
  float:right;
  /* margin-top:20px; */
}
.eContainer-table-block .el-table__body-wrapper {
  overflow: auto;
}
.m-table-list {
  margin-top: 20px;
}
.m-table-list-operation {
  margin-bottom: 15px;
}
.m-table-list-selection .desc{
  font-size: 14px;
  color: #808080;
}
.m-table-search-operation-simple {
  position: absolute;
  right: 20px;
  top: 20px;
}
</style>