<template>
	<view class="containers">
		<topWindow :isHome="false" @item-click="handleItemClick" @lanChange="changeLan"></topWindow>
		<goback></goback>
		<u-tabs :list="list" :current="current" lineColor="#00aeaa"
			:itemStyle="{width:'200px',height:'40px',backgraound:'#000'}" @click="tabChange" v-show="$isMobile"
			:activeStyle="activeStyle" :inactiveStyle="inactiveStyle"></u-tabs>
		<view class="ComponentsBody">
			<view class="productInformation" v-if="current == 0">
				<InformationModule v-if="informationData != null && Array.isArray(informationData.lampPath)"
					:informationData="informationData">
				</InformationModule>
			</view>
			<view class="inspectionInformation" v-else-if="current == 1">
				<InspectionModule v-if="inspectionData != null" :inspectionData="inspectionData"></InspectionModule>
			</view>
			<view class="attachmentInformation" v-else-if="current == 2">
				<AuxiliaryModule v-if="auxiliaryData != null" :auxiliaryData="auxiliaryData"></AuxiliaryModule>
			</view>
			<view class="repairReportBtnCss" @click="jumpService">
				<image src="/static/images/icon/repair.png" class="repairReportImageCss" mode="witFix"></u-image>
					<text class="repairReportTextCss">{{$t("hdk.Repair")}}</text>
			</view>
		</view>

	</view>
</template>

<script>
	import config from '@/common/config.js'
	import {
		getProductFind
	} from '@/api/scan'
	import topWindow from "@/pages/component/topWindow.vue"
	import goback from "@/pages/component/goback.vue"
	import InformationModule from '@/pages/component/InformationModule.vue'
	import InspectionModule from '@/pages/component/InspectionModule.vue'
	import AuxiliaryModule from '@/pages/component/AuxiliaryModule.vue'
	export default {
		components: {
			InformationModule,
			InspectionModule,
			AuxiliaryModule,
			topWindow,
			goback
		},
		data() {
			return {
				sn: "",
				productObject: null,
				informationData: null,
				inspectionData: null,
				auxiliaryData: null,
				repairInformation: null,
				// current: "productInformation",
				current: 0,
				list: [{
					name: this.$t('hdk.productInformation'),
				}, {
					name: this.$t('hdk.inspectionInformation'),
				}, {
					name: this.$t('hdk.attachmentInformation')
				}],
				inactiveStyle: {
					width: '120rpx',
					height: '38rpx',
					backgroundColor: 'rgba(255, 255, 255, 0)',
					boxSizing: 'border-box',
					fontFamily: "苹方 中等, 苹方, sans-serif",
					color: '#555555',
					textAlign: 'left',
					lineHeight: 'normal',
					fontSize: '28rpx'
				},
				activeStyle: {
					width: '128rpx',
					height: '43rpx',
					backgroundColor: 'rgba(255, 255, 255, 0)',
					boxSizing: 'border-box',
					fontFamily: "苹方 中等, 苹方, sans-serif",
					color: '#00aeaa',
					textAlign: 'left',
					lineHeight: 'normal',
					fontSize: '32rpx'
				},
			}
		},
		computed: {

		},
		onLoad(data) {
			console.log(data);
			if (data) {
				this.sn = data.sn;
			}
			this.initData()
		},
		methods: {
			changeLan(lang) {
				console.log("改变语言", lang);
				this.list = [];
				// 重新构建新的 list 数组
				this.list = [{
					name: this.$t('hdk.productInformation'),
				}, {
					name: this.$t('hdk.inspectionInformation'),
				}, {
					name: this.$t('hdk.attachmentInformation')
				}];
			},
			initData() {
				// uni.showLoading({title: '查询中...'})
				getProductFind(this.sn).then(res => {
					uni.hideLoading()
					if (res.code == 0) {
						console.log("sn查询结果", res)
						this.productObject = res.data
						this.initializationMethod()
					} else {
						uni.showToast({
							icon: 'error',
							title: this.$t('hdk.networkError'),
						})
					}
				})
			},
			initializationMethod() {
				//重新组装产品信息数据
				this.informationData = {
					lamp: this.productObject.productRespVO?.lamp || null,
					lampPath: this.productObject.productRespVO?.lampPath || [require('@/static/images/noPhoto.png')],
					sn: this.productObject.sn,
					productName: this.productObject.productRespVO?.productName || null,
					type: this.productObject.productRespVO?.type || null,
					productionTime: this.productObject.productionTime,
					productionUserName: this.productObject.productionUserName,
					productDatasheet: this.productObject.productRespVO?.productDatasheet || null,
					productDatasheetPath: this.productObject.productRespVO?.productDatasheetPath || null,
					productManual: this.productObject.productRespVO?.productManual || null,
					productManualPath: this.productObject.productRespVO?.productManualPath || null
				};
				console.log("产品信息", this.informationData);

				this.repairInformation = {
					sn: this.productObject.sn,
					productName: this.productObject.productRespVO?.productName || null,
					type: this.productObject.productRespVO?.type || null
				}

				//重新组装检验信息数据
				this.inspectionData = {
					softwareVersion: this.productObject.softwareVersion,
					hardwareVersion: this.productObject.hardwareVersion,
					checkTime: this.productObject.checkTime,
					type: this.productObject.productRespVO?.type || null,
					power: this.productObject.power,
					powerFactor: this.productObject.powerFactor,
					tightnessCheckFile: this.productObject.tightnessCheckFile,
					tightnessCheckFilePath: this.productObject.tightnessCheckFilePath,
					lightIntensityPhoto: [],
					lightIntensityFile: ''
				};
				console.log("检验信息", this.inspectionData);
				//重新组装附件信息数据
				this.auxiliaryData = this.productObject.attachmentRespVOList || [];


				// console.log("重新组装检验信息", this.inspectionData);
				if (this.productObject.attachmentRespVOList === null) {
					this.auxiliaryData = [];
				} else {
					this.auxiliaryData = this.productObject.attachmentRespVOList.map(obj => ({
						...obj,
						current: 0
					}));
				}
				console.log("附件信息", this.auxiliaryData);
				//产品数据转图片
				if (this.productObject && this.productObject.productRespVO) {
					const productRespVO = this.productObject.productRespVO;
					// console.log("灯具", productRespVO);
					// const modifiedManuals = this.generateDownloadUrls(productRespVO.lamp);
					// this.informationData.lamp = modifiedManuals;
					this.generateDownloadUrls(productRespVO.lampPath)
						.then(modifiedManuals => {
							// console.log("灯具==>", modifiedManuals);
							this.informationData.lampPath = modifiedManuals;
						})
						.catch(error => {
							console.error(error);
						});
				}
				//光强数据转图片
				if (this.productObject && this.productObject.lightIntensityPath) {
					if (this.productObject.lightIntensityPath) {
						this.generateDownloadUrls(this.productObject.lightIntensityPath)
							.then(modifiedManuals => {
								// console.log("光强==>", modifiedManuals);
								this.inspectionData.lightIntensityPhoto = modifiedManuals.filter(url => this
									.isPicture(
										url));
								this.inspectionData.lightIntensityFile = modifiedManuals.filter(filename => !this
									.isPicture(filename) && filename.includes('.'));
								// 在这里可以访问已更新的inspectionData.lightIntensityPhoto和inspectionData.lightIntensityFile的值
							})
							.catch(error => {
								console.error(error);
							});
					}
				}
				//附件信息转图片
				if (this.auxiliaryData) {
					this.auxiliaryData.forEach(attachment => {
						if (attachment.productPicturePath) {
							this.generateDownloadUrls(attachment.productPicturePath)
								.then(modifiedPictures => {
									// console.log("附件图片==>", modifiedPictures);
									attachment.productPicturePath = modifiedPictures;
								})
								.catch(error => {
									console.error(error);
								});
						}
					});
				}

			},
			jumpService() {
				console.log(this.repairInformation);
				uni.navigateTo({
					url: "/pages/product/repairReport?repairpObject=" + encodeURIComponent(JSON.stringify(
						this.repairInformation)),
				})
			},
			generateDownloadUrls(filenames) {
				// console.log("filenames", filenames)
				if (!filenames || filenames.length === 0) {
					// 如果 filenames 为空或者null，则执行相应的操作
					return Promise.resolve([require('@/static/images/noPhoto.png')])
				}
				const modifiedFilenames = filenames.replace(/;+$/, '');
				const modifiedUrls = modifiedFilenames.split(";").map(filename => {
					const trimmedFilename = filename.trim();
					if (trimmedFilename.endsWith('.png') || trimmedFilename.endsWith('.jpg')) {
						// const encodedFilename = Buffer.from(trimmedFilename, 'utf-8').toString('base64');
						const url = config.fileUrl + `/${trimmedFilename}`;
						// console.log(url);
						return this.checkUrlValidity(url)
						// .then(res => {
						// 	return res == null ? Promise.resolve(require('@/static/images/noPhoto.png')):res
						// })
						.catch(error => {
							// console.error(error);
							// console.log("请求失败", trimmedFilename)
							return Promise.resolve(require('@/static/images/noPhoto.png'));
						});
					} else if (trimmedFilename.includes('.')) {
						return Promise.resolve(trimmedFilename);
					} else {
						return Promise.resolve(require('@/static/images/noPhoto.png'));
					}
				});

				return Promise.all(modifiedUrls).then(results => {
					console.log(results);
					const validUrls = results.filter(url => url !== null);
					// console.log(validUrls);
					if (validUrls.length > 0) {
						// console.log("有效地址",validUrls);
						return validUrls;
					} else {
						return [require('@/static/images/noPhoto.png')];
					}
				});
			},
			checkUrlValidity(url) {
				return new Promise((resolve, reject) => {
					uni.request({
						url,
						method: 'HEAD',
						success(res) {
							// console.log("检验地址",res);
							if (res.statusCode >= 200 && res.statusCode < 400) {
								resolve(url); // URL有效
							} else {
								// console.log("地址无效");
								resolve(null); // URL无效
							}
						},
						fail(err) {
							reject(err); // 请求失败
						}
					});
				});
			},
			isPicture(str) {
				// 正则表达式判断是否为网址类型的字符串
				const pictureRegex = /\.(jpg|jpeg|png|gif)$/i;
				return pictureRegex.test(str);
			},
			tabChange(item) {
				this.current = item.index
				if (this.current == 0) {
					// console.log(this.informationData);
				} else if (this.current == 1) {
					// console.log(this.inspectionData);
				} else {
					// console.log(this.auxiliaryData);
				}
			},
			handleItemClick(item) {
				this.current = item;
				console.log('点击的菜单项:', item);
				// 在此处处理被点击的菜单项
			}
		}
	}
</script>

<style lang="scss" scoped>
	.containers {
		width: 100%;
		height: 100%;
		background: #F9FAF9;
	}

	.ComponentsBody {
		margin-top: 5px;
		// width:100%;
		// display: flex;
		// justify-content: center;
		// align-items: center;
	}

	// .productInformation{
	// 	width: 100%;
	// }

	// .inspectionInformation{
	// 	width: 100%;
	// }

	// .attachmentInformation{
	// 	width: 100%;
	// }

	//移动端样式
	@media screen and (max-width: 767px) {
		.repairReportBtnCss {
			width: 100px;
			height: 100px;
			border-radius: 100px;
			position: fixed;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			right: 0;
			bottom: 100px;
			// background-color: #00aeaa;
		}



		// .u-image__image{
		// 	width: 100px !important;
		// 	height: 100px !important;
		// }

		.repairReportImageCss {
			width: 100px !important;
			height: 100px !important;
		}

		.repairReportTextCss {
			position: absolute;
			bottom: 30px;
			color: #fff;
			font-size: 10px;
		}
	}



	// //PC端样式
	@media screen and (min-width: 768px) {
		.repairReportBtnCss {
			width: 200px;
			height: 200px;
			position: fixed;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			right: 20px;
			bottom: 100px;
			// background-color: #00aeaa;
		}

		// .u-image__image{
		// 	width: 200px !important;
		// }


		.repairReportImageCss {
			width: 200px !important;
			height: 200px !important;
		}

		.repairReportTextCss {
			position: absolute;
			bottom: 60px;
			color: #fff;
		}

	}
</style>