<template>
	<view class="main">
		<view class="toptitle">
			<view class="toptitle_left" @click="ht">
				<u-icon name="arrow-left" color="#fff" size="20"></u-icon>
			</view>
			<view class="toptitle_title">
				知识详情
			</view>
		</view>
		<view class="" style="padding: 10px;background-color: #fff;border-radius: 5px;margin-bottom: 15px;">
			<u-subsection :list="list" fontSize="14" activeColor="#0052D8" :current="current" @change='change'></u-subsection>
		</view>
		<view class="box" v-if="current == 0">
			<view class="tips">
				<view class="tip">
				</view>
				<view class="tiptitle">
					基础资料
				</view>
			</view>
			<view class="box_item">
				<view class="f1">设备名称</view>
				<view class="f2">{{ detail.sbm || '无' }}</view>
			</view>
			<view class="box_item">
				<view class="f1">规格型号</view>
				<view class="f2">{{ detail.gg || '无' }}</view>
			</view>
			<view class="box_item">
				<view class="f1">知识概要</view>
				<view class="f2">{{ detail.gy || '无' }}</view>
			</view>
			<view class="box_item">
				<view class="f1">知识分类</view>
				<view class="f2">{{ getFlName(detail.fl) || '无' }}</view>
			</view>
			<view class="box_item" style="display: flex;flex-direction: column;align-items: flex-start;">
				<view class="f1" style="margin-bottom: 15px;">设备介绍</view>
				<u-parse :content="detail.sbjs || ''"></u-parse>
			</view>
		</view>
		<view class="box1" v-if="current == 1">
			<view class="tips">
				<view class="tip">
				</view>
				<view class="tiptitle">
					相关资料
				</view>
			</view>
			<!-- 图片附件（fj1） -->
			<view v-if="detail.fj1 && detail.fj1.length > 0">
				<view style="padding: 10px 20px; font-weight: bold; color: #333; border-bottom: 1px solid #e5e5e5;">
					图片附件
				</view>
				<!-- 图片缩略图展示 -->
				<view v-if="getImageFiles(detail.fj1).length > 0" style="padding: 15px 20px;">
					<view style="display: flex; flex-wrap: wrap; gap: 10px;">
						<view 
							v-for="(img, index) in getImageFiles(detail.fj1)" 
							:key="'img-' + (img.fileId || index)"
							style="position: relative; width: 30%; padding-bottom: 30%;"
							@click="previewImage(index, getImageFiles(detail.fj1))"
						>
							<image 
								:src="getFullUrl(img.url)" 
								mode="aspectFill"
								style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border-radius: 6px; border: 1px solid #e5e5e5;"
							></image>
							<view style="position: absolute; bottom: 0; left: 0; right: 0; background: linear-gradient(to top, rgba(0,0,0,0.5), transparent); border-radius: 0 0 6px 6px; padding: 5px;">
								<text style="color: #fff; font-size: 12px; display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{img.name}}</text>
							</view>
						</view>
					</view>
				</view>
				<!-- 非图片文件列表展示 -->
				<view v-if="getNonImageFiles(detail.fj1).length > 0">
					<view class="box_item1" v-for="(file, index) in getNonImageFiles(detail.fj1)" :key="'fj1-nonimg-' + (file.fileId || index)">
						<view class="left">
							<view class="left_image">
								<image v-if="getFileType(file) == 'pdf'" src='../../../static/PDF.png' mode=""></image>
								<image v-else-if="getFileType(file) == 'doc' || getFileType(file) == 'docx'" src='../../../static/WORD.png' mode=""></image>
								<image v-else-if="getFileType(file) == 'xlsx' || getFileType(file) == 'xls'" src='../../../static/WORD.png' mode=""></image>
								<u-icon v-else-if="isVideoType(getFileType(file))" name="play-circle-fill" color="#0052D8" size="40"></u-icon>
								<image v-else src='../../../static/WORD.png' mode=""></image>
							</view>
							<view class="l_title">
								<view class="l_title_f1">
									{{ file.name }}
								</view>
							</view>
						</view>
						<view class="right">
							<view @click="previewFile(file)">
								<u-button size="small" type="primary" text="查看"></u-button>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 其它附件（fj2） -->
			<view v-if="detail.fj2 && detail.fj2.length > 0">
				<view style="padding: 10px 20px; font-weight: bold; color: #333; border-bottom: 1px solid #e5e5e5; margin-top: 10px;">
					其它附件
				</view>
				<view class="box_item1" v-for="(file, index) in detail.fj2" :key="'fj2-' + (file.fileId || index)">
					<view class="left">
						<view class="left_image">
							<image v-if="getFileType(file) == 'pdf'" src='../../../static/PDF.png' mode=""></image>
							<image v-else-if="getFileType(file) == 'doc' || getFileType(file) == 'docx'" src='../../../static/WORD.png' mode=""></image>
							<image v-else-if="getFileType(file) == 'xlsx' || getFileType(file) == 'xls'" src='../../../static/WORD.png' mode=""></image>
							<image v-else-if="getFileType(file) == 'png' || getFileType(file) == 'jpg' || getFileType(file) == 'jpeg'" src='../../../static/img/picture.png' mode=""></image>
							<u-icon v-else-if="isVideoType(getFileType(file))" name="play-circle-fill" color="#0052D8" size="40"></u-icon>
							<image v-else src='../../../static/WORD.png' mode=""></image>
						</view>
						<view class="l_title">
							<view class="l_title_f1">
								{{ file.name }}
							</view>
						</view>
					</view>
					<view class="right">
						<view @click="previewFile(file)">
							<u-button size="small" type="primary" text="查看"></u-button>
						</view>
					</view>
				</view>
			</view>
			<!-- 空状态提示 -->
			<view v-if="(!detail.fj1 || detail.fj1.length === 0) && (!detail.fj2 || detail.fj2.length === 0)" style="text-align: center; padding: 40px 20px; color: #999;">
				<text>暂无相关资料</text>
			</view>
		</view>
	</view>
</template>

<script>
import service from '@/service/service.js'
export default {
	data() {
		return {
			list: ['基础资料', '相关资料'],
			current: 0,
			id: '',
			detail: { sbm: '', gg: '', gy: '', sbjs: '', fl: '', fj1: [], fj2: [] },
			flOptions: []
		}
	},
onLoad(options){
		this.id = options && options.id ? options.id : ''
		this.getflOptions()
		if(this.id){
			this.fetchDetail()
		}
	},
methods: {
			getflOptions(){
				this.API.hqcpfl("626798056427226373").then(res => {
					if(res.code == 200 && res.data && res.data.list){
						this.flOptions = res.data.list;
					}
				}).catch(err => {
					console.error('获取分类选项失败:', err);
					this.flOptions = [];
				});
			},
			getFlName(flId){
				if (!flId) return '';
				const findFlName = (options, id) => {
					for(let i = 0; i < options.length; i++){
						if(options[i].id === id) return options[i].fullName;
						if(options[i].children && options[i].children.length > 0){
							const found = findFlName(options[i].children, id);
							if(found) return found;
						}
					}
					return null;
				};
				const flName = findFlName(this.flOptions, flId);
				return flName || flId;
			},
    fetchDetail(){
			this.API.zskxq({ id: this.id, n: Date.now() }).then(res=>{
				console.log("知识详情数据:", res);
				this.detail = res.data || { sbm: '', gg: '', gy: '', sbjs: '', fl: '', fj1: [], fj2: [] }
				
				// 确保附件字段是数组
				if (!Array.isArray(this.detail.fj1)) {
					if (typeof this.detail.fj1 === 'string' && this.detail.fj1) {
						try {
							this.detail.fj1 = JSON.parse(this.detail.fj1);
						} catch (e) {
							console.warn('解析 fj1 JSON 失败:', e);
							this.detail.fj1 = [];
						}
					} else {
						this.detail.fj1 = [];
					}
				}
				if (!Array.isArray(this.detail.fj2)) {
					if (typeof this.detail.fj2 === 'string' && this.detail.fj2) {
						try {
							this.detail.fj2 = JSON.parse(this.detail.fj2);
						} catch (e) {
							console.warn('解析 fj2 JSON 失败:', e);
							this.detail.fj2 = [];
						}
					} else {
						this.detail.fj2 = [];
					}
				}
				
				console.log("处理后的附件数据 - fj1(图片):", this.detail.fj1);
				console.log("处理后的附件数据 - fj2(其它):", this.detail.fj2);
				console.log("fj1 数量:", this.detail.fj1 ? this.detail.fj1.length : 0);
				console.log("fj2 数量:", this.detail.fj2 ? this.detail.fj2.length : 0);
				
				// 初始化附件下载状态
				if (Array.isArray(this.detail.fj1)) {
					this.detail.fj1.forEach(file => {
						this.$set(file, 'downloaded', false)
						this.$set(file, 'downloading', false)
						this.$set(file, 'downloadProgress', 0)
						this.$set(file, 'filePath', null)
					})
				}
				if (Array.isArray(this.detail.fj2)) {
					this.detail.fj2.forEach(file => {
						this.$set(file, 'downloaded', false)
						this.$set(file, 'downloading', false)
						this.$set(file, 'downloadProgress', 0)
						this.$set(file, 'filePath', null)
					})
				}
			}).catch(err => {
				console.error("获取知识详情失败:", err);
			});
		},
			change(e){
				this.current = e
			},
			ht(){
				uni.navigateBack({
				    delta: 1
				});
            },
            cktp() {
				uni.previewImage({
					urls: ["http://115.29.210.249/tggPic/content/2021-09/1630475389708.jpg"], //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
					current: '', // 当前显示图片的http链接，默认是第一个
				})
            },
            timestampToTime(timestamp) {
				if(!timestamp) return ''
				const date = new Date(timestamp);
				const Y = date.getFullYear() + '-';
				const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
				const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
				const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
				const m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
				const s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
				return Y + M + D + h + m + s;
            },
            getFileType(file){
                const raw = (file.name || file.url || '').toLowerCase()
                return raw.includes('.') ? raw.split('.').pop() : ''
            },
			// 判断是否为视频类型
			isVideoType(type) {
				const videoTypes = ['mp4', 'mov', 'avi', 'wmv', 'mkv', 'webm', 'mpeg', 'mpg', 'flv', '3gp'];
				return videoTypes.includes((type || '').toLowerCase());
			},
			// 判断是否为图片类型
			isImageType(type) {
				const imageTypes = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'];
				return imageTypes.includes((type || '').toLowerCase());
			},
			// 判断是否为PDF类型
			isPdfType(type) {
				return (type || '').toLowerCase() === 'pdf';
			},
			// 获取完整URL
			getFullUrl(url) {
				if (!url) return '';
				if (url.startsWith('http://') || url.startsWith('https://')) {
					return url;
				}
				return 'https://hhjj.antissoft.com' + url;
			},
			// 从文件列表中筛选出图片文件
			getImageFiles(files) {
				if (!Array.isArray(files)) return [];
				return files.filter(file => {
					const fileType = this.getFileType(file);
					return this.isImageType(fileType);
				});
			},
			// 从文件列表中筛选出非图片文件
			getNonImageFiles(files) {
				if (!Array.isArray(files)) return [];
				return files.filter(file => {
					const fileType = this.getFileType(file);
					return !this.isImageType(fileType);
				});
			},
			// 预览图片（从图片文件列表中）
			previewImage(index, imageFiles) {
				const images = imageFiles.map(img => this.getFullUrl(img.url));
				uni.previewImage({
					current: index,
					urls: images
				});
			},
			// 统一文件预览方法（在线预览，不支持下载）
			previewFile(file) {
				const fileUrl = this.getFullUrl(file.url);
				const fileType = this.getFileType(file);
				
				// 图片预览
				if (this.isImageType(fileType)) {
					uni.previewImage({
						current: 0,
						urls: [fileUrl]
					});
					return;
				}
				
				// PDF预览
				if (this.isPdfType(fileType)) {
					uni.setStorageSync('wjurl', fileUrl);
					uni.navigateTo({
						url: '/pages/pdf/pdf'
					});
					return;
				}
				
				// 视频预览
				if (this.isVideoType(fileType)) {
					uni.setStorageSync('videoUrl', fileUrl);
					uni.setStorageSync('videoName', file.name || '视频');
					uni.navigateTo({
						url: '/pages/new/zlgl/video-preview'
					});
					return;
				}
				
				// 其他文件类型（Word、Excel等）提示不支持在线预览
				uni.showToast({
					title: '该文件类型暂不支持在线预览',
					icon: 'none',
					duration: 2000
				});
			}
        }
}
</script>

<style scoped lang="scss">
	.u-subsection--button{
		height: 50px;
	}
	.main {
		padding-top: 87px; // 标题栏80px + 间距7px
		background-color: #F8F8F8;
		min-height: 100vh;
		.toptitle{
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			width: 100%;
			background-color: #0052D8;
			display: flex;
			height: 80px;
			justify-content: center;
			align-items: center;
			z-index: 200;
			.toptitle_left{
				padding-top: 20px;
				position: absolute;
				left: 10px;
				z-index: 1000;
			}
			.toptitle_title{
				color: #fff;
				font-size: 14px;
				padding-top: 20px;
			}
		}
		.title {
			padding: 10px;
			border-radius: 5px;
			margin-bottom: 10px;
			background-color: #fff;
		}

		.box {
			border-radius: 5px;
			margin-bottom: 10px;
			background-color: #fff;
			
			.tips{
				display: flex;
				align-items: center;
				margin-bottom: 10px;
				border-bottom: 1px solid #E9E9E9;
				padding: 15px 10px;
				
				.tip{
					width: 7px;
					height: 20px;
					background-color: #0052D8;
					margin-right: 10px;
				}
				.tiptitle{
					font-size: 17px;
				}
			}
			
			.box_item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 10px 20px;
				margin-bottom: 20px;
				// border-bottom: 1px dashed #ccc;
				.f1 {
					font-size: 16px;
				}
				.f2{
					color:#969696;
					font-size: 16px;
				}
				.f3{
					color: #38beff;
					border-bottom: 1px solid #38beff;
				}
			}
		}
		.box1{
			background-color: #fff;
			.tips{
				display: flex;
				align-items: center;
				margin-bottom: 10px;
				border-bottom: 1px solid #E9E9E9;
				padding: 15px 10px;
				
				.tip{
					width: 7px;
					height: 20px;
					background-color: #0052D8;
					margin-right: 10px;
				}
				.tiptitle{
					font-size: 17px;
				}
			}
			.box_item1{
				padding: 10px 20px;
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 10px;
				.left{
					display: flex;
					align-items: center;
					flex: 1;
					.left_image{
						margin-right: 15px;
						image{
							width: 40px;
							height: 40px;
						}
					}
					.l_title{
						flex: 1;
						.l_title_f1{
							font-size: 15px;
							margin-bottom: 5px;
							width: 50vw;
							overflow:hidden; //超出的文本隐藏
							text-overflow:ellipsis; //溢出用省略号显示
							white-space:nowrap; //溢出不换行
						}
						.l_title_f2{
							font-size: 13px;
							color: #969696;
						}
					}
				}
				.right{
					min-width: 80px;
					display: flex;
					justify-content: flex-end;
				}
				.download-progress{
					width: 100px;
					display: flex;
					flex-direction: column;
					align-items: center;
					.progress-text{
						font-size: 12px;
						color: #0052D8;
						margin-bottom: 4px;
						text-align: center;
					}
					.progress-bar{
						width: 100%;
						height: 6px;
						background-color: #e5e5e5;
						border-radius: 3px;
						overflow: hidden;
						.progress-fill{
							height: 100%;
							background-color: #0052D8;
							transition: width 0.3s ease;
							border-radius: 3px;
						}
					}
				}
			}
		}
	}
</style>
