<template>
	<view>
		<view class="container" v-if="formInfo&&formInfo.length>0">
			<view class="list-item title">投诉原因：{{ text }}</view>
		</view>
		<view class="formbox" v-if="formInfo&&formInfo.length>0">
			<u-form labelPosition="left" labelWidth='80' :model="formdata" :rules="rules" ref="uForm" errorType="toast">
				<u-form-item :required="item.isRequire == 1" :label="item.name" :prop="item.desc"
					v-for="(item,i) in formInfo" :key="i">
					<template v-if="item.type=='文本框'">
						<u-input v-model="formdata[item.desc]" border="none" :clearable="true"
							:placeholder="'请填写'+item.name"></u-input>
					</template>
					<template v-if="item.type=='图片'">
						<view class="imgitem">
							<u-upload :key="imgdata[item.desc].key" :fileList="imgdata[item.desc]" @afterRead="afterRead" @delete="deletePic"
								:name="item.desc" multiple :maxCount="9">
							</u-upload>
						</view>
					</template>
				</u-form-item>
			</u-form>
			<view class="footer-btn">
				<button class="submit-btn" @click="submit">提交</button>
				<button class="submit-btn back-btn" @click="goBack">返回</button>
			</view>
		</view>
		<view class="container" v-else>
			<view class="list-item title">请选择投诉原因</view>
			<view class="list-item" v-for="(item, index) in feedbackItems" :key="index"
				@click="handleClick(item,index)">
				<view>{{ item.name }}</view>
				<uni-icons type="right" size="20" color="rgba(0,0,0,.3)" v-if="formInfo.length==0"></uni-icons>
			</view>
			<view class="list-item" v-if="pageIndex!=0&&formInfo.length==0" @click="goBack">
				返回上一层
			</view>
		</view>
	</view>
</template>

<script>
	import { templateList, complaint,getUserInfo } from "@/api/user.js"
	export default {
		data() {
			return {
				statusBarHeight: uni.getSystemInfoSync().statusBarHeight,
				menuButtonH: 45,
				pageIndex: 0,
				list: [],
				feedbackItems: [],
				userId: '',
				courseId: '',
				videoId: '',
				formInfo: [],
				formdata: {},
				imgdata: {},
				rules: {},
				text: '',
				templateId: 0,
				user: {},
				isLastChild: 0
			};
		},
		onLoad(option) {
			this.$isLogin().then(
				res => {
					if(res){
						this.getUserInfo()
						this.getList()
					}
					else{
						uni.navigateTo({
							url:'/pages/auth/login'
						})
					}
				}
			);
		},
		methods: {
			getUserInfo(){
				getUserInfo().then(
					res => {
						if(res.code==200){
							if(res.user!=null){
								this.user=res.user
							}
						}
					},
					rej => {}
				);
			},
			goBack() {
				// 返回上一层逻辑
				if (this.pageIndex == 0) {
					uni.navigateBack();
				} else {
					this.pageIndex--;
					this.formInfo = []
					this.rules = {}
					this.formdata = {}
					this.imgdata = {}
					if (this.isLastChild == 1) {
						this.isLastChild = 0
					} else {
						if (this.pageIndex == 0) {
							this.feedbackItems = this.list
							this.templateId = 0
						} else {
							const list = this.findGrandparentOrAllData(this.list, this.templateId)
							this.feedbackItems = list.children
							this.templateId = list.id
						}
					}

				}
			},
			findGrandparentOrAllData(data, targetId) {
				// 递归函数，用于查找目标节点的父级节点
				function findParent(node, targetId) {
					if (!node || !node.children) return null;

					for (let child of node.children) {
						if (child.id === targetId) {
							return node; // 找到目标节点的父级节点
						}

						const result = findParent(child, targetId); // 递归查找子节点
						if (result) return result;
					}

					return null;
				}

				// 遍历顶层节点，查找目标节点的父级和祖父级节点
				for (let root of data) {
					if (root.id === targetId) {
						return data; // 如果目标节点是顶层节点，返回所有数据
					}

					const parent = findParent(root, targetId); // 查找目标节点的父级节点
					if (parent) {
						const grandparent = findParent(root, parent.id); // 查找父级节点的父级节点
						return grandparent || data; // 如果找到祖父节点返回祖父节点，否则返回所有数据
					}
				}

				return data; // 如果没有找到目标节点，返回所有数据
			},
			handleClick(item, index) {
				if (this.isLastChild == 1) return
				if (this.pageIndex >= 0) {
					this.pageIndex++
					let children = this.feedbackItems[index].children || [];
					this.templateId = this.feedbackItems[index].id
					this.formInfo = []
					this.rules = {}
					this.formdata = {}
					this.imgdata = {}
					this.text = this.feedbackItems[index].name
					if (children.length > 0) {
						this.isLastChild = 0
						this.feedbackItems = children
						this.templateId = this.feedbackItems[0].id
					} else {
						this.isLastChild = 1
						if (this.feedbackItems[index].description) {
							this.formInfo = JSON.parse(this.feedbackItems[index].description)
							const rules = {};
							const formdata = {};
							// 遍历description中的每个对象
							this.formInfo.forEach(descObj => {
								const {
									isRequire,
									desc,
									name,
									type
								} = descObj;
								formdata[desc] = ""
								if (type == '图片') {
									this.imgdata[desc] = []
									this.imgdata[desc].key = 1
									this.$forceUpdate()
								}
								// 如果isRequire为"1"，则添加到rules中
								if (isRequire == 1) {
									rules[desc] = [{
										required: true,
										message: name + '不能为空',
										trigger: ["change", "blur"]
									}];
								}
							});
							this.rules = rules
							this.formdata = formdata
							setTimeout(() => {
								this.$refs.uForm.setRules(this.rules)
							}, 200)
						} else {
							this.formInfo = []
							this.rules = {}
							this.formdata = {}
							this.imgdata = {}
							this.$forceUpdate()
						}
					}
				}
			},
			getList() {
				templateList().then(res => {
					if (res.code == 200) {
						this.list = res.data
						this.pageIndex = 0
						this.feedbackItems = this.list
					} else {
						this.list = []
					}
				})
			},
			submit() {
				const imgs = this.convertArrayToString(this.imgdata)
				this.formdata = {
					...this.formdata,
					...imgs
				};
				this.$refs.uForm.validate().then(res => {
					if (res) {
						const param = {
							userId: this.user.userId,
							userName: this.user.nickName,
							templateId: this.templateId,
							...this.formdata
						}
						complaint(param).then(res => {
							if (res.code == 200) {
								uni.showModal({
									title: '',
									content: '我们已收到您的反馈，谢谢',
									showCancel: false,
									success: (res) => {
										this.formInfo = []
										this.rules = {}
										this.formdata = {}
										this.imgdata = {}
										this.text = ''
										this.templateId = 0
										this.isLastChild = 0
										this.pageIndex = 0
										this.feedbackItems = this.list
										uni.navigateBack()
									}
								});
							} else {
								uni.showToast({
									title: res.msg,
									icon: 'none'
								})
							}
						})
					}
				})
			},
			convertArrayToString(obj) {
				const result = {};
				for (const key in obj) {
					if (obj.hasOwnProperty(key)) {
						const value = obj[key];
						// 如果值是数组，则将其转换为逗号分隔的字符串
						if (Array.isArray(value)) {
							result[key] = value.filter(item => item.status == 'success').map(it => it.url).join(
								","); // 使用逗号分隔数组元素
						} else {
							result[key] = value; // 保持原样
						}
					}
				}
				return result;
			},
			deletePic(event) {
				const fieldName = event.name;
				const index = event.index;

				if (this.imgdata[fieldName] && Array.isArray(this.imgdata[fieldName])) {
					this.imgdata[fieldName].splice(index, 1);
				}
				this.$forceUpdate()
				this.imgdata[fieldName].key --
			},
			async afterRead(event) {
				const fieldName = event.name;

				if (!this.imgdata[fieldName]) {
					this.imgdata[fieldName] = [];
					this.imgdata[fieldName].key = 1
				}

				let lists = Array.isArray(event.file) ? event.file : [event.file];
				for (let i = 0; i < lists.length; i++) {
					this.imgdata[fieldName].push({
						...lists[i],
						status: 'uploading',
						message: '上传中...'
					});
					this.$forceUpdate()
					this.imgdata[fieldName].key ++
					// 调用上传方法
					const result = await this.uploadFilePromise(lists[i].url);
					if (result.code == 200) {
						this.imgdata[fieldName][this.imgdata[fieldName].length - 1] = {
							...this.imgdata[fieldName][this.imgdata[fieldName].length - 1],
							url: result.url,
							status: 'success',
							message: ''
						};
						this.$forceUpdate()
						this.imgdata[fieldName].key ++
					} else {
						this.imgdata[fieldName][this.imgdata[fieldName].length - 1] = {
							...this.imgdata[fieldName][this.imgdata[fieldName].length - 1],
							status: 'fail',
							message: '上传失败'
						};
						this.$forceUpdate()
						this.imgdata[fieldName].key ++
						uni.showToast({
							title: '上传失败',
							icon: 'error'
						});
					}
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: uni.getStorageSync('requestPath') + '/app/common/uploadOSS', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							resolve(JSON.parse(res.data))
						},
						fail: (err) => {
							uni.showToast({
								title: '上传失败',
								icon: 'error'
							})
						}
					});
				})
			}
		}
	};
</script>

<style scoped lang="scss">
	.formbox {
		background-color: #fff;
		padding: 0 30rpx;
	}

	.footer-btn {
		width: 100%;
		box-sizing: border-box;
		padding: 32rpx 0;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.back-btn {
		margin-top: 40rpx;
		color: #078C9D !important;
		background: #fff !important;
		border: 1rpx solid #078C9D;
	}

	.submit-btn {
		width: 100%;
		height: 88upx;
		line-height: 88upx;
		text-align: center;
		font-size: 34upx;
		font-family: PingFang SC;
		font-weight: 400;
		color: #FFFFFF;
		background: #078C9D;
		border-radius: 10upx;
		
		&::after {
			border: none;
		}
	}

	.arrow-left {
		position: absolute;
		left: 24rpx;
		height: 88rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		overflow: hidden;
	}

	.list-item {
		background-color: #fff;
		padding: 24rpx;
		border-bottom: 1rpx solid #f4f4f4;
		font-size: 15px;
		color: #333;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.title {
		color: rgba(0, 0, 0, .5);
		background-color: transparent;
		border-top: 1rpx solid #f4f4f4;
	}

	.imgitem {
		display: flex;
		align-items: center;
		justify-content: flex-start;

		.icon {
			min-width: 30rpx;
			margin-right: 15rpx;
			width: 30rpx;
			height: 30rpx;
		}
	}
</style>