<template>
	<view v-if="mySrc">
		<web-view @message="receiveMessage" class="body" :webview-styles="webviewStyles" :src="mySrc"></web-view>
	</view>
</template>

<script>
	import {
		configGetMemberWx,
		getUserToken,
		APP_NAME,
		staticUrl,
		cacheDataLoopRedirect,
		cleanUserToken,
		saveUserToken
	} from '../js/request.js'

	const REDIRECT_NAME = 'redirect'

	export default {
		name: 'uniWebView',
		props: ['src', 'name', 'useH5', 'connection', 'hideBar', 'enableSerConfig'],
		watch: {
			name() {
				this.updateBarTitle()
			},
			src() {
				this.updateSrc()
			}
		},
		data() {
			return {
				config: null,
				mySrc: null,
				webviewStyles: {
					progress: {
						color: '#FF3333'
					}
				}
			}
		},
		created() {
			if (this.enableSerConfig) {
				this.configGetMemberWxReq()
			} else {
				this.updateSrc()
			}
			this.updateBarTitle()
		},
		methods: {
			receiveMessage(event) {
				const data = event.detail.data[0]
				if (data.logout) {
					cleanUserToken()
					this.$api.msg('退出成功')
					uni.redirectTo({
						url: '/pages/index/store'
					})
				} else if (data.setUserToken) {
					const token = data.token
					if (token) {
						saveUserToken(token)
						if (token !== getUserToken()) {
							this.$api.msg('登录成功')
							uni.redirectTo({
								url: '/pages/index/store'
							})
						}
					}
				}
			},
			async configGetMemberWxReq() {
				try {
					this.config = await configGetMemberWx()
				} catch (e) {
					this.$error(`configGetMemberWx Fail:`, e)
				}
				this.updateSrc()
			},
			updateSrc() {
				let mySrc = this.src
				if (!mySrc) return
				if (!mySrc.startsWith('http')) {
					if (!this.config) mySrc = staticUrl(mySrc)
					else mySrc = this.config.h5Host + mySrc
				}

				let find = mySrc
				let indexHash = find.indexOf("#")
				if (indexHash !== -1) find = find.substr(indexHash)
				let addEm = "?"
				if (find.indexOf("?") !== -1) {
					addEm = '&'
				}

				if (mySrc.indexOf("user-token") === -1) {
					mySrc += `${addEm}user-token=${getUserToken()}`
				}

				if (!this.connection) {
					let route = cacheDataLoopRedirect() || ''
					mySrc += `&${REDIRECT_NAME}=${route}`
				}

				if (this.hideBar) {
					mySrc += `&bar-state=1`
				}

				mySrc += `&OrderPaymentGoMini=1`

				this.mySrc = mySrc
				return mySrc
			},
			updateBarTitle(name = this.name) {
				uni.setNavigationBarTitle({
					title: name || APP_NAME
				})
			}
		}
	}
</script>

<style>
	.body {}
</style>
