<template>
	<view
		v-if="visible"
		class="common-loading"
		:class="{'common-loading--mask': mask}"
		@touchmove.stop.prevent="noop"
		@tap.stop="noop"
	>
		<view class="common-loading__box">
			<image class="common-loading__gif" src="/static/images/img/loading.gif" mode="aspectFit"></image>
			<view v-if="title" class="common-loading__text">{{ title }}</view>
		</view>
	</view>
</template>

<script>
	import { LOADING_HIDE_EVENT, LOADING_SHOW_EVENT, getLoadingState } from '@/utils/loading.js'

	export default {
		name: 'CommonLoading',
		data() {
			return {
				visible: false,
				title: '加载中...',
				mask: true
			}
		},
		created() {
			const state = getLoadingState()
			this.visible = state.visible
			this.title = state.title
			this.mask = state.mask
			uni.$on(LOADING_SHOW_EVENT, this.show)
			uni.$on(LOADING_HIDE_EVENT, this.hide)
		},
		beforeDestroy() {
			uni.$off(LOADING_SHOW_EVENT, this.show)
			uni.$off(LOADING_HIDE_EVENT, this.hide)
		},
		methods: {
			show(options = {}) {
				this.visible = true
				this.title = options.title || '加载中...'
				this.mask = options.mask !== false
			},
			hide() {
				this.visible = false
			},
			noop() {}
		}
	}
</script>

<style lang="scss" scoped>
	.common-loading {
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		z-index: 99999;
		display: flex;
		align-items: center;
		justify-content: center;
		pointer-events: none;
		background: rgba(0, 0, 0, 0.18);
	}

	.common-loading--mask {
		pointer-events: auto;
	}

	.common-loading__box {
		min-width: 180rpx;
		min-height: 180rpx;
		padding: 34rpx 36rpx 30rpx;
		border-radius: 28rpx;
		background: rgba(255, 255, 255, 0.96);
		box-shadow: 0 18rpx 46rpx rgba(0, 0, 0, 0.16);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.common-loading__gif {
		width: 92rpx;
		height: 92rpx;
	}

	.common-loading__text {
		margin-top: 18rpx;
		max-width: 320rpx;
		font-size: 26rpx;
		line-height: 36rpx;
		color: #333;
		text-align: center;
	}
</style>
