<template>
	<view class="container">
		<view class="example">
			<uni-forms ref="dynamicForm" :model="form" label-width="80px">
				<uni-forms-item label="巡检点" name="inspectionPoint">
					<uni-easyinput disabled :value="form.inspectionPoint" placeholder="请输入巡检点"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="巡检要求" name="inspectionRequirements">
					<uni-easyinput type="textarea" disabled :value="form.inspectionRequirements" placeholder="请输入巡检要求"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="图片上传">
					<view class="example-body">
						<uni-file-picker limit="3" :sourceType="sourceType" :value="img" title="最多选择3张图片"
							file-mediatype="image" @delete="deleteImg" @select="upload"
							:auto-upload="false"></uni-file-picker>
					</view>
				</uni-forms-item>
				<!-- 备注 -->
				<uni-forms-item label="备注" name="remark">
					<uni-easyinput type="textarea" v-model="form.remark" placeholder="请输入备注"></uni-easyinput>
				</uni-forms-item>
			</uni-forms>
			<view class="button-group">
				<button class="btn btn-primary" @click="submit()">提交</button>
				<button class="btn btn-cancel" @click="cancel()">取消</button>
			</view>
		</view>
		<!-- 消息提示框 -->
		<view>
			<uni-popup ref="alertDialog" type="dialog">
				<uni-popup-dialog :type="msgType" title="消息" :content="messageText" @confirm="dialogConfirm"
					showClose="false"></uni-popup-dialog>
			</uni-popup>
		</view>

	</view>
</template>

<script>
	import {
		uploadImg
	} from "@/api/system/user"
	import {
		addRecord
	} from "@/api/inspection/record.js"
	import {
		addWatermarkToImage
	} from "@/utils/watermark.js"
	export default {
		// vue
		data() {
			return {
				form: {
					inspectionType: 0, //默认常规巡检
					inspectorId: this.$store.state.user.nickName, //巡检人
					// 巡检点
					inspectionPoint: "",
					// 巡检要求
					inspectionRequirements: "",
					inspectionImg: "",
					ImgUrl: []
				},
				img: [],
				sourceType: ['camera'],
				//存图片文件
				imgFiles: "",
				// 消息提示框
				msgType: '',
				messageText: '',
				isUploading: false, // 上传中标志
			}
		},
		methods: {
			// 提交
			submit() {
				if (this.isUploading) {
					this.msgType = 'warning'
					this.messageText = '图片正在上传中，请稍等'
					this.$refs.alertDialog.open()
					return;
				}
				if (!Array.isArray(this.form.ImgUrl) || this.form.ImgUrl.length === 0) {
					this.msgType = 'error'
					this.messageText = `请选择要上传的图片`
					this.$refs.alertDialog.open()
					return;
				}

				this.form.inspectionImg = this.joinList()
				addRecord(this.form).then(res => {
					if (res.code === 200) {
						// console.log("sdfsadfsdfsdfsdfsdf");
						this.msgType = 'success'
						this.messageText = `打卡成功`
						this.$refs.alertDialog.open()

					} else {
						this.msgType = 'error'
						this.messageText = `打卡失败`
						this.$refs.alertDialog.open()

					}
				})
			},
			// 图片删除
			deleteImg(e) {
				//const index = this.img.findIndex(f => f.uuid === e.tempFile.uuid); // 假设文件通过 url 唯一标识
				const index = this.img.findIndex(f => f.path === e.tempFile.path); // 假设文件通过 url 唯一标识  
				if (index !== -1) {
					this.form.ImgUrl.splice(index, 1)
					this.img.splice(index, 1)
				}
			},
			// 上传图片
			upload(e) {
				console.log(e);
				// this.img.push(e.tempFiles[0])
				// e.tempFilePaths.forEach(item => {
				// 	uploadImg({
				// 		filePath: item
				// 	}).then(res => {
				// 		this.form.ImgUrl.push(res.fileName)
				// 	})
				// })
				this.handleImageUpload(e.tempFiles[0]);
			},
			// 取消
			cancel() {
				uni.reLaunch({
					url: '/pages/work/index'
				})
				uni.showToast({
					title: '打卡失败',
					icon: 'error', // 成功图标  
					duration: 1000 // 持续时间为2000ms
				});

			},
			// 定义一个方法，用于将list拼接成字符串
			joinList() {
				// 使用数组的join方法，以逗号分隔元素  
				return this.form.ImgUrl.join(',');
			},

			/** 处理图片上传 --知无涯 */
			async handleImageUpload(file) {
				this.isUploading = true; // 开始上传

				const that = this;
				try {
					if (!file) {
						throw new Error('无效的文件对象');
					}

					// 生成水印文字：巡检地点 + 巡检时间
					const times = this.getCurrentDate();

					const watermarkText = `${this.form.inspectionPoint || '未命名地点'} \n${times || '未设置时间'}`;

					// 添加水印 - 水印配置
					// const watermarkedFile = await addWatermarkToImage(file.file, watermarkText, {
					//   font: 'bold 20px Arial', // 加大字号并加粗
					//   color: 'rgba(0, 0, 0, 0.7)' // 黑色，70%不透明度
					// });
					const watermarkedFile = await addWatermarkToImage(file.file, watermarkText);

					// 创建预览URL
					const previewUrl = URL.createObjectURL(watermarkedFile);

					// 更新表单数据
					that.imgFiles = {
						raw: watermarkedFile,
						name: watermarkedFile.name,
						url: previewUrl
					};
					//上传图片,获取图片路径
					that.img.push(that.imgFiles)
					await uploadImg({
						filePath: previewUrl
					}).then(res => {
						that.form.ImgUrl.push(res.fileName)
						// console.log(res);
					})

				} catch (error) {
					console.error("水印处理失败:", error);
					proxy.$modal.msgError("图片处理失败: " + error.message);
				} finally {
					this.isUploading = false; // 上传完毕
				}
			},
			// 获取当前时间
			getCurrentDate() {
				const now = new Date();
				const year = now.getFullYear();
				const month = String(now.getMonth() + 1).padStart(2, '0');
				const day = String(now.getDate()).padStart(2, '0');
				const hours = String(now.getHours()).padStart(2, '0');
				const minutes = String(now.getMinutes()).padStart(2, '0');
				const seconds = String(now.getSeconds()).padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},

			//对话框确定按钮
			dialogConfirm() {
				if (this.msgType == 'success') {
					uni.reLaunch({
						url: '/pages/work/index'
					})
					return;
				} else {
					return;
				}
			},

		},
		// uniapp
		//uniapp方法，在最开始的时候拿到传值过来的值
		onLoad(option) {
			const _this = this
			// console.log('传递的值',option)
			_this.form.inspectionPoint = option.inspectionPoint
			_this.form.inspectionRequirements = option.inspectionRequirements
			_this.form.inspectionPointId = option.inspectionPointId
		},
		created() {
			// console.log("this.$store.state.user",this.$store.state.user);
		}
	}
</script>

<style lang="scss">
	page {
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		background-color: #fff;
		height: 90vh;
		/* 使页面高度占满整个视口 */
	}

	.container {
		flex: 1;
		/* 让 container 占满剩余空间 */
		display: flex;
		flex-direction: column;
		/* 设置为列方向 */
	}

	.example {
		flex: 1;
		/* 让 example 占满 container 的剩余空间 */
		display: flex;
		flex-direction: column;
		/* 设置为列方向，确保子元素垂直排列 */
		padding: 15px;
		background-color: #fff;
	}

	// 样式沉底
	.button-group {
		position: fixed;
		bottom: 20px;
		left: 0;
		/* 使用 margin-top: auto 来将按钮组推到 example 容器的底部 */
		display: flex;
		width: 100%;
		justify-content: space-around;
	}

	.button-group button {
		flex: 1;
		background: #fff;
		color: #000;
		/* 使按钮平分可用空间 */
		/* 可能还需要设置一些其他的样式来确保按钮看起来正确，比如 text-align, padding 等 */
	}
</style>