<template>
	<view class="container">
		<uni-nav-bar v-if="!selectedCount" :fixed="true" background-color="rgba(214, 240, 255, 0.0)" status-bar
			rightWidth="300">
			<block slot="left">
				<view @click="back">
					<text class="iconfont icon-fanhui"></text>
				</view>
			</block>
			<block slot="right" class="nav-right">
				<view class="header-buttons" @click="showDescDialog = true">
					<text class="iconfont icon-shuoming"></text>
				</view>
			</block>
		</uni-nav-bar>
		<uni-nav-bar v-else :fixed="true" background-color="#FFF" status-bar leftWidth="300" rightWidth="300">
			<block slot="left">
				<view class="header-left" @click="headerClose">
					<uni-icons size="21" type="closeempty" class="close"></uni-icons>
					<view class="selected-count"> 已选择{{ selectedCount }}张图片</view>
				</view>
			</block>
			<block slot="right" class="nav-right">
				<view class="header-right">
					<!-- <text
            class="iconfont icon-quanxuan"
            @click.stop="toggleSelectAll"
          ></text> -->
					<text class="iconfont icon-shanchu" @click.stop="deletePhotos"></text>
				</view>
			</block>
		</uni-nav-bar>

		<view class="photo-box">
			<view class="photo-list">
				<view v-for="(group, date) in photoGroups" :key="date" class="photo-group">
					<view class="group-header">
						<view class="circle-button" :class="{ active: isDateAllSelected(group, date) }"
							@click.stop="toggleSelectDate(date)">

						</view>
						<view v-if="isDateAllSelected(group, date)" class="iconfont icon-wancheng" @click.stop="toggleSelectDate(date)"></view>
						<text class="date">{{ date }}</text>
					</view>
					<view class="card-list">
						<view v-for="(photo, index) in group" :key="index" class="card"
							@click="previewPhoto(photo, index)">
							<view class="mask" v-if="photo.selected"></view>
							<image :src="photo.imgPath" mode="aspectFill" class="photo"></image>
							<view class="photo-mask">
								<view>拍摄时间：{{photo.time}}</view>
							</view>
							<view class="check-icon" :class="{ active: photo.selected }"
								@click.stop="toggleSelect(photo)">
							</view>
							<view v-if="photo.selected" class=" check-icon iconfont icon-wancheng" @click.stop="toggleSelect(photo)"></view>
							<!-- <text
                class="delete-icon iconfont icon-shanchu"
                @click.stop="deletePhoto(photo)"
              ></text> -->
							<view class="type">{{
                photo.synchronization ? "已同步" : "待同步"
              }}</view>
							<view class="photo-info">
								照片编号：{{ photo.id }}
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view v-if="selectedCount" class="inspection-button" @click="showSyncDialog = true">数据同步</view>

		<view v-else class="inspection-button" @click="takePhoto">设备拍照</view>

		<Dialog v-show="showSyncDialog" ref="Dialog" :list="selectedPhotos" :photos="photos"
			@close="showSyncDialog = false" @getDetails="getDetails"></Dialog>
		<desc-Dialog v-show="showDescDialog" ref="descDialog" @close="close"></desc-Dialog>
	</view>
</template>

<script>
	import moment from "moment";
	import Dialog from "./dialog.vue";
	import descDialog from "./descdialog.vue";
	import {
		addLog,
		getLogContent,
		LOG_TYPE_ENUM,
		writeDeviceData,
	} from "@/utils/IoReadingAndWriting.js";
	import {
		getDeviceDataDetails
	} from "@/request/index.js";

	export default {
		components: {
			Dialog,
			descDialog
		},
		data() {
			return {
				showSyncDialog: false,
				photos: [],
				selectedPhotos: [],
				showDescDialog: false
			};
		},
		computed: {
			photoGroups() {
				const groups = {};
				this.photos.forEach((photo) => {
					const date = photo.date;
					if (!groups[date]) {
						groups[date] = [];
					}
					groups[date].push(photo);
				});
				return groups;
			},
			selectedCount() {
				return this.selectedPhotos.length;
			},
			userInfo() {
				return this.$store.state.now_user || {};
			},
		},
		onLoad() {
			this.getDetails();
		},
		methods: {
			close(key) {
				this.showDescDialog = false
				if (key == 'photo') this.takePhoto()
			},
			showDesc() {
				this.showDesc = true
			},
			back() {
				uni.navigateTo({
					url: "/pages/home/home",
				});
			},
			headerClose() {
				this.clearSelection();
			},
			clearSelection() {
				this.photos.forEach((photo) => (photo.selected = false));
				this.selectedPhotos = [];
			},

			// 数据获取
			getDetails() {
				uni.showLoading();
				getDeviceDataDetails()
					.then((res) => {
						this.photos = res;
						uni.hideLoading();
					})
					.catch((error) => {
						uni.showToast({
							title: error.msg,
							icon: "none"
						});
						uni.hideLoading();
					});
			},

			// 拍照功能
			async takePhoto() {
				try {
					const res = await uni.chooseImage({
						count: 1,
						sourceType: ["camera"]
					});
					const tempFilePath = res.tempFilePaths[0];
					const saveRes = await uni.saveImageToPhotosAlbum({
						filePath: tempFilePath,
					});

					const base64 = await this.convertFileToBase64(tempFilePath);
					const newPhoto = {
						id: this.getFileName(tempFilePath),
						// url: base64,
						imgPath: saveRes.path,
						date: moment().format("YYYY-MM-DD"),
						time: moment().format("YYYY-MM-DD HH:mm"),
						selected: false,
						synchronization: false,
					};

					this.photos.unshift(newPhoto);
					this.addPhotos(this.photos, `照片编号(${newPhoto.id})`, "设备上架");
				} catch (err) {
					console.error("拍照保存失败:", err);
				}
			},

			// 选择功能
			toggleSelect(photo) {
				photo.selected = !photo.selected;
				if (photo.selected) {
					this.selectedPhotos.push(photo);
				} else {
					this.selectedPhotos = this.selectedPhotos.filter(
						(p) => p.id !== photo.id
					);
				}
			},

			isDateAllSelected(group, date) {
				return group.every((photo) => photo.selected);
			},

			toggleSelectDate(date) {
				const group = this.photoGroups[date];
				const isGroupAllSelected = this.isDateAllSelected(group, date);

				group.forEach((photo) => {
					photo.selected = !isGroupAllSelected;
					this.updateSelectedPhotos(photo);
				});
			},

			toggleSelectAll() {
				const isAllSelected = this.photos.length === this.selectedCount;

				this.photos.forEach((photo) => {
					photo.selected = !isAllSelected;
					this.updateSelectedPhotos(photo);
				});
			},

			updateSelectedPhotos(photo) {
				if (photo.selected) {
					if (!this.selectedPhotos.some((p) => p.id === photo.id)) {
						this.selectedPhotos.push(photo);
					}
				} else {
					this.selectedPhotos = this.selectedPhotos.filter(
						(p) => p.id !== photo.id
					);
				}
			},

			// 删除功能
			deletePhoto(photo) {
				this.photos = this.photos.filter((p) => p.id !== photo.id);
				this.selectedPhotos = this.selectedPhotos.filter(
					(p) => p.id !== photo.id
				);
				this.addPhotos(this.photos, "删除照片", "删除");
			},

			deletePhotos() {
				uni.showModal({
					title: "提示",
					content: "确认删除选中的照片？",
					success: (res) => {
						if (res.confirm) {
							const selectedIds = this.selectedPhotos.map((p) => p.id);
							this.photos = this.photos.filter(
								(p) => !selectedIds.includes(p.id)
							);
							this.clearSelection();
							this.addPhotos(this.photos, "批量删除照片", "删除");
							uni.showToast({
								title: "删除成功",
								icon: "success"
							});
						}
					},
				});
			},

			// 其他功能
			previewPhoto(photo, index) {
				// uni.previewImage({
				//   urls: this.photos.map((p) => p.url),
				//   current: photo.url,
				// });
				uni.previewImage({
					urls: this.photos.map((p) => p.imgPath),
					current: index,
				});
			},

			async convertFileToBase64(filePath) {
				return new Promise((resolve, reject) => {
					plus.io.resolveLocalFileSystemURL(
						filePath,
						(entry) => {
							entry.file((file) => {
								const reader = new plus.io.FileReader();
								reader.onloadend = (evt) => resolve(evt.target.result);
								reader.readAsDataURL(file);
							}, reject);
						},
						reject
					);
				});
			},

			getFileName(filePath) {
				return filePath.split("/").pop().split(".").shift();
			},

			addPhotos(photos, title, type) {
				this.$store.commit("SET_DEVICEDATA", photos);
				writeDeviceData(photos, this.userInfo.user);

				const logContent = getLogContent(LOG_TYPE_ENUM.edit, title, type);
				this.$logApi.addlog(logContent)
				const log_list = [
					...this.$store.state.log_list,
					{
						...logContent,
						inspectionType: "3",
					},
				];

				this.$store.commit("SET_LOG_LIST", log_list);
				addLog(log_list);
			},
		},
	};
</script>

<style lang="less" scoped>
	/* 保持原有的样式不变 */
	.container {
		background-image: linear-gradient(115deg, #e8f0fb 0%, #e1ebfa 100%);
		height: 100%;
	}

	.uni-nav-bar-text {
		height: 28.8px;
		width: 28.8px;
		background: #ffffff;
		border: 0.32px solid rgba(224, 224, 224, 1);
		border-radius: 14.4px;
		color: #333;
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;

		.iconfont {
			font-size: 16px;
			line-height: 28.8px;
		}
	}

	.header-left {
		display: flex;
		justify-content: flex-start;
		align-items: center;
		.close {
			font-size: 20px;
		}

		.selected-count {
			font-size: 14.4px;
			line-height: 27px;
			color: #000000;
			font-weight: 500;
			margin-left: 6.4px;
		}
	}

	.nav-right {
		width: 192px;
	}

	::v-deep .uni-navbar__header-btns-left {
		width: 300px !important;
	}

	.header-buttons {
		display: flex;
		align-items: center;
		margin-left: auto;
		width: 28.8px;
		height: 28.8px;
		border-radius: 50%;
		background: #fff;

		.iconfont {
			margin: 0 auto;

			&.icon-shuoming {}
		}
	}

	.header-right {
		.iconfont {
			margin: 0 auto;

			&.icon-quanxuan {
				margin-right: 19.2px;
			}
		}
	}

	.photo-box {
		width: 100%;
		height: 100%;
		overflow: hidden;

		.photo-list {
			padding: 19.2px 0;
			overflow: auto;

			.photo-group {
				margin-bottom: 12.8px;

				.group-header {
					display: flex;
					justify-content: flex-start;
					align-items: center;
					margin-bottom: 6.4px;
					padding: 0 25.6px;
					position: relative;

					.circle-button {
						width: 14.4px;
						height: 14.4px;
						line-height: 14.4px;
						border-radius: 50%;
						border: 1px solid rgba(199, 199, 199, 1);
						cursor: pointer;
						transition: all 0.3s ease;
						text-align: center;


					}

					.icon-wancheng {
						color: #3774f6;
						font-size: 14.4px;
						border: 1px solid #fff;
						background-color: #fff;
						border-radius: 50%;
						position: absolute;
					}

					.date {
						font-size: 14.4px;
						color: #000000;
						line-height: 14.4px;
						font-weight: bold;
						margin-left: 6.4px;
					}
				}

				.card-list {
					display: flex;
					flex-wrap: wrap;
					gap: 3.2px;

					.card {
						width: 168px;
						height: 188.8px;
						margin-bottom: 17.6px;
						position: relative;

						.photo {
							width: 168px;
							height: 168px;

						}

						.check-icon {
							position: absolute;
							top: 6.4px;
							left: 6.4px;
							border-radius: 50%;
							width: 20px;
							height: 20px;
							border: 1px solid #fff;
							display: flex;
							justify-content: center;
							align-items: center;
							line-height: 1;
							z-index: 4;


						}

						.icon-wancheng {
							color: #3774f6;
							font-size: 20px;
							// border: 1px solid #fff;
							background-color: #fff;
							border-radius: 50%;
						}

						.delete-icon {
							position: absolute;
							bottom: 26.4px;
							left: 6.4px;
							border-radius: 50%;
							width: 19.2px;
							height: 19.2px;
							display: flex;
							justify-content: center;
							align-items: center;
							color: white;
						}

						.type {
							width: 41.6px;
							padding: 0 6.4px;
							text-align: center;
							background: rgba(0, 0, 0, 0.5);
							border-radius: 8.8px;
							font-size: 9.6px;
							color: #ffffff;
							text-align: left;
							line-height: 16px;
							font-weight: 400;
							position: absolute;
							right: 10.8px;
							top: 6.4px;
						}

						.photo-mask {
							background: rgba(0, 0, 0, 0.5);
							color: #ffffff;
							position: absolute;
							bottom: 26.4px;
							width: 148px;
							left: 0;
							right: 0;
							border-radius: 4.8px;
							margin: 0 auto;
							padding: 4.8px;
							font-size: 9.6px;
							color: #ffffff;
							line-height: 16px;
							text-shadow: 0 0 2px rgba(0, 0, 0, 0.30);
						}

						.photo-info {
							text-align: center;
							font-family: PingFangSC-Regular;
							font-size: 11.2px;
							color: #000000;
							line-height: 17.6px;
							font-weight: 400;
						}
					}
				}
			}
		}
	}

	.inspection-button {
		display: flex;
		align-items: center;
		justify-content: center;
		position: fixed;
		bottom: 25.6px;
		width: 224px;
		height: 38.4px;
		left: 50%;
		transform: translateX(-50%);
		background-image: linear-gradient(180deg, #3773f6 0%, #2c57f6 99%);
		box-shadow: 0px 8px 19.2px 0px rgba(51, 104, 246, 0.24);
		border-radius: 21.6px;
		font-family: PingFangSC-Regular;
		font-size: 16px;
		line-height: 38.4px;
		color: #ffffff;
		text-align: center;
		font-weight: 400;
	}

	.mask {
		z-index: 2;
		background-color: rgba(255, 255, 255, 0.24);
		position: absolute;
		width: 168px;
		height: 168px;
	}
</style>