
<template>
	<div class="table-component">
    <div v-if="showTableTitleFilter" class="table-title-filter">
      <label class="normal-text" style="margin-right: 10px">数据筛选：</label>
      <el-select
        style="width: 250px"
				size="small"
        v-model="openColumns"
        multiple
        placeholder="请选择要查看的数据"
        collapse-tags
        @change="handleOpenColumnsChange">
        <el-option
          v-for="item in tableTitles"
          :key="item.prop"
          :label="item.label"
          :value="item.prop">
        </el-option>
      </el-select>
    </div>

		<el-table
      ref="table"
			:data="dataSource"
      :border="border"
			:stripe="stripe"
      style="width: 100%"
      :row-style="rowStyle"
      @row-click="onRowClick"
      @sort-change="onSortChange"
      @select-all="onSelectAll"
      :empty-text="emptyText"
      :row-key="rowKey"
			:style="`height:${tableHeight}px;`"
		>

			<el-table-column
				:key="index" v-for="(item, index) in tableTitlesData"
				:label="item.label"
				:prop="item.prop"
				:width="item.width"
        :min-width="item.minWidth"
				:align="item.align"
				:type="item.type"
        :fixed="item.fixed"
        :sortable="item.sortable"
        :show-overflow-tooltip="item.tooltip"
        :reserve-selection="item.reserveSelection"
			>
        <template slot="empty">
          <span>-</span>
        </template>
				<slot v-if="item.template" slot-scope="scope" :name="item.prop" :row="scope.row" :index="scope.$index"></slot>
				<div v-else>{{scope.row[item.prop] || emptyDataText }}</div>
			</el-table-column>
		</el-table>

		<div class="pagination" v-if="pagination">
			<el-pagination
				background
				@size-change="handlePageSizeChange"
				@current-change="handlePageChange"
				:current-page.sync="ppage"
				:page-sizes="pageNumberlist"
				:page-size="pnumber"
				:layout="paginationLayout"
				:total="total">
			</el-pagination>
		</div>
	</div>
</template>

<script>
  import _ from 'loadsh';
	export default {
		name: "TableYjComponent",
		props: {
			height: {
				type: Number,
				default: document.body.clientHeight
			},

			tableData: {
				type: Array,
				default: function () {
					return []
				}
			},

      rowKey: {
	      type: String,
	      default: function () {
		      return undefined
	      }
      },

			defaultPageNumber: {
				type: Number,
				default: 10
			},

			border: {
				type: Boolean,
				default: false
      },

			stripe: {
				type: Boolean,
				default: true
      },

      pageNumberlist: {
	      type: Array,
	      default: function () {
          return [10, 50, 100]
	      }
      },

			tableTitles: {
				type: Array,
				default: function () {
					return []
				}
			},

			pagination: {
				type: Boolean,
				default: true
			},

			paginationLayout: {
				type: String,
				default: function () {
          return "total, prev, pager, next, sizes"
				}
      },

			autoLoad: {
				type: Boolean,
				default: true
			},

			remoteApi: {
				type: Function,
				default: null
			},

			showTableTitleFilter: {
				type: Boolean,
				default: false
      },

			rowStyle: {
				type: Function,
				default: undefined
      },

      emptyText: {
				type: String,
        default: function () {
          return '暂无数据'
        }
      },

      emptyDataText: {
	      type: String,
	      default: function () {
		      return ''
	      }
      },

      currentPageText: {
				type: String,
        default: function () {
          return 'pageSize'
        }
      },

			pageSizeText: {
				type: String,
				default: function () {
					return 'currentPage'
				}
			}
		},

		computed: {
			tableHeight() {
				let innerHeight = this.height-62;
				if(this.showTableTitleFilter){
					innerHeight = innerHeight- 42;
				}
				return innerHeight;
			},
		},

		data() {
			const ppage = 1;
			const pnumber = this.defaultPageNumber;
			let dataSource = !this.remoteApi && this.tableData ? [...this.tableData] : [];
			if (this.pagination && dataSource.length > 0) {
				dataSource = dataSource.slice(0, this.defaultPageNumber)
      }
			const total = !this.remoteApi && this.tableData ? this.tableData.length : 0;
			const tableTitlesData = this.tableTitles;
			const openColumns = this.tableTitles.map(item => item.prop);
			return {
				dataSource,
				total,
				ppage,
				pnumber,
				params: undefined,
				tableTitlesData,
				openColumns,
				pdirection: undefined,
				pcolumn: undefined
			}
		},

		watch: {
			tableData: {
				handler(newVal, oldVal) {
					let data = !this.remoteApi && newVal ? [...newVal] : [];
					if (this.pagination && newVal.length > 0) {
						data = newVal.slice((this.ppage - 1) * this.pnumber, this.ppage * this.pnumber)
            if (data.length === 0 && this.ppage - 1 > 0) {
	            data = newVal.slice((this.ppage - 2) * this.pnumber, (this.ppage - 1) * this.pnumber)
            }
					}
					this.dataSource = data;
					this.total = !this.remoteApi && newVal ? newVal.length : 0;
				},
        deep: true
			},

			tableTitles: {
				handler(newVal, oldVal) {
					this.tableTitlesData = newVal;
				}
			},

			dataSource: {
				handler(newVal) {
				    this.$emit('onDataChange', newVal)
				},
				deep: true
      }
		},

		mounted() {
			this.autoLoad && this.queryData();
		},


		methods: {
			queryData(queryParams) {
				this.getDataSourceFormServer(queryParams);
			},

      refreshData(queryParams) {
				this.ppage = 1;
				this.pnumber = this.defaultPageNumber;
	      this.getDataSourceFormServer(queryParams);
      },

			async getDataSourceFormServer(params) {
				if (!this.remoteApi) {
					return;
				}
				this.params = params
				const p = {
					[this.pageSizeText]: this.pagination? this.ppage : undefined,
					[this.currentPageText]: this.pagination? this.pnumber : undefined,
					pdirection: this.pdirection,
					pcolumn: this.pcolumn,
					...this.params
				}
				const data = await this.remoteApi(p)
				if (data) {
					this.dataSource = data.rows
					this.total = data.total
					this.autoLoad && this.$emit('onLoaded', data);
				}
			},

			handlePageChange(ppage) {
				this.ppage = ppage;
				if (this.remoteApi) {
					this.getDataSourceFormServer(this.params)
				} else {
					this.dataSource = this.tableData ? this.tableData.slice((ppage - 1) * this.pnumber, ppage * this.pnumber) : []
				}
			},

			handlePageSizeChange (pnumber) {
				this.ppage = 1;
				this.pnumber = pnumber;
				if (this.remoteApi) {
					this.getDataSourceFormServer(this.params)
				} else {
					this.dataSource = this.tableData ? this.tableData.slice(0, pnumber) : []
				}
			},

			handleOpenColumnsChange (selection) {
				this.tableTitlesData = _.intersectionBy(this.tableTitles, selection.map(item => {
					return {
						prop: item
          }
        }), 'prop');
      },

			getDataSource() {
				return this.dataSource;
			},

			getTotal() {
				return this.total;
			},

			getPageNumber() {
				return this.ppage
			},

			getPageSize() {
				return this.pnumber
			},

			onRowClick(row) {
				this.$emit('onRowClick', row);
      },

			onSelectAll(val) {
				this.$emit('onSelectAll', val);
      },

			clearSelection() {
				this.$refs.table.clearSelection()
      },

			toggleRowSelection(row, val) {
				this.$refs.table.toggleRowSelection(row, val)
      },

			onSortChange({ column, prop, order }) {
        this.pcolumn = order === null ? undefined : prop;
        this.pdirection =  order === null ? undefined : order === 'ascending';
				this.getDataSourceFormServer(this.params)
      },

      refreshSelection(selection = []) {
				this.clearSelection()
	      selection.forEach(row => {
		      if (row) {
			      this.toggleRowSelection(row, true);
		      }
	      });
      }
		}
	}
</script>

<style lang='scss' >
.table-component{
	padding: 10px 0px;

	.table-title-filter{
		display: flex;
		align-items: center; 
		padding-bottom: 10px;
	}

	.el-table__header thead tr th{
		background-color: #F8F8F8 !important;
		color: #000000;
	}

  .pagination {
		padding-top: 10px;
		text-align: right;
	}
}
	
</style>
