<template>
	<!-- 使用自定义导航栏 -->
	<view>
		<custom-navbar title="产品说明" :showBack="true" backgroundColor="#202020" color="#FFFFFF"
			:right-text="isDeleteMode ? '完成' : '删除'" right-color="rgba(255, 255, 255, 0.87)"
			@right-click="toggleDeleteMode">
		</custom-navbar>

		<view class="device-page" :style="{ paddingTop: navBarHeight + 'px' }">
			<view class="example-body">
				<!-- 图片列表 -->
				<view class="image-list">
					<view class="image-item" v-for="(image, index) in instructionImages" :key="index"
						@click="handleImageClick(index,image)">
						<image :src="image.fileUrl" mode="aspectFit" class="instruction-image"
							:class="{ 'image-selected': isDeleteMode && selectedImages.includes(index) }"></image>

						<!-- 多选模式下的选中标记 -->
						<view class="checkmark" v-if="isDeleteMode && selectedImages.includes(index)">
							<image src="/static/images/delete-icon.png" mode="aspectFill"></image>
						</view>
					</view>

					<!-- 上传按钮（非删除模式显示） -->
					<view class="upload-btn" v-if="!isDeleteMode">
						<uni-file-picker ref="filePicker" v-model="fileList" @select="selectFile" limit="9"
							class="custom-file-picker"></uni-file-picker>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部删除按钮（多选模式显示） -->
		<view class="delete-footer" v-if="isDeleteMode && selectedImages.length > 0">
			<button @click="deleteSelectedImages">删除({{selectedImages.length}})</button>
		</view>
		<!-- 删除弹框 -->
		<view class="agreement-mask" v-if="deleteShow">
			<view class="agreement-popupC">
				<view class="popup-content">
					<image src="/static/images/dell.png" mode="" class="svg"></image>
					<uni-icon class="trash"></uni-icon>
					<view>
						<view class="popup-Title">确定删除所选设备！</view>
					</view>
				</view>
				<!-- 按钮组 -->
				<view class="popup-buttons">
					<button class="btn agreeBtn" @click="handleBtn">确定</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		baseURL,
		getToken,
		clientid
	} from '@/utils/request'
	import {
		fileInfo,
		fileDelete
	} from '@/api/common/operatingInstruct/index.js'

	export default {
		data() {
			return {
				navBarHeight: 70 + uni.getSystemInfoSync().statusBarHeight,
				fileList: [],
				deviceID: "",
				instructionImages: [],
				isDeleteMode: false, // 是否删除模式
				selectedImages: [], // 选中的图片索引
				deleteShow: false,
				ImageData: [],
				filePicker: ''
			}
		},
		methods: {
			// 选择文件
			selectFile(e) {
				console.log('选择文件：', e)
				// const file = e.tempFiles[0].file
				const files = e.tempFiles.map(item => item.file)
				console.log('files', files);
				this.uploadFile(files)
			},
			// 上传图片
			uploadFile(files) {
				this.$refs.filePicker.clearFiles() // 通过ref操作uni-file-picker组件
				uni.showLoading({
					title: '上传中...'
				})
				files.forEach(file => {
					uni.uploadFile({
						url: baseURL + '/app/file/upload',
						filePath: file.path || file.url,
						name: 'files',
						formData: {
							deviceId: this.deviceID,
							fileType: '2' //文件类型(1:操作说明，2:产品参数)
						},
						header: {
							'Authorization': 'Bearer ' + getToken(),
							'clientid': clientid(),
						},
						complete: (res) => {
							console.log(res, 'resss');
							try {
								const responseData = JSON.parse(res.data); 
								if (responseData.code === 200) {
									uni.showToast({
										title: responseData.msg,
										icon: 'success'
									});
									this.$refs.filePicker.clearFiles(); // 清空已选文件
									this.callOtherApi();
								} else {
									uni.showToast({
										title: responseData.msg,
										icon: 'none'
									});
								}
							} catch (e) {
								uni.showToast({
									title: '上传失败',
									icon: 'none'
								});
							} finally {
								uni.hideLoading();
							}
						}
					})
				})
			},

			// 获取图片列表
			callOtherApi() {
				let data = {
					deviceId: this.deviceID
				}
				fileInfo(data).then((res) => {
					if (res.code == 200) {
						this.instructionImages = res.data
					}
				})
			},

			// 切换删除模式
			toggleDeleteMode() {
				this.isDeleteMode = !this.isDeleteMode
				if (!this.isDeleteMode) {
					this.selectedImages = []
				}
			},
			// 图片点击处理
			handleImageClick(index, item) {
				if (this.isDeleteMode) {
					// 删除模式下处理多选
					const selectedIndex = this.selectedImages.indexOf(index)
					if (selectedIndex > -1) {
						this.selectedImages.splice(selectedIndex, 1)
						this.ImageData.splice(selectedIndex, 1) // 保持同步删除
					} else {
						this.selectedImages.push(
							index

						)
						this.ImageData.push(item) // 保持同步添加
					}
				} else {
					// 正常模式下预览图片
					uni.previewImage({
						current: this.instructionImages[index].fileUrl,
						urls: this.instructionImages.map(item => item.fileUrl)
					})
				}
			},

			// 删除选中的图片
			deleteSelectedImages() {
				if (this.selectedImages.length === 0) return
				this.deleteShow = true
			},
			async handleBtn() {
				try {
					uni.showLoading({
						title: '删除中...',
						mask: true
					})
					// 构造删除请求数据
					const ids = this.ImageData.map(item => item.id).join(',')
					// 调用删除接口
					const res = await fileDelete(ids)
					if (res.code === 200) {
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						})
						// 从后往前删除，避免索引变化
						this.selectedImages
							.sort((a, b) => b.index - a.index)
							.forEach(item => {
								this.instructionImages.splice(item.index, 1)
							})
						this.callOtherApi()
						// 重置状态
						this.selectedImages = []
						this.isDeleteMode = false
						this.deleteShow = false
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
						this.deleteShow = false
					}
				} catch (error) {} finally {
					uni.hideLoading()
				}
			}
		},
		onLoad(options) {
			this.deviceID = options.id
			this.callOtherApi()
		}
	}
</script>

<style scoped>
	.device-page {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		background-color: rgb(18, 18, 18);
		padding: 30rpx;
	}

	.example-body {
		margin-top: 20rpx;
	}

	/* 图片列表 */
	.image-list {
		display: flex;
		flex-wrap: wrap;
		margin: -10rpx;
	}

	/* 图片项 */
	.image-item {
		width: 33.33%;
		padding: 10rpx;
		position: relative;
	}

	/* 图片样式 */
	.instruction-image {
		width: 180rpx;
		height: 180rpx;
		border-radius: 10rpx;
		background-color: #2a2a2a;
	}

	/* 选中效果 */
	.image-selected {
		opacity: 0.7;
	}

	/* 选中标记 */
	.checkmark {
		position: absolute;
		bottom: 20rpx;
		right: 40rpx;
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.checkmark image {
		width: 24rpx;
		height: 24rpx;
	}

	/* 上传按钮 */
	.upload-btn {
		width: 33.33%;
		padding: 10rpx;
	}

	/* 底部删除按钮 */
	.delete-footer {
		position: fixed;
		bottom: 20rpx;
		left: 0;
		right: 0;
		height: 100rpx;
		display: flex;
		justify-content: center;
		align-items: center;

	}

	.delete-footer button {
		width: 90%;
		height: 88rpx;
		line-height: 88rpx;
		background: rgba(187, 230, 0, 1);
		background: rgba(187, 230, 0, 1);
		border-radius: 90px;
	}

	/* 遮罩层 */
	.agreement-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 9999;
	}

	/* 弹窗主体 */
	.agreement-popup {
		width: 100%;
		height: 50%;
		background-color: rgb(42, 42, 42);
		border-radius: 60rpx 60rpx 0rpx 0rpx;
		padding: 40rpx;
		box-sizing: border-box;
		position: absolute;
		bottom: 0rpx;
	}

	.popup-Title {
		color: rgba(255, 255, 255, 0.86);
		text-align: center;
		padding: 30rpx 0rpx;
	}

	.popup-buttons {
		display: flex;
		text-align: center;
	}

	.agreement-popupC {
		width: 60%;
		background-color: rgb(42, 42, 42);
		border-radius: 40rpx;
		padding: 30rpx;
		text-align: center;
		border: 1px solid rgba(255, 200, 78, 0.3);
	}

	.popup-flex {
		display: flex;
		white-space: nowrap;
		color: rgba(255, 255, 255, 0.87);
		height: 50rpx;
		padding: 30rpx;
	}

	.popup-input {
		border: 1px solid rgba(255, 255, 255, 0.4);
		border-radius: 12rpx;
		margin-left: 15rpx;
		padding: 10rpx 0rpx;
		font-size: 28rpx;
	}

	.svg {
		width: 58rpx;
		height: 62rpx;
	}

	/* 通用按钮样式 */
	.btn {
		height: 60rpx;
		line-height: 60rpx;
		border-radius: 40rpx;
		font-size: 24rpx;
		margin: 10rpx auto;
		text-align: center;

	}

	/* 同意按钮 */
	.agreeBtn {
		background: #FFC84E;
		color: #232323;
		border: none;
		width: 170rpx !important;
	}
</style>