<template>
	<el-container>
		<div v-if="(hasSearchSlot || hasExtendSearchSlot) && show" class="extend">
			<el-collapse-transition>
				<div class="extend-panel">
					<slot name="extend"></slot>
				</div>
			</el-collapse-transition>
		</div>
		<el-header v-if="hasSearchSlot || hasExtendSearchSlot || hasDoSlot">
			<div class="left-panel">
				<slot name="do"></slot>
			</div>
			<div class="right-panel">
				<slot name="search"></slot>
				<el-button v-if="hasExtendSearchSlot" type="primary" icon="el-icon-filter" @click="show = !show"
						   :plain="show"/>
			</div>
		</el-header>
		<el-main class="nopadding">
			<div :style="{'height':_height}" v-loading="loading">
				<div class="pi-table" :style="{'height':_table_height}">
					<el-table v-bind="$attrs" :data="tableData" :row-key="rowKey" :key="toggleIndex" ref="piTableRef"
							  :height="height=='auto'?null:'100%'" :size="_config.size" :border="_config.border"
							  :stripe="_config.stripe" :summary-method="remoteSummary?remoteSummaryMethod:summaryMethod"
							  @sort-change="sortChange" @filter-change="filterChange">
						<slot></slot>
						<template v-for="(item, index) in userColumn" :key="index">
							<el-table-column v-if="!item.hide" :column-key="item.prop" :label="item.label"
											 :prop="item.prop" :width="item.width" :sortable="item.sortable"
											 :fixed="item.fixed" :filters="item.filters"
											 :filter-method="remoteFilter||!item.filters?null:filterHandler"
											 :show-overflow-tooltip="item.showOverflowTooltip">
								<template #default="scope">
									<slot :name="item.prop" v-bind="scope">
										{{ scope.row[item.prop] }}
									</slot>
								</template>
							</el-table-column>
						</template>
						<el-table-column min-width="1"></el-table-column>
						<template #empty>
							<el-empty :description="emptyText" :image-size="100"></el-empty>
						</template>
					</el-table>
				</div>
				<div class="pi-table-page" v-if="!hidePagination || !hideDo">
					<div class="pi-table-pagination">
						<el-pagination v-if="!hidePagination" background size="small" :layout="paginationLayout"
									   :total="total" :page-size="piPageSize" :page-sizes="pageSizes"
									   v-model:currentPage="currentPage" @current-change="paginationChange"
									   @update:page-size="pageSizeChange"></el-pagination>
					</div>
					<div class="pi-table-do" v-if="!hideDo">
						<el-button v-if="!hideRefresh" @click="refresh" icon="el-icon-refresh" circle
								   style="margin-left:15px"></el-button>
						<el-popover v-if="column" placement="top" title="列设置" :width="500" trigger="click"
									:hide-after="0" @show="customColumnShow=true" @after-leave="customColumnShow=false">
							<template #reference>
								<el-button icon="el-icon-set-up" circle style="margin-left:15px"></el-button>
							</template>
							<columnSetting v-if="customColumnShow" ref="columnSettingRef"
										   @userChange="columnSettingChange"
										   @save="columnSettingSave" @back="columnSettingBack"
										   :column="userColumn"></columnSetting>
						</el-popover>
						<el-popover v-if="!hideSetting" placement="top" title="表格设置" :width="400" trigger="click"
									:hide-after="0">
							<template #reference>
								<el-button icon="el-icon-setting" circle style="margin-left:15px"></el-button>
							</template>
							<el-form label-width="80px" label-position="left">
								<el-form-item label="表格尺寸">
									<el-radio-group v-model="_config.size" size="small" @change="configSizeChange">
										<el-radio-button value="large">大</el-radio-button>
										<el-radio-button value="default">正常</el-radio-button>
										<el-radio-button value="small">小</el-radio-button>
									</el-radio-group>
								</el-form-item>
								<el-form-item label="样式">
									<el-checkbox v-model="_config.border" label="纵向边框"></el-checkbox>
									<el-checkbox v-model="_config.stripe" label="斑马纹"></el-checkbox>
								</el-form-item>
							</el-form>
						</el-popover>
					</div>
				</div>
			</div>
		</el-main>
	</el-container>
</template>

<script setup>
import columnSetting from './columnSetting'
import config from "@/config/table"
import {ref, watch, computed, onMounted, onActivated, onDeactivated, getCurrentInstance, useSlots, nextTick} from "vue"
import tools from "@/utils/tools";
import sortablejs from 'sortablejs'

defineOptions({
	name: 'piTable'
})

defineExpose({
	refresh,
	upData,
	reload
})

const {proxy} = getCurrentInstance()
const emit = defineEmits(['dataChange', 'onEnd'])

const slots = useSlots()
const hasSearchSlot = computed(() => !!slots.search)
const hasExtendSearchSlot = computed(() => !!slots.extend)
const hasDoSlot = computed(() => !!slots.do)

const props = defineProps({
	tableName: {type: String, default: ""},
	apiObj: {
		type: Function, default: () => {
		}
	},
	workbench: {type: Boolean, default: false},
	params: {type: Object, default: () => ({})},
	data: {
		type: Object, default: () => {
		}
	},
	height: {type: [String, Number], default: "100%"},
	size: {type: String, default: "default"},
	border: {type: Boolean, default: false},
	stripe: {type: Boolean, default: false},
	pageSize: {type: Number, default: config.pageSize},
	pageSizes: {type: Array, default: config.pageSizes},
	rowKey: {type: String, default: ""},
	summaryMethod: {type: Function, default: null},
	column: {
		type: Object, default: () => {
		}
	},
	remoteSort: {type: Boolean, default: false},
	remoteFilter: {type: Boolean, default: false},
	remoteSummary: {type: Boolean, default: false},
	hidePagination: {type: Boolean, default: false},
	hideDo: {type: Boolean, default: false},
	hideRefresh: {type: Boolean, default: false},
	hideSetting: {type: Boolean, default: false},
	paginationLayout: {type: String, default: config.paginationLayout},
	sortable: {type: Boolean, default: false}
})

const piTableRef = ref(null)
const columnSettingRef = ref(null)

let piPageSize = ref(props.pageSize)
let isActive = ref(true)
let emptyText = ref("暂无数据")
let toggleIndex = ref(0)
let tableData = ref([])
let total = ref(0)
let currentPage = ref(1)
let prop = ref(null)
let order = ref(null)
let loading = ref(false)
let tableParams = ref(props.params)
let userColumn = ref([])
let customColumnShow = ref(false)
let summary = ref({})
let _config = ref({
	size: props.size,
	border: props.border,
	stripe: props.stripe
})
let show = ref(false)

watch(() => props.data, () => {
	tableData.value = props.data;
	total.value = tableData.value.length;
})

watch(() => props.apiObj, () => {
	tableParams.value = props.params;
	refresh();
})

const _height = computed(() => {
	return Number(props.height) ? Number(props.height) + 'px' : props.height
})

const _table_height = computed(() => {
	return props.hidePagination && props.hideDo ? "100%" : "calc(100% - 50px)"
})

onMounted(() => {
	//判断是否开启自定义列
	if (props.column) {
		getCustomColumn()
	} else {
		userColumn = props.column
	}
	//判断是否静态数据
	if (props.apiObj) {
		getData()
	} else if (data.value) {
		tableData.value = data.value
		total.value = tableData.value.length
	}
	// 拖拽排序
	if (props.sortable) {
		initSortable()
	}
})

onActivated(() => {
	if (!isActive.value) {
		piTableRef.value.doLayout()
	}
})

onDeactivated(() => {
	isActive.value = false
})

async function initSortable() {
	await nextTick()
	const tbody = document.querySelector('.el-table__body-wrapper tbody');
	sortablejs.create(tbody, {
		animation: 150, // 拖拽动画时长，使过渡更自然
		ghostClass: 'sortable-ghost', // 拖拽时占位元素的样式类
		onEnd: ({newIndex, oldIndex}) => { // 拖拽结束事件
			if (newIndex === oldIndex) return;
			emit('onEnd', newIndex, oldIndex)
		}
	});
}

async function getCustomColumn() {
	userColumn.value = await config.columnSettingGet(props.tableName, props.column)
}

async function getData() {
	loading.value = true;
	var reqData = {
		[config.request.page]: currentPage.value,
		[config.request.pageSize]: piPageSize.value,
		[config.request.prop]: prop.value,
		[config.request.order]: order.value
	}
	if (props.hidePagination) {
		delete reqData[config.request.page]
		delete reqData[config.request.pageSize]
	}
	Object.assign(reqData, tableParams.value)
	try {
		var res = await props.apiObj(reqData)
	} catch (error) {
		loading.value = false;
		emptyText.value = error.statusText;
		return false;
	}
	try {
		var response = config.parseData(res);
	} catch (error) {
		loading.value = false;
		emptyText.value = "数据格式错误";
		return false;
	}
	if (response.code !== config.successCode) {
		loading.value = false;
		emptyText.value = response.msg;
	} else {
		emptyText.value = "暂无数据";
		if (props.hidePagination) {
			tableData.value = response.data || [];
		} else {
			tableData.value = response.rows || [];
		}
		if (props.rowKey) {
			tableData.value = tools.makeTreeData(tableData.value, 0, props.rowKey)
		}
		total.value = response.total || 0;
		summary.value = response.summary || {};
		loading.value = false;
	}
	piTableRef.value.setScrollTop(0)
	emit('dataChange', res, tableData.value)
}

//分页点击
function paginationChange() {
	getData();
}

//条数变化
function pageSizeChange(size) {
	piPageSize.value = size
	getData()
}

//刷新数据
function refresh() {
	piTableRef.value.clearSelection()
	getData()
}

//更新数据 合并上一次params
function upData(params, page = 1) {
	currentPage.value = page;
	piTableRef.value.clearSelection();
	Object.assign(tableParams.value, params || {})
	getData()
}

//重载数据 替换params
function reload(params, page = 1) {
	currentPage.value = page;
	tableParams.value = params || {}
	piTableRef.value.clearSelection();
	piTableRef.value.clearSort()
	piTableRef.value.clearFilter()
	getData()
}

//自定义变化事件
function columnSettingChange(column) {
	userColumn.value = column;
	toggleIndex.value += 1;
}

//自定义列保存
async function columnSettingSave(column) {
	columnSettingRef.value.isSave = true
	try {
		await config.columnSettingSave(props.tableName, column)
	} catch (error) {
		proxy.$message.error('保存失败')
		columnSettingRef.value.isSave = false
	}
	proxy.$message.success('保存成功')
	columnSettingRef.value.isSave = false
}

//自定义列重置
async function columnSettingBack() {
	columnSettingRef.value.isSave = true
	try {
		const column = await config.columnSettingReset(props.tableName, props.column)
		userColumn.value = column
		columnSettingRef.value.usercolumn = tools.objCopy(userColumn.value)
	} catch (error) {
		proxy.$message.error('重置失败')
		columnSettingRef.value.isSave = false
	}
	columnSettingRef.value.isSave = false
}

//排序事件
function sortChange(obj) {
	if (!proxy.remoteSort) {
		return false
	}
	if (obj.column && obj.prop) {
		prop.value = obj.prop
		order.value = obj.order
	} else {
		prop.value = null
		order.value = null
	}
	getData()
}

//本地过滤
function filterHandler(value, row, column) {
	const property = column.property;
	return row[property] === value;
}

//过滤事件
function filterChange(filters) {
	if (!props.remoteFilter) {
		return false
	}
	Object.keys(filters).forEach(key => {
		filters[key] = filters[key].join(',')
	})
	upData(filters)
}

//远程合计行处理
function remoteSummaryMethod(param) {
	const {columns} = param
	const sums = []
	columns.forEach((column, index) => {
		if (index === 0) {
			sums[index] = '合计'
			return
		}
		const values = summary.value[column.property]
		if (values) {
			sums[index] = values
		} else {
			sums[index] = ''
		}
	})
	return sums
}

function configSizeChange() {
	piTableRef.value.doLayout()
}

//插入行 unshiftRow
function unshiftRow(row) {
	tableData.value.unshift(row)
}

//插入行 pushRow
function pushRow(row) {
	tableData.value.push(row)
}

//根据key覆盖数据
function updateKey(row, rowKey = props.rowKey) {
	tableData.value.filter(item => item[rowKey] === row[rowKey]).forEach(item => {
		Object.assign(item, row)
	})
}

//根据index覆盖数据
function updateIndex(row, index) {
	Object.assign(tableData.value[index], row)
}

//根据index删除
function removeIndex(index) {
	tableData.value.splice(index, 1)
}

//根据index批量删除
function removeIndexes(indexes = []) {
	indexes.forEach(index => {
		tableData.value.splice(index, 1)
	})
}

//根据key删除
function removeKey(key, rowKey = props.rowKey) {
	tableData.value.splice(tableData.value.findIndex(item => item[rowKey] === key), 1)
}

//根据keys批量删除
function removeKeys(keys = [], rowKey = props.rowKey) {
	keys.forEach(key => {
		tableData.value.splice(tableData.value.findIndex(item => item[rowKey] === key), 1)
	})
}

//原生方法转发
function clearSelection() {
	piTableRef.value.clearSelection()
}

function toggleRowSelection(row, selected) {
	piTableRef.value.toggleRowSelection(row, selected)
}


function toggleAllSelection() {
	piTableRef.value.toggleAllSelection()
}

function toggleRowExpansion(row, expanded) {
	piTableRef.value.toggleRowExpansion(row, expanded)
}

function setCurrentRow(row) {
	piTableRef.value.setCurrentRow(row)
}

function clearSort() {
	piTableRef.value.clearSort()
}

function clearFilter(columnKey) {
	piTableRef.value.clearFilter(columnKey)
}

function doLayout() {
	piTableRef.value.doLayout()
}

function sort(prop, order) {
	piTableRef.value.sort(prop, order)
}
</script>

<style lang="scss" scoped>
.pi-table {
	height: calc(100% - 50px);
}

.pi-table-page {
	height: 50px;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 15px;
}

.pi-table-do {
	white-space: nowrap;
}

.pi-table:deep(.el-table__footer) .cell {
	font-weight: bold;
}

.pi-table:deep(.el-table__body-wrapper) .el-scrollbar__bar.is-horizontal {
	height: 12px;
	border-radius: 12px;
}

.pi-table:deep(.el-table__body-wrapper) .el-scrollbar__bar.is-vertical {
	width: 12px;
	border-radius: 12px;
}

.pi-extend {
	background: var(--el-bg-color-overlay);
	border-color: var(--el-border-color-light);
	display: flex;
	flex-wrap: wrap;
	max-width: 100%;
}

::v-deep(.el-header) {
	height: auto !important;
}

.extend {
	background: var(--el-bg-color-overlay);
	border-color: var(--el-border-color-light);
	padding: 15px 15px 0 15px;
}

.extend-panel {
	display: inline-flex;
	flex-wrap: wrap;
	flex-direction: column;
}

.right-panel > * + *, .left-panel > * + *, .extend-panel > * + * {
	margin-left: 10px;
}
</style>
