<!--
@name 回到顶部
@desc 通过滚动高度计算当前页码

【必填参数】：
    @param {Number} [pageindex] - 接口入参页码

-->
<template>
	<div class="back-to-top" ref="btn" @click="totop">
		<template v-if="timer">
			{{ currentIndex }}
		</template>
		<template v-else>
			<i class="iconfont icon-ToTop_light"></i>
		</template>
	</div>
</template>

<script>
export default {
	name: "lj-scrollToTop",
	data() {
		return {
			timer: null,
			heightArr: [],
			lastHeight: 0,
			currentIndex: 1
		}
	},
	props: {
		pageindex: {
			type: Number,
			default: 1
		}
	},
	mounted() {
		this.body = window.document.querySelector("body");
		this.scroll();
	},
	methods: {
		totop() {
			window.scrollTo({
				top: 0,
				behavior: "auto", // smooth：缓慢
			});
		},
		scroll() {
			this.body.onscroll = () => {
				let scrollTop =
					this.body.scrollTop ||
					document.documentElement.scrollTop ||
					window.pageYOffset ||
					document.body.scrollTop;
				let innerHeight = window.innerHeight - 500;
				let opacityNum = 1 - (innerHeight - scrollTop) / innerHeight;
				let resNum = opacityNum > 1 ? 1 : opacityNum;

				this.$refs["btn"].style.opacity = scrollTop <= 0 ? 0 : resNum;
				// this.$refs["btn"].style.display = scrollTop > innerHeight ? "block" : "none";
				clearTimeout(this.timer);
				this.timer = setTimeout(this.fnFinishScroll, 500);
				this.lastHeight = scrollTop;
				this.fnGetCurrentIndex(scrollTop);
			};
		},
		/**判断是否滚动结束 */
		fnFinishScroll() {
			let scrollTop =
				this.body.scrollTop ||
				document.documentElement.scrollTop ||
				window.pageYOffset ||
				document.body.scrollTop;
			if(this.lastHeight == scrollTop){
				this.timer = null;
			}
		},
		fnGetCurrentIndex(height) {
			for (let i = 0; i < this.heightArr.length; i++) {
				if (height < this.heightArr[i]) {
					this.currentIndex = i + 1;
					break;
				}
			}
		},
		resetData() {
			this.heightArr = [];
			this.currentIndex = 1;
			this.lastHeight = 0;
			this.timer = null;
		}
	},
	watch: {
		pageindex(newVal) {
			if (newVal > 1) {
				this.$nextTick(() => {
					this.heightArr.push(this.body.clientHeight);
				});
			} else {
				this.resetData();
			}
		}
	},
	beforeDestroy () {
		window.removeEventListener("scroll", this.body);
	}
};
</script>

<style lang="less" scoped>
.back-to-top {
	position: fixed;
	right: 10px;
	bottom: 2rem;
	width: 36px;
	height: 36px;
	opacity: 0;
	background-color: #fff;
	// display: none;
	z-index: 888;
	border-radius: 50%;
	box-shadow: 0px 2px 5px 0px rgba(0,0,0,0.06), 0px 0px 3px 0px rgba(0,0,0,0.1);
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 16px;
	color: @secondary;

	.iconfont {
		font-size: 24px;
	}
}
</style>
