<template>
	<view
		v-if="visible"
		class="fe-report-float"
		:style="{ top: top + 'px' }"
		@touchstart="onTouchStart"
		@touchmove.stop.prevent="onTouchMove"
		@touchend="onTouchEnd"
	>
		<text class="fe-report-float__icon">📊</text>
	</view>
</template>

<script>
export default {
	name: 'FeReportFloat',
	props: {
		visible: { type: Boolean, default: false }
	},
	data() {
		return {
			top: 0,
			dragging: false,
			touchStartY: 0,
			startTop: 0,
			moved: false,
			inited: false
		}
	},
	watch: {
		visible(val) {
			if (val && !this.inited) this.initPosition()
		}
	},
	mounted() {
		if (this.visible) this.initPosition()
	},
	methods: {
		initPosition() {
			const sys = uni.getSystemInfoSync()
			const headerH = uni.upx2px(112)
			const insetBottom = (sys.safeAreaInsets && sys.safeAreaInsets.bottom) || 0
			const footerH = uni.upx2px(128 + 112) + insetBottom
			const floatH = uni.upx2px(88)
			const min = headerH + uni.upx2px(24)
			const max = sys.windowHeight - footerH - floatH - uni.upx2px(24)
			this.top = min + (max - min) * 0.38
			this.inited = true
		},
		getBounds() {
			const sys = uni.getSystemInfoSync()
			const headerH = uni.upx2px(112)
			const insetBottom = (sys.safeAreaInsets && sys.safeAreaInsets.bottom) || 0
			const footerH = uni.upx2px(128 + 112) + insetBottom
			const floatH = uni.upx2px(88)
			return {
				min: headerH + uni.upx2px(16),
				max: sys.windowHeight - footerH - floatH - uni.upx2px(16)
			}
		},
		clampTop(value) {
			const { min, max } = this.getBounds()
			return Math.max(min, Math.min(max, value))
		},
		onTouchStart(e) {
			this.dragging = true
			this.moved = false
			this.touchStartY = e.touches[0].clientY
			this.startTop = this.top
		},
		onTouchMove(e) {
			if (!this.dragging) return
			const dy = e.touches[0].clientY - this.touchStartY
			if (Math.abs(dy) > 4) this.moved = true
			this.top = this.clampTop(this.startTop + dy)
		},
		onTouchEnd() {
			this.dragging = false
			this.top = this.clampTop(this.top)
			if (!this.moved) this.$emit('open')
		}
	}
}
</script>

<style lang="scss" scoped>
.fe-report-float {
	position: fixed;
	left: 0;
	z-index: 98;
	width: 88rpx;
	height: 88rpx;
	border-radius: 0 44rpx 44rpx 0;
	background: linear-gradient(135deg, $fe-primary, $fe-secondary);
	color: #fff;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 4rpx 4rpx 24rpx rgba(124, 58, 237, 0.35);
}

.fe-report-float__icon {
	font-size: 40rpx;
	line-height: 1;
}
</style>
