<template>
	<view class="page_preview">
		<commonHeader :title="fileName" @back="goBack"></commonHeader>

		<!-- #ifdef APP-PLUS -->
		<view class="app_container">
			<view v-if="showLoading" class="loading_container">
				<text class="loading_text">{{ loadingText }}</text>
			</view>

			<view v-if="showError" class="error_container">
				<text class="error_title">文件暂时无法预览</text>
				<text class="error_text">{{ errorMessage }}</text>
				<view class="error_btn" @click="retryPreview">
					<text class="error_btn_text">重新尝试</text>
				</view>
			</view>

			<view v-if="showDownloadBtn && !showLoading && !showError" class="download_container">
				<text class="file_name">{{ fileName }}</text>
				<text class="file_tip">{{ fileTip }}</text>
				<view class="download_btn" @click="handleDownload">
					<text class="download_btn_text">点击下载预览</text>
				</view>
			</view>
		</view>
		<!-- #endif -->

		<!-- #ifdef H5 -->
		<web-view
			v-if="resolvedPreviewUrl"
			:src="resolvedPreviewUrl"
			class="preview_webview"
			@error="handleWebViewError"
			@load="handleWebViewLoad"
		></web-view>

		<view v-if="showLoading" class="loading_container">
			<text class="loading_text">加载中...</text>
		</view>

		<view v-if="showError" class="error_container">
			<text class="error_title">文件暂时无法预览</text>
			<text class="error_text">当前文件可能不支持在线预览，或预览服务暂时不可用。</text>
			<view class="error_btn" @click="retryPreview">
				<text class="error_btn_text">重新尝试</text>
			</view>
		</view>
		<!-- #endif -->
	</view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import CommonHeader from '@/components/commonHeader.vue';

const PREVIEW_STORAGE_KEY = 'noticePreviewFile';
const fileUrl = ref('');
const fileName = ref('文件预览');
const fileExtension = ref('');
const resolvedPreviewUrl = ref('');
const showLoading = ref(true);
const showError = ref(false);
const showDownloadBtn = ref(false);
const loadingText = ref('正在加载...');
const errorMessage = ref('当前文件可能不支持在线预览，或预览服务暂时不可用。');
const fileTip = ref('当前文件需下载后才能预览');

const getFileExtension = (url) => {
	if (!url) return '';
	const cleanUrl = url.split('?')[0].split('#')[0];
	return cleanUrl.split('.').pop()?.toLowerCase() || '';
};

const isImageFile = (ext) => {
	return ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(ext);
};

const isPdfFile = (ext) => ext === 'pdf';

const isOfficeFile = (ext) => {
	return ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'csv'].includes(ext);
};

const applyPreviewData = (data) => {
	if (!data) return;

	if (data.url) fileUrl.value = data.url;
	if (data.name) fileName.value = data.name;

	fileExtension.value = getFileExtension(fileUrl.value);

	// #ifdef APP-PLUS
	initAppPreview();
	// #endif

	// #ifdef H5
	initH5Preview();
	// #endif
};

// #ifdef APP-PLUS
const initAppPreview = () => {
	showLoading.value = true;
	showError.value = false;
	showDownloadBtn.value = false;

	const ext = fileExtension.value;

	if (!fileUrl.value) {
		showLoading.value = false;
		showError.value = true;
		errorMessage.value = '文件地址无效';
		return;
	}

	if (isImageFile(ext)) {
		previewImage();
	} else if (isPdfFile(ext) || isOfficeFile(ext)) {
		downloadAndOpenFile();
	} else {
		showLoading.value = false;
		showDownloadBtn.value = true;
		fileTip.value = `当前文件类型(.${ext || '未知'})需下载后查看`;
	}
};

const previewImage = () => {
	showLoading.value = true;
	loadingText.value = '正在加载图片...';

	uni.previewImage({
		urls: [fileUrl.value],
		current: fileUrl.value,
		fail: (err) => {
			console.error('预览图片失败:', err);
			downloadAndOpenFile();
		}
	});
};

const downloadAndOpenFile = () => {
	showLoading.value = true;
	loadingText.value = '正在下载文件...';
	showError.value = false;

	const token = uni.getStorageSync('token');

	const downloadOptions = {
		url: fileUrl.value,
		success: (res) => {
			if (res.statusCode === 200) {
				openFile(res.tempFilePath);
			} else {
				showLoading.value = false;
				showError.value = true;
				errorMessage.value = `下载失败(${res.statusCode})，请检查网络后重试`;
			}
		},
		fail: (err) => {
			console.error('下载文件失败:', err);
			showLoading.value = false;
			showError.value = true;
			errorMessage.value = '下载失败，请检查网络连接后重试';
		}
	};

	if (token) {
		downloadOptions.header = {
			'Authorization': token
		};
	}

	uni.downloadFile(downloadOptions);
};

const openFile = (filePath) => {
	showLoading.value = false;

	uni.openDocument({
		filePath: filePath,
		showMenu: true,
		fail: (err) => {
			console.error('打开文件失败:', err);
			uni.showToast({
				title: '当前设备不支持预览此文件',
				icon: 'none'
			});
		}
	});
};

const handleDownload = () => {
	downloadAndOpenFile();
};
// #endif

// #ifdef H5
const initH5Preview = () => {
	showLoading.value = true;
	showError.value = false;

	const ext = fileExtension.value;
	const url = fileUrl.value;

	if (!url) {
		showLoading.value = false;
		showError.value = true;
		return;
	}

	if (isImageFile(ext)) {
		previewImageH5();
	} else if (isPdfFile(ext)) {
		resolvedPreviewUrl.value = url;
	} else if (isOfficeFile(ext)) {
		resolvedPreviewUrl.value = buildOfficePreviewUrl(url);
	} else {
		resolvedPreviewUrl.value = url;
	}
};

const previewImageH5 = () => {
	uni.previewImage({
		urls: [fileUrl.value],
		current: fileUrl.value,
		fail: () => {
			resolvedPreviewUrl.value = fileUrl.value;
		}
	});
};

const buildOfficePreviewUrl = (url) => {
	return `https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(url)}`;
};

const handleWebViewLoad = () => {
	showLoading.value = false;
	showError.value = false;
};

const handleWebViewError = () => {
	showLoading.value = false;
	showError.value = true;
};
// #endif

const retryPreview = () => {
	// #ifdef APP-PLUS
	initAppPreview();
	// #endif

	// #ifdef H5
	initH5Preview();
	// #endif
};

onLoad((options) => {
	const eventChannel = typeof uni.getOpenerEventChannel === 'function'
		? uni.getOpenerEventChannel()
		: null;
	if (eventChannel && typeof eventChannel.on === 'function') {
		eventChannel.on('previewFileData', (data) => {
			applyPreviewData(data);
		});
	}

	const storageData = uni.getStorageSync(PREVIEW_STORAGE_KEY);
	if (storageData) {
		try {
			applyPreviewData(JSON.parse(storageData));
		} catch (error) {
			console.error('解析预览文件信息失败:', error);
		}
		uni.removeStorageSync(PREVIEW_STORAGE_KEY);
	}

	if (options && options.url && !fileUrl.value) {
		fileUrl.value = decodeURIComponent(options.url);
	}
	if (options && options.name && !fileName.value) {
		fileName.value = decodeURIComponent(options.name);
	}

	if (!resolvedPreviewUrl.value && fileUrl.value) {
		applyPreviewData({
			url: fileUrl.value,
			name: fileName.value
		});
	} else if (!fileUrl.value) {
		showLoading.value = false;
		showError.value = true;
		errorMessage.value = '文件地址无效';
	}
});

onMounted(() => {
	if (!fileUrl.value) {
		showLoading.value = false;
		showError.value = true;
		errorMessage.value = '未获取到文件信息';
	}
});

onUnmounted(() => {
	resolvedPreviewUrl.value = '';
});

const goBack = () => {
	uni.navigateBack();
};
</script>

<style lang="scss">
.page_preview {
	height: 100vh;
	display: flex;
	flex-direction: column;
	background-color: #FFFFFF;
}

.preview_webview {
	flex: 1;
	margin-top: 96rpx;
}

.app_container {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 0 48rpx;
}

.download_container {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 60rpx 48rpx;
	background-color: #F9FAFF;
	border-radius: 20rpx;
	width: 100%;

	.file_name {
		font-size: 32rpx;
		font-weight: 500;
		color: #333333;
		margin-bottom: 16rpx;
		text-align: center;
		word-break: break-all;
	}

	.file_tip {
		font-size: 26rpx;
		color: #999999;
		margin-bottom: 40rpx;
		text-align: center;
	}

	.download_btn {
		background-color: #2E64FA;
		border-radius: 12rpx;
		padding: 24rpx 64rpx;

		.download_btn_text {
			font-size: 30rpx;
			color: #FFFFFF;
			font-weight: 500;
		}
	}
}

.loading_container {
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	background-color: rgba(0, 0, 0, 0.6);
	padding: 40rpx 60rpx;
	border-radius: 16rpx;
	z-index: 1000;

	.loading_text {
		font-size: 28rpx;
		color: #FFFFFF;
	}
}

.error_container {
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 560rpx;
	padding: 48rpx 40rpx;
	background: #FFFFFF;
	border-radius: 24rpx;
	box-shadow: 0 16rpx 56rpx rgba(0, 0, 0, 0.15);
	display: flex;
	flex-direction: column;
	align-items: center;
	z-index: 1001;

	.error_title {
		font-size: 34rpx;
		font-weight: 600;
		color: #333333;
		margin-bottom: 20rpx;
	}

	.error_text {
		font-size: 26rpx;
		line-height: 1.8;
		color: #8A9099;
		text-align: center;
		margin-bottom: 40rpx;
	}

	.error_btn {
		min-width: 240rpx;
		height: 80rpx;
		padding: 0 40rpx;
		border-radius: 40rpx;
		background: #2E64FA;
		display: flex;
		align-items: center;
		justify-content: center;

		.error_btn_text {
			font-size: 30rpx;
			color: #FFFFFF;
			font-weight: 500;
		}
	}
}
</style>
