import appSettings from '@/core/config/app-settings'
import store from '@/store'

const TAB_ROUTES = new Set([
	'/pages/index/index',
	'/pages/feed/index',
	'/pages/live/hall',
	'/pages/dynamics/index',
	'/pages/mine/index',
	'/pages/index',
	'/pages/category',
	'/pages/feed',
	'/pages/cart',
	'/pages/user'
])

export function isExternalHttpUrl(url) {
	const raw = String(url || '').trim()
	return /^https?:\/\//i.test(raw) || /^\/\//.test(raw)
}

export function buildWebViewPageUrl(targetUrl, title = '') {
	const encoded = encodeURIComponent(targetUrl)
	let path = `/pages/common/webview?url=${encoded}`
	if (title) path += `&title=${encodeURIComponent(title)}`
	return path
}

/**
 * 跳转应用内原生页面（非 H5 WebView）
 * @param {string} jumpUrl 如 /pages/index/scenic-list 或 pages/foo/bar?id=1
 * @returns {boolean} 是否识别为有效应用内路径
 */
export function openInAppRoute(jumpUrl) {
	const raw = String(jumpUrl || '').trim()
	if (!raw || isExternalHttpUrl(raw)) return false

	let path = raw
	if (!path.startsWith('/')) {
		if (path.startsWith('pages/')) path = `/${path}`
		else return false
	}

	const qIdx = path.indexOf('?')
	const basePath = qIdx >= 0 ? path.slice(0, qIdx) : path

	if (TAB_ROUTES.has(basePath)) {
		uni.switchTab({
			url: basePath,
			fail: () => uni.reLaunch({ url: basePath })
		})
		return true
	}

	uni.navigateTo({
		url: path,
		fail: () => {
			uni.showToast({ title: '页面不存在', icon: 'none' })
		}
	})
	return true
}

/**
 * 根据后端 jump_url 跳转：应用内页面 或 应用内 WebView 打开 H5
 * @param {string} jumpUrl
 * @param {{ title?: string }} [opts]
 */
export function openJumpUrl(jumpUrl, opts = {}) {
	const raw = String(jumpUrl || '').trim()
	if (!raw) return

	if (isExternalHttpUrl(raw)) {
		const href = raw.startsWith('//') ? `https:${raw}` : raw
		uni.navigateTo({
			url: buildWebViewPageUrl(href, opts.title || ''),
			fail: () => openExternalUrl(href)
		})
		return
	}

	openInAppRoute(raw)
}

export function openPage(url, animationType = 'pop-in', animationDuration = 300) {
	uni.navigateTo({
		url,
		animationType,
		animationDuration,
		success: (res) => appSettings.debug && console.log(res),
		fail: (err) => appSettings.debug && console.log(err)
	})
}

export function popPages(delta = 1) {
	uni.navigateBack({ delta })
}

export function openWithLogin(url) {
	const target = store.state.user.isLogin ? url : '/pages/passport/lobby'
	openPage(target)
}

export function openAnyLink(rawUrl) {
	const url = decodeURIComponent(rawUrl)
	if (TAB_ROUTES.has(url)) {
		uni.switchTab({ url })
	} else {
		openPage(url)
	}
}

/** 在系统默认浏览器中打开 https 链接（App / H5） */
export function openExternalUrl(url) {
	if (!url || !/^https?:\/\//i.test(url)) return
	// #ifdef H5
	window.open(url, '_blank')
	return
	// #endif
	// #ifdef APP-PLUS
	plus.runtime.openURL(url, () => {
		uni.showToast({ title: '無法打開連結', icon: 'none' })
	})
	return
	// #endif
	if (typeof plus !== 'undefined' && plus.runtime && plus.runtime.openURL) {
		plus.runtime.openURL(url, () => {
			uni.showToast({ title: '無法打開連結', icon: 'none' })
		})
	} else {
		uni.setClipboardData({
			data: url,
			success: () => uni.showToast({ title: '連結已複製', icon: 'none' })
		})
	}
}

export function previousPageVm() {
	const stack = getCurrentPages()
	const prior = stack[stack.length - 2]
	// #ifdef H5
	return prior
	// #endif
	return prior ? prior.$vm : null
}

export function setNavTitle(text = '', barStyle = {}) {
	if (text) uni.setNavigationBarTitle({ title: text })
	if (Object.keys(barStyle).length) uni.setNavigationBarColor(barStyle)
}

/** 评论/动态等场景：从评论行解析用户标识（优先 user_no） */
export function resolveCommentUserId(row) {
	if (!row) return ''
	const user = row.user
	const rowUserNo = row.user_no != null && String(row.user_no).trim() !== ''
		? String(row.user_no).trim()
		: ''
	if (rowUserNo) return rowUserNo
	const userUserNo = user && user.user_no != null && String(user.user_no).trim() !== ''
		? String(user.user_no).trim()
		: ''
	if (userUserNo) return userUserNo
	return String((user && user.id) || row.user_id || '').trim()
}

/** 打开用户主页 pages/profile/show?id= */
export function openUserProfile(rowOrId) {
	const id = (rowOrId && typeof rowOrId === 'object')
		? resolveCommentUserId(rowOrId)
		: String(rowOrId || '').trim()
	if (!id) return false
	uni.navigateTo({
		url: `/pages/profile/show?id=${encodeURIComponent(id)}`,
		fail: () => {
			uni.showToast({ title: '无法打开主页', icon: 'none' })
		}
	})
	return true
}
