<template>
	<!-- 井道巡检操作 -->
	<view class="container">
		<uni-nav-bar :fixed="true" background-color="rgba(214, 240, 255, 0.0)" status-bar rightWidth="300">
			<block slot="left">
				<view class="uni-nav-bar-text" @click="back">
					<text class="iconfont icon-Arrow-Left"></text>
				</view>
			</block>
		</uni-nav-bar>
		<view class="profile-section">
			<view class="profile-box">
				<view class="profile-left">
					<view class="avatar">
						<image src="@/static/img/add-img/defaultAvatar.png" mode="aspectFit"></image>
					</view>
					<view class="info">
						<view class="username">井道巡检</view>
						<view class="number">巡检编号：<text class="value">{{ location }}{{floor}}</text></view>
					</view>
				</view>
			</view>
		</view>

		<!-- 模块1：巡检井道 -->
		<!-- 	<view class="module">
			<view class="title-bar">
				<view class="blue-line"></view>
				<text class="title">巡检井道</text>
				<text class="location">{{ location }}{{floor}}</text>
				<button class="submit-btn" :class="{ active: isSubmitEnabled }" :disabled="!isSubmitEnabled" @click="submit">
					完成当前机房全部巡检
				</button>
			</view>
		</view> -->

		<!-- 模块2：巡检说明 -->
		<!-- 		<view class="module">
			<view class="title-bar">
				<view class="blue-line"></view>
				<text class="title">巡检说明</text>
			</view>
			<text class="description">{{ randomDescription }}</text>
		</view> -->

		<!-- 模块3：Tab 操作区域 -->
		<view class="module">
			<view class="tab-buttons">
				<view v-for="(tab, index) in tabs" :key="index" :class="['tab-item', { active: activeTab === index }]"
					@click="switchTab(index)">
					<image :src="tab.icon" class="tab-icon"></image>
					<text class="tab-text">{{ tab.label }}</text>
					<view v-if="activeTab === index" class="underline"></view>
				</view>
			</view>
			<view class="tip">
				<image class="tip-icon" src="@/static/img/add-img/defaultAvatar.png" mode="aspectFit"></image>请点击“需巡检井道”执行巡检
			</view>
			<view class="tab-content">
				<!-- 操作区域 -->
				<view class="form-item"><text class="form-label">巡检项</text>
					<view class="label">
						<text>{{ tabs[activeTab].label }}</text>
					</view>
				</view>
				<view class="form-item">
					<text class="form-label"><text class="required">*</text>巡检结论</text>
					<view class="switch-container">
						<view :class="['status-btn', { active: inspectionResult === 0 }]" @click="setInspectionResult(0)">
							正常
						</view>
						<view :class="['status-btn', { active: inspectionResult === 1 }]" @click="setInspectionResult(1)">
							异常
						</view>
					</view>
				</view>

				<view class="form-item">
					<text class="form-label"><text class="required">*</text>情况摘要</text>
					<input class="input-box" v-model="list[activeTab]&&list[activeTab].conclusion" placeholder="请输入情况摘要" />
				</view>
				<view class="form-item">
					<text class="form-label">现场照片</text>
					<text class="photo-limit">（最多5张）</text>
					<view class="photo-container">
						<view v-for="(photo, index) in list[activeTab]&&list[activeTab].photos" :key="index" class="photo-item">
							<image :src="photo" class="photo"></image>
							<text class="delete-photo" @click="deletePhoto(index)">×</text>
						</view>
					</view>
					<button @click="takePhoto" class="photo-btn">
						拍照
					</button>
				</view>
			</view>
		</view>

		<!-- 模块4：提交模块 -->
		<!-- <view class="module submit-module">
			<button class="action-btn" @click="saveDraft">暂存</button>
			<button class="action-btn complete-btn" @click="complete">
				完成
			</button>
		</view> -->
		<view class="module submit-module">
			<button class="action-btn" @click="saveDraft">暂存</button>
			<button v-if="isSubmitEnabled" class="action-btn" :class="{ active: isSubmitEnabled }" @click="submit">
				完成巡检
			</button>
			<button v-else class="action-btn complete-btn" @click="closePopup">下一项
			</button>
		</view>
		<!-- 使用 uni-popup 组件 完成弹窗 -->
		<uni-popup ref="popup" type="center">
			<view class="popup-content">
				<!-- 关闭按钮 -->
				<view class="close-icon" @click="closePopup">×</view>

				<!-- 成功图标 -->
				<view class="icon-success">✔️</view>

				<!-- 保存成功的文字 -->
				<view class="success-text">保存成功</view>

				<!-- 下一项按钮 -->
				<view class="next-button" @click="closePopup">下一项</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		pad_2_1_inspection_items,
		pad_2_1_inspection_position,
		pad_2_1_floor
	} from "@/utils/dict.js"; //巡检位置，A座到F座 楼层2楼4楼到26楼
	import {
		addLog,
		getLogContent,
		LOG_TYPE_ENUM,
		writeDarf,
		writeInspectionData,
	} from "@/utils/IoReadingAndWriting.js";

	import {
		getInspectionDetails,
		getDarft
	} from "@/request/index.js";
	import moment from "moment";

	export default {
		data() {
			return {
				location: "A座", // 从上一个页面带过来的位置
				floor: "2楼", // 从上一个页面带过来的位置
				isSubmitEnabled: false, // 提交按钮是否可点击
				uid: "",
				randomDescription: "这是一段随机说明文字。", // 随机说明文字
				tabs: [{
						label: "门禁",
						icon: "../../static/img/add-img/home1.png"
					},
					{
						label: "卫生",
						icon: "../../static/img/add-img/home1.png"
					},
					{
						label: "设备告警",
						icon: "../../static/img/add-img/home1.png"
					},
				],
				activeTab: 0, // 当前选中的 Tab
				inspectionResult: 0, // Switch 值（0: 正常, 1: 异常）
				conclusion: "", // 情况摘要
				photos: [], // 现场照片
				historyData: null, // 历史数据
				firstSubmitTime: null, // 首次提交时间
				detailsInfo: {}, // 详情
				baseInfo: {}, // 基础信息
				list: [], //巡检信息
				inspectionCode:"",//编号
			};
		},
		computed: {
			userInfo() {
				return this.$store.state.now_user || {};
			},
			// isOperationPermissions() {
			// 	// 是否有操作权限
			// 	const {
			// 		uid,
			// 		createByName
			// 	} = this.detailsInfo;
			// 	return !uid || (uid && createByName == this.userInfo.user);
			// },
		},
		onLoad(options) {
			this.coverlist();
			this.isDisable = options.isDisable == 1 ? true : false;
			this.uid = options.uid
			this.inspectionCode = options.inspectionCode
			console.log("options", options)

			if (options.uid) {
				this.getDetails(options.uid);
			} else if (options.isDarf) {
				// 获取草稿数据
				uni.showLoading();
				getDarft()
					.then((res) => {
						console.log("res", res)
						const darf_data = res || {};
						this.baseInfo = darf_data.originData.baseInfo;
						this.list = darf_data.originData.tempForm;
						this.detailsInfo = darf_data;
						uni.hideLoading();

						this.init();
					})
					.catch((error) => {
						uni.showToast({
							title: error.msg,

							icon: "none",
							duration: 1000,
						});
						uni.hideLoading();
					});
			}
		},
		watch: {},
		mounted() {
			this.init();
		},
		methods: {
			// 初始化
			init() {
				return new Promise((resolve, reject) => {
					// 判断是否有回显数据
					if (!this.uid) {
						// 基础数据
						this.baseInfo = {
							inspectionType: "2",
							inspectionCode: `JFXJ${moment().format("yyyyMMDDHHmmss")}${(Math.floor(Math.random() * 900) + 100)}`,
							recordName: `${moment().format("yyyyMMDD")}-井道巡检`,
							inspectionTime: moment().format("yyyy-MM-DD HH:mm"),
							inspectionBy: this.$store.state.now_user.user,
							inspectionById: this.$store.state.now_user.userId,
							createByName: this.$store.state.now_user.user,
							isException: "", // 是否有异常
							position: this.location, // 位置
							floor: this.floor, // 楼层
							isSubmit: "", // 0 是草稿态；  1 是正式提交
							isSign: "", // 是否签字
							conclusion: "", //摘要
							creatTime: `${new Date().getTime()}`,
							items: [],
						};
					}
					console.log(2222, this.baseInfo, this.list, this.detailsInfo)
					resolve();
				});
			},
			// 回显数据
			getDetails(uid) {
				uni.showLoading();
				getInspectionDetails(uid)
					.then((res) => {
						const detailsInfo = res;
						console.log("getDetails", res)
						this.baseInfo = detailsInfo.originData.baseInfo;
						this.list = detailsInfo.originData.tempForm;
						this.detailsInfo = detailsInfo;

						this.isDisable = this.isDisable || detailsInfo.synchronization == 1; // 是否禁用 1:已同步数据 0: 未同步数据
						uni.hideLoading();
						this.isSubmitEnabled = this.isAllTabValid()
					})
					.catch((error) => {
						uni.showToast({
							title: error.msg,
							icon: "none",
							duration: 1000,
						});
						uni.hideLoading();
					});
			},
			// 加载历史数据
			loadHistoryData() {
				const history = uni.getStorageSync("inspectionHistory");
				console.log("history", history)
				if (history && Date.now() - history.firstSubmitTime < 168 * 60 * 60 * 1000) {
					this.historyData = history;
					this.location = history.location;
					this.randomDescription = history.randomDescription;
					this.list = history.tabData;
					this.activeTab = 0; // 默认切换到第一个 Tab
					this.updateCurrentTabData();
				}
			},
			// 数据结构重组
			coverlist() {
				// 获取井道巡检的三个检查项固定数据再进行处理
				const data = pad_2_1_inspection_items.rows.map((item) => {
					return {
						//   ...item,
						dictLabel: item.dictLabel,
						dictValue: item.dictValue,
						conclusion: "", // 情况摘要
						// roomType,
						inspectionResult: 0, // 异常结论
						itemCode: item.dictValue, // 检查项  如:门禁
						measuredData: this.floor, // 逗号分隔字符串
						photos: [], // 照片
						postionList: [{
							...pad_2_1_floor.rows[0],
							isActive: false,
						}]
					};
				});

				this.list = data;
			},

			// 更新当前 Tab 数据
			updateCurrentTabData() {
				const currentTabData = this.list[this.activeTab];
				this.inspectionResult = currentTabData.inspectionResult;
				this.conclusion = currentTabData.conclusion;
				this.photos = currentTabData.photos;
			},
			// 拍照
			takePhoto() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						if (this.photos.length < 5) {
							this.photos.push(res.tempFilePaths[0]);
							this.list[this.activeTab].photos = this.photos;
						} else {
							uni.showToast({
								title: "最多只能上传5张照片",
								icon: "none",
							});
						}
					},
				});
			},
			// 删除照片
			deletePhoto(index) {
				this.photos.splice(index, 1);
				this.list[this.activeTab].photos = this.photos;
			}, // 处理提交数据
			getParams() {
				const baseInfo = this.baseInfo;
				const tempForm = this.list;
				console.log("this.list", this.list)

				const data = {
					...baseInfo,
					isSubmit: 1, //是否提交
					items: [],
					synchronization: 0, // 是否同步过
					submitTime: moment().format("yyyy-MM-DD"), // 记录提交时间
					submitMonth: moment().format("yyyy-MM"), // 记录提交月份
					originData: {
						baseInfo,
						tempForm,
					},
				};
				console.log("getParams,data", data)
				return data;
			},
			// 检查所有Tab 的必填项是否填写完整
			isAllTabValid() {
				const data = this.list
				// 校验函数
				const validateData = (data) => {
					return data.every(
						(item) =>
						item.inspectionResult !== null && item.conclusion.trim() !== ""
					);
				};
				// 调用校验函数
				const isValid = validateData(data);
				console.log(141, isValid)
				return isValid
			},
			// 检查当前 Tab 的必填项是否填写完整
			isCurrentTabValid() {
				const currentTabData = this.list[this.activeTab];
				console.log("currentTabData", currentTabData)
				return (
					currentTabData.inspectionResult !== null && // 巡检结论必填
					currentTabData.conclusion.trim() !== "" // 情况摘要必填
					// 现场照片为非必填项，不做校验
				);
			},
			// 暂存
			saveDraft(isSave = true) {
				return new Promise((resolve, reject) => {

					if (isSave) {
						// 写入草稿文件   更新  store 草稿内容
						const params = this.getParams();
						console.log("params", params)
						params.isSubmit = 0;

						this.$store.commit("SET_DARF_DATA", params); // 缓存[巡检信息]
						writeDarf(params).then((res) => {
							console.log("写入草稿文件成功");
							uni.showToast({
								icon: "success",
								title: "保存草稿成功",
							});
						});

						// 新增日志信息
						const logContent = getLogContent(
							LOG_TYPE_ENUM.darf,
							`${params.recordName}(${params.inspectionCode})`,
							"巡检模块"
						);
						const log_list = this.$store.state.log_list;
						logContent.inspectionType = params.inspectionType;
						this.$logApi.addlog(logContent)
						log_list.push(logContent);
						this.$store.commit("SET_LOG_LIST", log_list);
						addLog(log_list).then((res) => {
							console.log("日志文件写入成功");
						});
					}
					resolve();
				});
			},
			// 完成
			complete() {
				this.isSubmitEnabled = this.isAllTabValid()
				if (this.isCurrentTabValid()) {
					// 暂存All
					this.saveDraft().then(() => {
						if (this.isSubmitEnabled) {
							this.openPopup()
						}
					})
				} else {
					uni.showToast({
						title: "请填写完整必填项",
						icon: "none",
					});
				}

			},

			// 提交
			submit() {
				// 校验是否通过
				if (this.isCurrentTabValid()) {
					if (!this.firstSubmitTime) {
						this.firstSubmitTime = Date.now();
						this.$st
					}
					const params = this.getParams(); //数据获取
					const all_data = ore.state.all_data; //获取全部数据
					params.isSubmit = 1; //修改提交状态
					let logContent = "";
					if (this.uid) {
						const index = all_data.findIndex((element) => element.uid == this.uid);
						params.uid = this.uid;

						all_data[index] = params;
						logContent = getLogContent(
							LOG_TYPE_ENUM.edit,
							`${params.recordName}(${params.inspectionCode})`,
							"巡检模块"
						);

					} {
						params.uid = new Date().getTime(); // 唯一标识 pad 端使用
						all_data.push(params);
						logContent = getLogContent(
							LOG_TYPE_ENUM.add,
							`${params.recordName}(${params.inspectionCode})`,
							"巡检模块"
						);
					}
					// 更新巡检list
					const userInfo = this.userInfo;
					this.$store.commit("SET_ALL_DATA", all_data);
					const inspectList = all_data.filter(
						(item) => item.createByName == userInfo.user
					);

					writeInspectionData(inspectList, userInfo.user);

					// 更新日志
					const log_list = this.$store.state.log_list;
					logContent.inspectionType = params.inspectionType;
					this.$logApi.addlog(logContent)
					log_list.push(logContent);
					this.$store.commit("SET_LOG_LIST", log_list);
					addLog(log_list).then((res) => {
						console.log("日志文件写入成功");
					});

					// 清空草稿数据
					this.$store.commit("SET_DARF_DATA", {}); // 缓存[巡检信息]
					writeDarf("").then((res) => {
						console.log("写入草稿文件成功");
					});

					// 清空基础缓存信息
					this.$store.commit("SET_TEMP_DATA", {}); // 缓存[巡检信息]
					// const historyData = {
					// 	location: this.location,
					// 	randomDescription: this.randomDescription,
					// 	tabData: this.list,
					// 	firstSubmitTime: this.firstSubmitTime,
					// };
					// uni.setStorageSync("inspectionHistory", historyData);
					uni.showToast({
						title: "提交成功",
						icon: "success",
					});
					uni.navigateTo({
						url: "/pages/inspectionManagement/index",
					});
				} else {
					uni.showToast({
						title: "请填写完整必填项",
						icon: "none",
					});
				}
			},
			// 切换 Tab
			switchTab(index) {
				this.activeTab = index;
				this.updateCurrentTabData();
			}, // 设置巡检结论
			setInspectionResult(value) {
				this.inspectionResult = value;
				this.list[this.activeTab].inspectionResult = value; // 更新当前 Tab 的数据
				this.onSwitchChange(value); // 触发 Switch 值变化的逻辑
			},
			// Switch 值变化
			onSwitchChange(e) {
				this.inspectionResult = e.detail.value ? 1 : 0;
				this.list[this.activeTab].inspectionResult = this.inspectionResult;
			},
			// 返回
			back() {
				uni.navigateBack();
			},
			// 打开弹窗
			openPopup() {
				this.$refs.popup.open();
			},
			// 关闭弹窗
			closePopup() {
				this.switchTab((this.activeTab + 1) % this.tabs.length);
				this.$refs.popup.close();
			},
		},
	};
</script>
<style scoped lang="less">
	/* 导航栏样式 */
	.uni-nav-bar-text {
		height: 36px;
		width: 36px;
		background: #ffffff;
		border: 0.4px solid rgba(224, 224, 224, 1);
		border-radius: 18px;
		color: #333;
		text-align: center;

		.iconfont {
			font-size: 20px;
			line-height: 36px;
		}
	}

	.container {
		padding: 24px;
	}

	.profile-section {
		width: 100%;
		margin-bottom: 12.8px;

		.profile-box {
			background-color: #fff;
			border-radius: 9.6px;
			padding: 12.8px 25.6px;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.profile-left {
				display: flex;
				align-items: center;

				.avatar {
					position: relative;
					width: 40.5px;
					height: 40.5px;
					border-radius: 50%;
					overflow: hidden;
					margin-right: 9px;

					image {
						width: 100%;
						height: 100%;
					}

					.change-password {
						position: absolute;
						bottom: 0;
						left: 0;
						right: 0;
						background-color: rgba(0, 0, 0, 0.5);
						text-align: center;
						height: 17.6px;
						font-family: PingFangSC-Regular;
						font-size: 9.6px;
						color: #ffffff;
						line-height: 16px;
						font-weight: 400;
					}
				}

				.info {
					.username {
						font-size: 16px;
						color: #000000;
						line-height: 22.4px;
						font-weight: 500;
						margin-bottom: 7.2px;
					}

					.number {
						font-size: 12.8px;
						color: #4A4A4A;
						line-height: 22.4px;
						font-weight: 400;

						.value {
							color: #000000;
						}
					}
				}
			}
		}
	}

	.module {
		background: #FFFFFF;
		border-radius: 12px;
		padding: 16px 25px;
	}

	.title-bar {
		display: flex;
		align-items: center;
		margin-bottom: 10px;

		.blue-line {
			width: 4px;
			height: 16px;
			background-color: #007AFF;
			margin-right: 8px;
		}

		.title {
			font-size: 16px;
			font-weight: bold;
		}

		.location {
			margin-left: 8px;
			color: #666;
		}

		.submit-btn {
			position: absolute;
			right: 24px;
			width: 20%;
			background-color: #ccc;
			color: #fff;
			border-radius: 4px;
			padding: 4px 8px;
			font-size: 12px;

			&.active {
				background-color: #007AFF;
			}
		}
	}

	.description {
		font-size: 14px;
		color: #666;
	}

	.tab-buttons {
		display: flex;
		justify-content: flex-start;
		/* 左对齐 */
		align-items: center;
		margin-bottom: 10px;
		gap: 20px;
		/* Tab 之间的间隔 */
		/* 容器内边距 */
	}

	.tip {
		width: 100%;
		height: 34px;
		background: rgba(55, 116, 246, 0.05);
		border: 1px solid rgba(55, 116, 246, 0.3);
		border-radius: 10px;
		font-size: 14px;
		color: #4A4A4A;
		letter-spacing: 0;
		line-height: 34px;
		font-weight: 400;
		padding: 0 12px;

		.tip-icon {
			width: 14px;
			height: 14px;
			margin-right: 8px;
		}
	}

	.tab-item {
		display: flex;
		align-items: flex-start;
		position: relative;
		padding: 8px 0;
		/* 上下内边距 */
		cursor: pointer;
		white-space: nowrap;
		/* 防止文字换行 */

		.tab-icon {
			width: 10.5px;
			height: 10.5px;
			margin-bottom: 4px;
			margin-right: 3px;
		}

		.tab-text {
			font-size: 14px;
			color: #333;
		}

		&.active {
			.tab-text {
				color: #3774F6;
				/* 选中时的文字颜色 */
			}

			.underline {
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				width: 100%;
				/* 横线宽度与内容一致 */
				height: 2px;
				background-color: #3774F6;
				/* 选中时的横线颜色 */
			}
		}
	}

	.form-item {
		display: flex;
		align-items: center;
		padding: 12px 0;
		line-height: 36px;
		border-bottom: 1px solid #F2F3F5;
		;

		.form-label {
			font-size: 14px;
			font-weight: bold;
			margin-right: 32px;
			width: 73px;
			text-align: right;

			.required {
				color: red;
				margin-right: 4px;
			}
		}

		.switch-container {
			display: flex;
			gap: 12px;
			/* 按钮之间的间隔 */


			.status-btn {
				flex: 1;
				/* 按钮宽度平分 */
				padding: 7px 24px;
				font-size: 16px;
				color: #000000;
				background: #F2F2F2;
				text-align: center;
				font-weight: 400;
				line-height: 22px;
				border-radius: 18px;

				&.active {
					color: #FFFFFF;
					background: #3774F6;
					border: 0.4px solid rgba(224, 224, 224, 1);
				}
			}
		}

		.input-box {
			flex: 1;
			border: 1px solid #ddd;
			border-radius: 4px;
			padding: 6px;
			font-size: 14px;
		}

		.photo-limit {
			font-size: 12px;
			color: #666;
		}

		.photo-container {
			display: flex;
			flex-wrap: wrap;
			margin-bottom: 8px;

			.photo-item {
				position: relative;
				margin-right: 8px;
				margin-bottom: 8px;

				.photo {
					width: 80px;
					height: 80px;
					border-radius: 4px;
				}

				.delete-photo {
					position: absolute;
					top: -8px;
					right: -8px;
					background-color: #ff4d4f;
					color: #fff;
					width: 16px;
					height: 16px;
					border-radius: 50%;
					text-align: center;
					line-height: 16px;
					font-size: 12px;
				}
			}
		}

		.photo-btn {
			background-color: #007AFF;
			color: #fff;
			border-radius: 4px;
			padding: 4px 8px;
			font-size: 12px;
			width: 80px;
			text-align: center;
		}
	}

	.submit-module {
		display: flex;
		justify-content: center;
		gap: 20px;

		.action-btn {
			background-color: #007AFF;
			color: #fff;
			border-radius: 4px;
			padding: 8px 16px;
			font-size: 14px;
			text-align: center;

			&.complete-btn {
				background-color: #007AFF;
			}
		}
	}

	// 弹窗内容样式
	.popup-content {
		background-color: white;
		padding: 40px;
		border-radius: 10px;
		text-align: center;
		position: relative;
		width: 300px;

		// 关闭按钮样式
		.close-icon {
			position: absolute;
			top: 10px;
			right: 10px;
			font-size: 20px;
			cursor: pointer;
		}

		// 成功图标样式
		.icon-success {
			font-size: 40px;
			color: green;
			margin-bottom: 20px;
		}

		// 成功文字样式
		.success-text {
			font-size: 18px;
			margin-bottom: 20px;
		}

		// 下一项按钮样式
		.next-button {
			background-color: blue;
			color: white;
			padding: 10px 20px;
			border-radius: 5px;
			cursor: pointer;
			font-size: 16px;

			// 按钮 hover 效果
			&:hover {
				opacity: 0.9;
			}
		}
	}
</style>