<template>
	<view
		v-if="visible"
		class="d-top-message"
		:class="['d-top-message--' + type, { 'd-top-message--show': animated }]"
		:style="{ top: topOffset + 'px' }"
	>
		<u-icon v-if="type === 'success'" name="checkmark-circle-fill" color="#6ACDBB" size="28" class="d-top-message-icon"></u-icon>
		<text class="d-top-message-text">{{ text }}</text>
	</view>
</template>

<script>
export default {
	name: 'DTopMessage',
	data() {
		return {
			visible: false,
			animated: false,
			text: '',
			type: 'success',
			topOffset: 88,
			hideTimer: null,
		};
	},
	mounted() {
		this.calcTopOffset();
	},
	beforeDestroy() {
		this.clearTimer();
	},
	methods: {
		calcTopOffset() {
			try {
				const systemInfo = uni.getSystemInfoSync();
				const statusBar = systemInfo.statusBarHeight || 0;
				if (typeof wx !== 'undefined' && wx.getMenuButtonBoundingClientRect) {
					const menuButton = wx.getMenuButtonBoundingClientRect();
					this.topOffset = menuButton.bottom + uni.upx2px(16);
				} else {
					this.topOffset = statusBar + uni.upx2px(88);
				}
			} catch (e) {
				this.topOffset = 88;
			}
		},
		clearTimer() {
			if (this.hideTimer) {
				clearTimeout(this.hideTimer);
				this.hideTimer = null;
			}
		},
		show(options = {}) {
			const {
				text = '数据已刷新',
				type = 'success',
				duration = 1500,
			} = options;

			this.clearTimer();
			this.text = text;
			this.type = type;
			this.visible = true;
			this.animated = false;
			this.$nextTick(() => {
				this.animated = true;
			});

			this.hideTimer = setTimeout(() => {
				this.hide();
			}, duration);
		},
		hide() {
			this.clearTimer();
			this.animated = false;
			setTimeout(() => {
				this.visible = false;
			}, 200);
		},
	},
};
</script>

<style lang="scss" scoped>
.d-top-message {
	position: fixed;
	left: 50%;
	z-index: 100000;
	display: flex;
	flex-direction: row;
	align-items: center;
	max-width: 80vw;
	padding: 10rpx 28rpx;
	border-radius: 999rpx;
	opacity: 0;
	transform: translate(-50%, -12rpx);
	transition: opacity 0.2s ease, transform 0.2s ease;
	pointer-events: none;
	box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.08);
}

.d-top-message--show {
	opacity: 1;
	transform: translate(-50%, 0);
}

.d-top-message--success {
	background: #E8F8F3;
}

.d-top-message-text {
	font-size: 24rpx;
	line-height: 1.4;
	color: #6ACDBB;
	white-space: nowrap;
}

.d-top-message-icon {
	margin-right: 8rpx;
	flex-shrink: 0;
}
</style>
