<template>
	<view class="addIssue">
		<view class="fixedheader">
			<headers :showBack="true">
				<view class="headerName">
					查看{{defaultType == 2 ? '个人' : '项目'}}施工日志
				</view>
			</headers>
		</view>
		<view class="content" :style="{paddingTop: mobileTopHeight + 44 + 'px'}">
			<view class="content_main" :class="{'pb-60': defaultType == 2}">
				<view class="main1_box">
					<view>
						风力:{{ocrBuildLogInfo.weatherJson ? ocrBuildLogInfo.weatherJson.win_speed : '--'}}
					</view>
					<view>
						气温:{{ocrBuildLogInfo.weatherJson ?ocrBuildLogInfo.weatherJson.tem_day : '--'}}
					</view>
					<view>
						天气: {{ocrBuildLogInfo.weatherJson ? ocrBuildLogInfo.weatherJson.wea: '--'}}
					</view>
				</view>
				<view class="main2_box">
					<view class="box-header">
						<view>施工情况</view>
						<view></view>
					</view>
					<view class="box-item">
						<view>施工区域</view>
						<view>{{ocrBuildLogInfo.constructionAreaNames}}</view>
					</view>
					<view class="box-item">
						<view>施工单位</view>
						<view>{{ocrBuildLogInfo.constructionUnitNames}}</view>
					</view>
					<view class="box-item">
						<view>施工人员</view>
						<view>{{ocrBuildLogInfo.constructionWorkerNames}}</view>
					</view>
					<view class="box-content">
						<view>施工任务</view>
						<view v-if="ocrBuildLogInfo.lineHeightFlag1"
							@click.stop="ocrBuildLogInfo.expandMoreShow1 = !ocrBuildLogInfo.expandMoreShow1">
							{{ocrBuildLogInfo.expandMoreShow1 ? '收起更多': '展开更多'}}
						</view>
					</view>
					<view
						:class="{'webkit-clamp_2': ocrBuildLogInfo.lineHeightFlag1 && !ocrBuildLogInfo.expandMoreShow1}"
						id="box-content_detail1" class="box-content_detail">
						{{ocrBuildLogInfo.constructionTask}}
					</view>
					<view class="box-content">
						<view>出勤情况</view>
						<view v-if="ocrBuildLogInfo.lineHeightFlag2"
							@click.stop="ocrBuildLogInfo.expandMoreShow2 = !ocrBuildLogInfo.expandMoreShow2">
							{{ocrBuildLogInfo.expandMoreShow2 ? '收起更多': '展开更多'}}
						</view>
					</view>
					<view
						:class="{'webkit-clamp_2': ocrBuildLogInfo.lineHeightFlag2 && !ocrBuildLogInfo.expandMoreShow2}"
						id="box-content_detail2" class="box-content_detail">
						{{ocrBuildLogInfo.attendance}}
					</view>
					<view class="box-content">
						<view>施工机械</view>
						<view v-if="ocrBuildLogInfo.lineHeightFlag3"
							@click.stop="ocrBuildLogInfo.expandMoreShow3 = !ocrBuildLogInfo.expandMoreShow3">
							{{ocrBuildLogInfo.expandMoreShow3 ? '收起更多': '展开更多'}}
						</view>
					</view>
					<view
						:class="{'webkit-clamp_2': ocrBuildLogInfo.lineHeightFlag3 && !ocrBuildLogInfo.expandMoreShow3}"
						id="box-content_detail3" class="box-content_detail">
						{{ocrBuildLogInfo.constructionMachinery}}
					</view>
				</view>
				<view class="main3_box">
					<view class="box-header">
						设计变更材料
					</view>
					<view class="box-item" v-for="item in ocrBuildLogInfo.designChangeMaterial" :key="item.url">
						<view class="box-item_left">
							{{item.name}}
						</view>
						<view class="box-item_right">
							<view>{{item.fileSizeMb}}kb</view>
							<view @click="handlePreview(item.url)">
								<u-icon name="eye" color="#5382F6" size="32"></u-icon>
							</view>
							<view @click="downloadFn(item)">
								<u-icon name="download" color="#5382F6" size="32"></u-icon>
							</view>
						</view>
					</view>
				</view>
				<view class="main3_box">
					<view class="box-header">
						安全交底材料
					</view>
					<view class="box-item" v-for="item in ocrBuildLogInfo.safetyBriefingMaterial" :key="item.url">
						<view class="box-item_left">
							{{item.name}}
						</view>
						<view class="box-item_right">
							<view>{{item.fileSizeMb}}kb</view>
							<view @click="handlePreview(item.url)">
								<u-icon name="eye" color="#5382F6" size="32"></u-icon>
							</view>
							<view @click="downloadFn(item)">
								<u-icon name="download" color="#5382F6" size="32"></u-icon>
							</view>
						</view>
					</view>
				</view>
				<view class="main3_box">
					<view class="box-header">
						技术交底材料
					</view>
					<view class="box-item" v-for="item in ocrBuildLogInfo.technicalBriefingMaterial" :key="item.url">
						<view class="box-item_left">
							{{item.name}}
						</view>
						<view class="box-item_right">
							<view>{{item.fileSizeMb}}kb</view>
							<view @click="handlePreview(item.url)">
								<u-icon name="eye" color="#5382F6" size="32"></u-icon>
							</view>
							<view @click="downloadFn(item)">
								<u-icon name="download" color="#5382F6" size="32"></u-icon>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="confrim-btn" v-if="defaultType == 2">
				<view @click="onDelete">删除</view>
				<view @click="createProjectLog">编辑</view>
			</view>
		</view>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import {
		isJSON
	} from "@/utils/tool.js"
	export default {
		data() {
			return {
				mobileTopHeight: 0,
				projectDetail: {},
				riskListPointId: "",
				ocrBuildLogInfo: {
					designChangeMaterial: [],
					safetyBriefingMaterial: [],
					technicalBriefingMaterial: [],
				},
				defaultType: 1,
			}
		},
		onLoad(opts) {
			this.projectDetail = JSON.parse(uni.getStorageSync('projectDetail'));
			this.riskListPointId = opts.id;
			this.defaultType = opts.type;
		},
		onShow(){
			this.getRiskListPointQueryByIdFn();
		},
		mounted() {
			var that = this
			uni.getSystemInfo({
				success(res) {
					that.mobileTopHeight = res.statusBarHeight ? res.statusBarHeight : 0;
					uni.setStorageSync('systemInfo', res)
					console.log(res)
				}
			})
		},
		methods: {
			createProjectLog(){
				uni.navigateTo({
					url: `./addBuildersDiary?date=${this.ocrBuildLogInfo.date}&id=${this.riskListPointId}`
				})
			},
			// 删除
			onDelete() {
				let that = this;
				let data = {
					id: this.riskListPointId
				};

				uni.showModal({
					title: '提示',
					content: '确定删除该作业吗?',
					success: function(res) {
						if (res.confirm) {
							that.sendRequest({
								url: 'xmgl/ocrBuildLog/delete',
								method: 'POST',
								data: data,
								success: res => {
									if (res.code == 200) {
										that.showToast('删除成功！', 'success');
										setTimeout(() => {
											uni.$emit('updateData');
											that.onNavigateBack();
										}, 800)
									}
								}
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});

			},
			// 返回上一级
			onNavigateBack() {
				uni.navigateBack({
					delta: 0
				})
			},
			showToast(title, type) {
				this.$refs.uToast.show({
					title: title,
					type: type,
				})
			},
			async fontSizeMb(url) {
				const isUrl = url.includes("http://") ? url : this.url_config + 'image/' + url;
				const response = await fetch(isUrl);
				const blob = await response.blob();
				const fileSize = blob.size; // 文件大小，单位为字节
				return (fileSize / 1024 / 1024).toFixed(2)
			},
			// 通过id查询管控清单信息
			getRiskListPointQueryByIdFn() {
				let that = this;
				let data = {
					projectSn: this.projectDetail.projectSn,
					id: this.riskListPointId,
				};
				this.sendRequest({
					url: 'xmgl/ocrBuildLog/queryById',
					method: 'GET',
					data: data,
					success: res => {
						if (res.code == 200) {
							that.ocrBuildLogInfo = {
								...res.result,
								constructionAreaIds: res.result.constructionAreaIds ?
									res.result.constructionAreaIds.split(",") : [],
								constructionUnitIds: res.result.constructionUnitIds ?
									res.result.constructionUnitIds.split(",") : [],
								constructionWorkerIds: res.result.constructionWorkerIds ?
									res.result.constructionWorkerIds.split(",") : [],
								supervisionUnitIds: res.result.supervisionUnitIds ?
									res.result.supervisionUnitIds.split(",") : [],
								supervisionPersonnelIds: res.result.supervisionPersonnelIds ?
									res.result.supervisionPersonnelIds.split(",") : [],
								designChangeMaterial: isJSON(res.result.designChangeMaterial) ?
									JSON.parse(res.result.designChangeMaterial) : [],
								safetyBriefingMaterial: isJSON(res.result.safetyBriefingMaterial) ?
									JSON.parse(res.result.safetyBriefingMaterial) : [],
								technicalBriefingMaterial: isJSON(res.result.technicalBriefingMaterial) ?
									JSON.parse(res.result.technicalBriefingMaterial) : [],
								weatherJson: isJSON(res.result.weatherJson) ?
									JSON.parse(res.result.weatherJson) : {},
							};
							this.$set(that.ocrBuildLogInfo, 'expandMoreShow1', false);
							this.$set(that.ocrBuildLogInfo, 'expandMoreShow2', false);
							this.$set(that.ocrBuildLogInfo, 'expandMoreShow3', false);
							this.$set(that.ocrBuildLogInfo, 'lineHeightFlag1', false);
							this.$set(that.ocrBuildLogInfo, 'lineHeightFlag2', false);
							this.$set(that.ocrBuildLogInfo, 'lineHeightFlag3', false);
							if (that.ocrBuildLogInfo.designChangeMaterial.length > 0) {
								that.ocrBuildLogInfo.designChangeMaterial.map(async file => {
									const fileSizeMb = await this.fontSizeMb(file.url);
									this.$set(file, 'fileSizeMb', fileSizeMb);
								})
								console.log(11122, that.ocrBuildLogInfo.designChangeMaterial)
							}
							if (that.ocrBuildLogInfo.safetyBriefingMaterial.length > 0) {
								that.ocrBuildLogInfo.safetyBriefingMaterial.forEach(async file => {
									const fileSizeMb = await this.fontSizeMb(file.url);
									this.$set(file, 'fileSizeMb', fileSizeMb);
								})
							}
							if (that.ocrBuildLogInfo.technicalBriefingMaterial.length > 0) {
								that.ocrBuildLogInfo.technicalBriefingMaterial.forEach(async file => {
									const fileSizeMb = await this.fontSizeMb(file.url);
									this.$set(file, 'fileSizeMb', fileSizeMb);
								})
							}
							// 等待文件大小计算完成后再获取行数
							this.$nextTick(() => {
								// 增加延迟时间，确保DOM完全渲染
								this.getLineCount();
							})
						}
					}
				})
			},
			getLineCount() {
				const that = this;
				// 使用 Promise 确保所有查询完成
				const promises = [];
				
				for (var i = 1; i <= 3; i++) {
					const promise = new Promise((resolve) => {
						// 增加重试机制
						const queryElement = (i) => {
							uni.createSelectorQuery().in(this).select(`#box-content_detail${i}`).boundingClientRect(rect => {
								if (rect && rect.height > 0) {
									// 计算行数：每行高度约20rpx
									let lineHeight = Math.ceil(rect.height / uni.upx2px(20));
									console.log(`元素${i}高度:`, rect.height, '行数:', lineHeight);
									if (lineHeight > 2) {
										that.ocrBuildLogInfo[`lineHeightFlag${i}`] = true;
										console.log(that.ocrBuildLogInfo[`lineHeightFlag${i}`],that.ocrBuildLogInfo)
									}
									resolve();
								} else {
									// 如果元素未找到或高度为0，延迟重试
									console.log(`元素${i}未找到或高度为0，重试中...`);
									setTimeout(() => {
										queryElement(i);
									}, 200);
								}
							}).exec();
						};
						
						queryElement(i);
					});
					
					promises.push(promise);
				}
				
				// 等待所有查询完成
				Promise.all(promises).then(() => {
					console.log('所有行数计算完成');
				});
			},
			downloadFn(item) {
				const isUrl = item.url.includes("http://") ? item.url : this.url_config + 'image/' + item.url;
				var that = this
				uni.showModal({
					title: '提示',
					content: item.name,
					confirmText: '下载',
					success: function(res) {
						if (res.confirm) {
							uni.downloadFile({
								url: isUrl, //仅为示例，并非真实的资源
								success: (res) => {
									if (res.statusCode === 200) {
										// uni.showToast({
										// 	title:'下载成功'
										// })
										var filePath = res.tempFilePath;
										if (!filePath) return
										uni.openDocument({
											filePath: filePath,
											success: function(res) {
												console.log(res);
												console.log('打开文档成功');
												uni.showToast({
													title: '打开文档成功'
												})
											}
										});
									} else {
										uni.showToast({
											title: '下载失败'
										})
									}
								}
							});
						}
					}
				});
			},
			//预览文件
			handlePreview(url) {
				let type = url.split('.')[1];
				const isUrl = url.includes("http://") ? url : this.url_config + 'image/' + url;
				if (type == 'doc' || type == 'xls' || type == 'ppt' || type == 'pdf' || type == 'docx' || type == 'xlsx' ||
					type ==
					'pptx') {
					uni.openDocument({
						filePath: this.url_config + 'image/' + url,
					})
				} else {
					let fileList = [];
					fileList = [isUrl];
					uni.previewImage({
						current: 0,
						urls: fileList
					})
				}

			},
		},
	}
</script>

<style scoped lang="scss">
	.content {
		.pb-60 {
			padding-bottom: 60px;
		}

		.content_main {
			position: relative;

			.main3_box {
				padding: 26rpx 22rpx;
				background-color: white;
				margin-top: 26rpx;

				.box-item {
					padding: 20rpx 0;
					display: flex;
					justify-content: space-between;
					border-bottom: 2rpx solid #F2F2F2;

					.box-item_right {
						width: 40%;
						display: flex;
						justify-content: flex-end;
						align-items: center;

						>view:first-child {
							font-size: 24rpx;
							color: #B3B3B3;
						}

						>view:nth-child(2) {
							margin-left: 72rpx;
						}

						>view:nth-child(3) {
							margin-left: 62rpx;
						}
					}

					.box-item_left {
						font-weight: 500;
						font-size: 28rpx;
						color: #3190F3;
						width: 60%;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 1;
						/* 限制为两行 */
						overflow: hidden;
					}
				}

				.box-header {
					font-weight: 500;
					font-size: 30rpx;
					color: #1A1A1A;
					margin-bottom: 16rpx;
				}
			}

			.main1_box {
				background-color: white;
				font-size: 28rpx;
				color: #808080;
				padding: 0 26rpx;
				display: flex;
				justify-content: space-between;
			}

			.main2_box {
				padding: 26rpx 22rpx;
				background-color: white;
				position: relative;

				.box-content_detail {
					font-size: 28rpx;
					color: #4D4D4D;
					margin-top: 4rpx;
				}

				.webkit-clamp_2 {
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					/* 限制为两行 */
					overflow: hidden;
				}

				.box-content {
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-top: 26rpx;

					>view:last-child {
						font-size: 24rpx;
						color: #4D8EEC;
					}

					>view:first-child {
						font-size: 28rpx;
						color: #808080;
					}
				}

				.box-item {
					display: flex;
					align-items: center;
					margin-top: 26rpx;
					font-size: 28rpx;

					>view:first-child {
						width: 168rpx;
						margin-right: 26rpx;
						color: #808080;
					}

					>view:last-child {
						flex: 1;
						color: #4D4D4D;
						display: -webkit-box;
						-webkit-box-orient: vertical;
						-webkit-line-clamp: 1;
						/* 限制为两行 */
						overflow: hidden;
					}
				}

				.box-header {
					display: flex;
					align-items: center;
					justify-content: space-between;

					>view:first-child {
						font-weight: 500;
						font-size: 30rpx;
						color: #1A1A1A;
					}

					>view:last-child {
						font-weight: 500;
						font-size: 24rpx;
						color: #4D8EEC;
					}
				}
			}
		}

		.confrim-btn {
			width: 100%;
			padding: 18rpx 26rpx;
			background-color: #FFFFFF;
			box-shadow: 0rpx -8rpx 8rpx 0rpx rgba(0, 0, 0, 0.05);
			display: flex;
			position: fixed;
			bottom: 0;
			z-index: 1;

			>view {
				width: 50%;
				height: 76rpx;
				font-weight: 500;
				font-size: 28rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			>view:first-child {
				background: rgba(255, 0, 0, 0.1);
				border-radius: 6rpx 0rpx 0rpx 6rpx;
				color: #FF0000;
			}

			>view:last-child {
				background-color: #5181F6;
				border-radius: 0rpx 6rpx 6rpx 0rpx;
				color: #FFFFFF;
			}
		}

	}

	.addIssue {
		min-height: 100vh;
		background-color: #F2F3F7;
	}

	.fixedheader {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		z-index: 999;

		/deep/ .headerBox {
			border-bottom: none;
		}

		.headerName {
			z-index: 1;
		}
	}
</style>