<template>
	<view class="container">
		<view class="example">
			<uni-forms ref="dynamicForm" :model="form" label-width="80px" :rules="rules">
				<uni-forms-item label="巡检点" name="inspectionPoint" required>
					<uni-easyinput v-model="form.inspectionPoint" placeholder="请输入巡检点"></uni-easyinput>
				</uni-forms-item>
				<uni-forms-item label="巡检类型" name="inspectionType" required>
					<uni-data-select v-model="form.inspectionType" :localdata="selectList"></uni-data-select>
				</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-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>
			<view class="button-group">
				<button type="primary" size="mini" @click="cancel()">取消</button>
				<button type="primary" size="mini" @click="submit()">提交1</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		uploadImg
	} from "@/api/system/user"
	import {
		listData
	} from '@/api/system/dict/data.js'
	import {
		addAbnormal
	} from "@/api/inspection/abnormal.js"
	import { addWatermarkToImage } from "@/utils/watermark.js"
	export default {
		// vue
		data() {
			return {
				// 选择框数据
				selectList: [],
				form: {
					inspectionType: null, //默认常规巡检
					inspectorId: this.$store.state.user.nickName, //巡检人
					inspectionPoint: "",// 巡检点
					remark: "",
					inspectionImg: "",
					ImgUrl: []
				},
				img: [],
				sourceType: ['camera'],
				//存图片文件
				imgFiles: "",
				rules: {
					inspectionPoint: {
						// name 字段的校验规则
						rules: [
							// 校验 name 不能为空
							{
								required: true,
								errorMessage: '请填写巡检点',
							}
						],
					},
					inspectionType: {
						// name 字段的校验规则
						rules: [
							// 校验 name 不能为空
							{
								required: true,
								errorMessage: '请填选择巡检类型',
							}
						],
					},
					remark: {
						// name 字段的校验规则
						rules: [
							// 校验 name 不能为空
							{
								required: true,
								errorMessage: '请填写备注',
							}
						],
					},
				}
			}
		},
		methods: {
			// 初始化字典
			async initDictType() {
				const typeData = await listData({
					dictType: "inspection_type"
				});
				typeData.rows.forEach(item => {
					let data = {
						value: 0,
						text: ""
					}
					data.value = item.dictValue
					data.text = item.dictLabel
					this.selectList.push(data)
				})
			},
			// 提交
			submit() {
				this.$refs.dynamicForm.validate().then(res => {
					this.form.inspectionImg = this.joinList()
					this.form.inspectionTime = new Date() // 添加当前时间
					console.log("this.form",this.form);
					addAbnormal(this.form).then(res => {
						console.log(res);
						if (res.code==200) {
							uni.showToast({
								title: '提交成功',
								icon: 'success', // 成功图标  
								duration: 1000 // 持续时间为2000ms
							});
							setTimeout(() => {
								this.$tab.navigateBack(); // 假设这是正确的页面跳转方法，具体方法可能因框架而异  
							}, 1000);
						}
					})
				})
			},
			// 图片删除
			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); // 通过图片路径表示来删除数组中的指定数据
				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) {
				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);
			
			    // 创建预览URL
			    const previewUrl = URL.createObjectURL(watermarkedFile);
			
			    // 更新表单数据
			    that.imgFiles = {
			      raw: watermarkedFile,
			      name: watermarkedFile.name,
			      url: previewUrl
			    };
				//上传图片,获取图片路径
				that.img.push(that.imgFiles)
				uploadImg({
					filePath: previewUrl
				}).then(res => {
					that.form.ImgUrl.push(res.fileName)
					console.log(res);
				})
				
			  } catch (error) {
			    console.error("水印处理失败:", error);
			    proxy.$modal.msgError("图片处理失败: " + error.message);
			  }
			},
			// 获取当前时间
			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}`;
			},
	
		},
		created() {
			this.initDictType()
		}
	}
</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>