<template>
	<view class="container">
		<view class="example">
			<!-- 基础用法，不包含校验规则 -->
			<uni-forms ref="SafetyDeclarationTable" :rules="customRules" :modelValue="SafetyDeclarationTable"
				label-width="80px">
				<uni-forms-item label="隐患类别" name="declarationType" required>
					<uni-data-select :disabled="id!=null" v-model="SafetyDeclarationTable.declarationType"
						:localdata="selectList"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="隐患内容" name="requirementDescription" required>
					<uni-easyinput :disabled="id!=null" v-model="SafetyDeclarationTable.requirementDescription"
						placeholder="请输入申报内容" />
				</uni-forms-item>
				<!-- <uni-forms-item label="隐患时间" name="occurTime" required>
					<uni-datetime-picker :disabled="id!=null" type="datetime" v-model="SafetyDeclarationTable.occurTime" />
				</uni-forms-item> -->
				<uni-forms-item label="备注" name="remark">
					<uni-easyinput :disabled="id!=null" type="textarea" v-model="SafetyDeclarationTable.remark"
						placeholder="请输入备注" />
				</uni-forms-item>
				<uni-forms-item label="图片上传">
					<view class="example-body">
						<uni-file-picker :readonly="id!=null" limit="9" :value="img" title="最多选择9张图片" 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" flex="1" v-if="!id" @click="cancellation()">取消</button>
				<button type="primary" size="mini" flex="1" v-if="!id" @click="submit('SafetyDeclarationTable')">提交</button>
			</view>
		</view>
	</view>
</template>

<script>
	import { checkRole,checkPermi } from "@/utils/permission"; // 权限判断函数
	import config from '@/config'
	const baseUrl = config.baseUrl
	import store from "@/store"
	import {
		listData
	} from '@/api/system/dict/data.js'
	import {
		uploadImg
	} from "@/api/system/user"
	import {
		addSafetyDeclaration,
		getSafetyDeclaration
	} from "@/api/sidebar/sidebar.js"

	export default {
		data() {
			return {
				id: null,
				msgType: "",
				messageText: "",
				// 选择框数据
				selectList: [],
				img: [],
				SafetyDeclarationTable: {
					declarationType: 0,
					requirementDescription: "",
					occurTime: "",
					declarationImg: "",
					remark: "",
					ImgUrl: []
				},
				selectedImg: "",
				customRules: {
					declarationType: {
						rules: [{
							required: true,
							errorMessage: '请选择申报类型'
						}]
					},
					requirementDescription: {
						rules: [{
							required: true,
							errorMessage: '申报内容不能为空'
						}]
					},
					// occurTime: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '申报时间不能为空'
					// 	}]
					// }
				}
			}
		},
		mounted() {
			// 需要在onReady中设置规则
			this.$refs.SafetyDeclarationTable.setRules(this.customRules)
		},
		onLoad(option) {
			if (option.id) {
				this.id = option.id
				this.getData();
			}
		},
		methods: {
			// 注册
			checkPermi,
			checkRole,
			getData() {
				getSafetyDeclaration(this.id).then(res => {
					this.SafetyDeclarationTable.declarationType = res.data.declarationType * 1.
					this.SafetyDeclarationTable = res.data
					if (res.data.declarationImg != "") {
						let filePathArray = res.data.declarationImg.split(",");
						filePathArray.forEach(item => {
							this.img.push({
								url: baseUrl + item
							})
							console.log(this.img);
							console.log(baseUrl);
						})
						// console.log("filePathArray",filePathArray);	
					}
				})
			},
			deleteImg(e) {
				console.log("deleteImg", e.tempFile.uuid);
				// console.log("deleteImg",this.SafetyDeclarationTable.ImgUrl);
				const index = this.img.findIndex(f => f.uuid === e.tempFile.uuid); // 假设文件通过 url 唯一标识  
				console.log(index);
				if (index !== -1) {
					// 移除文件  
					this.selectList.splice(index, 1);
					this.SafetyDeclarationTable.ImgUrl.splice(index, 1)
					// console.log();
				}
			},
			submit(ref) {
				this.$refs[ref].validate().then(res => {
					this.SafetyDeclarationTable.declarationImg = this.joinList()
					console.log("提交成功");
					console.log("this.SafetyDeclarationTable", this.SafetyDeclarationTable);
					addSafetyDeclaration(this.SafetyDeclarationTable).then(res => {
						uni.showToast({
							title: '提交成功',
							icon: 'success', // 成功图标  
							duration: 1000 // 持续时间为2000ms
						});
						// 延时执行，确保弹窗有足够的时间显示  
						setTimeout(() => {
							this.$tab.navigateBack(); // 假设这是正确的页面跳转方法，具体方法可能因框架而异  
						}, 1000);
					})
				}).catch(err => {
					console.log('err', err);
				})
			},
			cancellation() {
				this.$tab.navigateBack();
			},
			// 上传图片
			upload(e) {
				console.log(e);
				this.img.push(e.tempFiles[0])
				e.tempFilePaths.forEach(item => {
					uploadImg({
						filePath: item
					}).then(res => {
						console.log(res);
						this.SafetyDeclarationTable.ImgUrl.push(res.fileName)
					})
				})
			},
			// 初始化字典
			async initDictType() {
				const typeData = await listData({
					dictType: "hs_declaration_type"
				});
				typeData.rows.forEach(item => {
					let data = {
						value: 0,
						text: ""
					}
					data.value = item.dictValue
					data.text = item.dictLabel
					this.selectList.push(data)
					// console.log(this.selectList);
				})
			},
			// 定义一个方法，用于将list拼接成字符串  
			joinList() {
				// 使用数组的join方法，以逗号分隔元素  
				return this.SafetyDeclarationTable.ImgUrl.join(',');
			}
		},
		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;
	}

	.segmented-control {
		margin-bottom: 15px;
	}

	.form-item {
		display: flex;
		align-items: center;
	}

	// 样式沉底
	.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>