<template>
	<view class="art-page art-page--advert">
		<view class="art-nav" :style="{ paddingTop: statusBar + 'px' }">
			<view class="art-nav-row">
				<view class="art-back" @tap="goBack">
					<text class="art-back-icon">←</text>
				</view>
				<text class="art-nav-title">{{ navTitle }}</text>
				<view class="art-nav-placeholder" />
			</view>
		</view>

		<web-view
			v-if="hasUrl"
			class="art-webview"
			:style="{ height: webViewHeight + 'px' }"
			:webview-styles="webviewStyles"
			:src="article.url"
		/>

		<scroll-view
			v-else
			scroll-y
			class="art-scroll"
			:style="{ height: scrollHeight + 'px' }"
		>
			<view class="art-body" :style="{ paddingBottom: safeBottom + 'px' }">
				<view v-if="loading" class="art-state">
					<text class="art-state-txt">{{ copy.loading }}</text>
				</view>
				<view v-else class="art-card">
					<rich-text class="art-rich" :nodes="contentNodes" />
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import {
	fetchAdvertDetails,
	formatArticleRichContent,
	isExternalArticleUrl
} from '@/features/article/article-gateway'

export default {
	data() {
		return {
			statusBar: 0,
			scrollHeight: 600,
			webViewHeight: 600,
			safeBottom: 0,
			articleId: '',
			navTitle: '',
			loading: true,
			article: {},
			contentNodes: [],
			webviewStyles: {
				progress: {
					color: '#4a8cff'
				}
			}
		}
	},
	computed: {
		copy() {
			const t = this.$t.bind(this)
			return {
				loading: t('article.loading'),
				loadFailed: t('article.loadFailed')
			}
		},
		hasUrl() {
			return isExternalArticleUrl(this.article && this.article.url)
		}
	},
	onLoad(option) {
		const sys = uni.getSystemInfoSync()
		this.statusBar = sys.statusBarHeight || 0
		this.safeBottom = sys.safeAreaInsets ? sys.safeAreaInsets.bottom : 0
		const navH = this.statusBar + uni.upx2px(88)
		const bodyH = (sys.windowHeight || 667) - navH
		this.scrollHeight = bodyH
		this.webViewHeight = bodyH

		this.articleId = option.id || ''
		this.navTitle = this.copy.loading
		this.loadArticle()
	},
	methods: {
		goBack() {
			if (getCurrentPages().length > 1) {
				uni.navigateBack({ delta: 1 })
			} else {
				uni.switchTab({
					url: '/pages/index/index',
					fail: () => uni.reLaunch({ url: '/pages/index/index' })
				})
			}
		},
		async loadArticle() {
			if (!this.articleId) {
				this.loading = false
				this.$appKit.msg(this.copy.loadFailed)
				return
			}
			this.loading = true
			try {
				const data = await fetchAdvertDetails(this.articleId)
				this.article = data
				if (data.title) {
					this.navTitle = data.title
				}
				if (!this.hasUrl) {
					const rich = formatArticleRichContent(data.content, null, {
						hideImages: true
					})
					this.contentNodes = rich.html ? rich.html : rich.nodes
				}
			} catch (err) {
				this.$appKit.msg((err && err.message) || this.copy.loadFailed)
			} finally {
				this.loading = false
			}
		}
	}
}
</script>

<style scoped>
@import './article-shared.css';
</style>
