<template>
	<view class="page">

		<z-nav-bar title="班级成员设置"></z-nav-bar>
		<!-- 公共组件-每个页面必须引入 -->

		<public-module></public-module>
		<uni-forms :modelValue="form" :rules="rules" ref="form" v-if="roleCode.length > 0">
			<view class="input_box " style="">
				<uni-forms-item label="" name="monitor" label-width="0" v-show="roleCode.includes('主任') || roleCode.includes('副主任')">
					<view class="">
						<text class="input_tit"><i>*</i>班长：</text>
					</view>
					<view class="addBtnBox">
						<view class="item" v-if="memeberRefsh">
							<view class="box" @click="showMemberAdd('monitor')">								
								<view v-show="!form.monitor" class="haveNoPerson flex_box">
									<uni-icons class="addIcon" color="#999" type="plusempty" size="20"></uni-icons>
									<text class="addText">添加人员</text>
								</view>
								<view class="havePerson" v-if="form.monitor">
									<view class="flex_box ">
										<view class="classmateImg">
											<image v-if="form.monitor.avatar != null && form.monitor.avatar != ''" :src="form.monitor.avatar"
												mode="aspectFit"></image>
											<image v-else src="/static/icon/morenAvavter.png" mode="aspectFit"></image>
										</view>
										<view class="textBox">
											<view class="">
												<text style="width: 100%; display: inline-block;">
													{{form.monitor && form.monitor.nickname != '' && form.monitor.nickname != null ? form.monitor.nickname : '匿名用户'}}
												</text>
												<text style="width: 100%; display: inline-block;"> - {{form.monitor.tel}}</text>
											</view>
										</view>										
									</view>
									<view class="" @click.stop="delMemeber('monitor')">
										<text class="delBtn" 
											>删除</text>
									</view>
								</view>								
							</view>
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="" name="dmonitor" label-width="0"
					v-show="roleCode.includes('1') || roleCode.includes('主任') || roleCode.includes('副主任')">
					<view class="">
						<text class="input_tit">
							<!-- <i>*</i> -->
							副班长：</text>
					</view>
					<view class="addBtnBox">
						<view class="item" v-if="memeberRefsh">
							<view class="box" @click="showMemberAdd('dmonitor')">							
								<view v-show="!form.dmonitor" class="haveNoPerson flex_box">
									<uni-icons class="addIcon" color="#999" type="plusempty" size="20"></uni-icons>
									<text class="addText">添加人员</text>
								</view>
								<view class="havePerson" v-if="form.dmonitor">
									<view class="flex_box ">
										<view class="classmateImg">
											<image v-if="form.dmonitor.avatar != null && form.dmonitor.avatar != ''" :src="form.dmonitor.avatar"
												mode="aspectFit"></image>
											<image v-else src="/static/icon/morenAvavter.png" mode="aspectFit"></image>
										</view>
										<view class="textBox">
											<view class="">
												<text style="width: 100%; display: inline-block;">
													{{form.dmonitor && form.dmonitor.nickname != '' && form.dmonitor.nickname != null ? form.dmonitor.nickname : '匿名用户'}}
												</text>
												<text style="width: 100%; display: inline-block;"> - {{form.dmonitor.tel}}</text>
											</view>
										</view>										
									</view>
									<view class="" @click.stop="delMemeber('dmonitor')">
										<text class="delBtn" 
											>删除</text>
									</view>
								</view>								
							</view>
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="" name="learner" label-width="0">
					<view class="">
						<text class="input_tit">
							<!-- <i>*</i> -->
							学习委员：</text>
					</view>
					<view class="addBtnBox">
						<view class="item" v-if="memeberRefsh">
							<view class="box" @click="showMemberAdd('learner')">								
								<view v-show="!form.learner" class="haveNoPerson flex_box">
									<uni-icons class="addIcon" color="#999" type="plusempty" size="20"></uni-icons>
									<text class="addText">添加人员</text>
								</view>
								<view class="havePerson" v-if="form.learner">
									<view class="flex_box ">
										<view class="classmateImg">
											<image v-if="form.learner.avatar != null && form.learner.avatar != ''" :src="form.learner.avatar"
												mode="aspectFit"></image>
											<image v-else src="/static/icon/morenAvavter.png" mode="aspectFit"></image>
										</view>
										<view class="textBox">
											<view class="">
												<text style="width: 100%; display: inline-block;">
													{{form.learner && form.learner.nickname != '' && form.learner.nickname != null ? form.learner.nickname : '匿名用户'}}
												</text>
												<text style="width: 100%; display: inline-block;"> - {{form.learner.tel}}</text>
											</view>
										</view>										
									</view>
									<view class="" @click.stop="delMemeber('learner')">
										<text class="delBtn" 
											>删除</text>
									</view>
								</view>									
							</view>
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="" name="scorer" label-width="0">
					<view class="">
						<text class="input_tit">
							<!-- <i>*</i> -->
							评分员：</text>
					</view>
					<view class="addBtnBox">
						<!-- {{setDefaultAddItem}} -->
						<view class="item" v-if="memeberRefsh">
							<view class="box" v-for="(item, index) in form.scorer"
								@click="showMemberAdd('scorer',index)">								
								<view v-show="!item || item == null || item == 'null'" class="haveNoPerson flex_box">
									<uni-icons class="addIcon" color="#999" type="plusempty" size="20"></uni-icons>
									<text class="addText">添加人员</text>
								</view>
								<view class="havePerson" v-if="item">
									<view class="flex_box ">
										<view class="classmateImg">
											<image v-if="item.avatar != null && item.avatar != ''" :src="item.avatar"
												mode="aspectFit"></image>
											<image v-else src="/static/icon/morenAvavter.png" mode="aspectFit"></image>
										</view>
										<view class="textBox">
											<view class="">
												<text style="width: 100%; display: inline-block;">
													{{item && item.nickname != '' && item.nickname != null ? item.nickname : '匿名用户'}}
												</text>
												<text style="width: 100%; display: inline-block;"> - {{item.tel}}</text>
											</view>
										</view>										
									</view>
									<view class="" @click.stop="delMemeber('scorer',index)">
										<text class="delBtn" 
											>删除</text>
									</view>
								</view>								
							</view>
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="" name="counter" label-width="0">
					<view class="">
						<text class="input_tit">
							<!-- <i>*</i> -->
							记分员：</text>
					</view>
					<view class="addBtnBox">
						<view class="item" v-if="memeberRefsh">
							<view class="box" v-for="(item, index) in form.counter"
								@click="showMemberAdd('counter',index)">
								<view v-show="!item" class="haveNoPerson flex_box">
									<uni-icons class="addIcon" color="#999" type="plusempty" size="20"></uni-icons>
									<text class="addText">添加人员</text>
								</view>
								<view class="havePerson" v-if="item">
									<view class="flex_box ">
										<view class="classmateImg">
											<image v-if="item.avatar != null && item.avatar != ''" :src="item.avatar"
												mode="aspectFit"></image>
											<image v-else src="/static/icon/morenAvavter.png" mode="aspectFit"></image>
										</view>
										<view class="textBox">
											<view class="">
												<text style="width: 100%; display: inline-block;">
													{{item && item.nickname != '' && item.nickname != null ? item.nickname : '匿名用户'}}
												</text>
												<text style="width: 100%; display: inline-block;"> - {{item.tel}}</text>
											</view>
										</view>										
									</view>
									<view class="" @click.stop="delMemeber('counter',index)">
										<text class="delBtn" 
											>删除</text>
									</view>
								</view>

								<!-- <text class="delBtn" v-if="item" @click.stop="delMemeber('counter',index)">删除</text>
								<text class="addText" v-else>添加人员</text> -->
							</view>
						</view>
					</view>
				</uni-forms-item>
			</view>
		</uni-forms>
		<view class="btn_box"><button @click="onSubmit">提 交</button></view>
		<u-popup v-if="MemberAdd" key="1" :show="MemberAdd" :round="10" @close="closePup">
			<view style="padding: 40rpx;" class="flex_box box6">
				<view class="" style="width: 100%; text-align: center;">
					<text class="tips">请选择在下放输入栏中输入电话号码</text>
					<u-search placeholder="请输入电话号码" @focus="focus" @clear="clear" v-model="searchValue" @input="input"
						@blur="blur" @search="search"></u-search>
					<view class="searchList" v-show="showSearchList">
						<view class="itemBox" v-if="searchList.length > 0">
							<view class="item" v-for="(item, index) in searchList" :key="index"
								@click="setMember(item)">
								{{item.tel}}
							</view>
						</view>
						<view v-else class="">
							<u-divider text="未找到此用户"></u-divider>
						</view>
					</view>
				</view>
			</view>
		</u-popup>
		<!-- <z-navigation></z-navigation> -->
	</view>
</template>
<script>
	import $http from '@/config/requestConfig.js';
	import permission from "@/js_sdk/wa-permission/permission.js"
	import {
		mapState,
		mapMutations
	} from 'vuex';
	export default {
		data() {
			return {
				memeberRefsh: true,
				fileList1: [],
				searchValue: '',
				searchList: [],
				showSearchList: false,
				playData: {},
				nowSeting: {
					name: '',
					index: 0
				},
				MemberAdd: false,
				modeType: undefined, // 模型type
				//手机号账号
				form: {
					"classId": 1,
					"monitor": undefined, //班长
					"dmonitor": undefined, //2班长
					"learner": undefined, //学习委员
					"scorer": [undefined, undefined,undefined], //评分员
					"counter": [undefined, undefined] //记分员
				},
				telError: false,
				// relationError: false,
				// relationErrorPattern: false,
				rules: {
					monitor: {
						rules: [{
								required: true,
								errorMessage: '请设置班长人员',
							}

						]
					}
					// ,
					// dmonitor: {
					// 	rules: [{
					// 			required: true,
					// 			errorMessage: '请设置副班长人员',
					// 		}

					// 	]
					// }				
				},
				pageType: '',
				modelLIst: [
					// { value: 0, text: "请选择" },					
				],
				roleCode: ''
			};
		},
		//第一次加载
		onLoad(e) {
			console.log('收到的值', e);
			// this.getUserModel()
			this.roleCode = e.roleCode
			if (e.id) {
				this.form.classId = e.id
				this.getClassInfo()
			} else {
				this.form.id = undefined
			}
		},
		//页面显示
		onShow() {

		},
		computed: {
			...mapState(['userInfo'])
		},
		//方法
		methods: {
			selectChange(e) {

			},
			closePup() {
				this.MemberAdd = false
				setTimeout(() => {
					this.clearSearchData()
				}, 200)

			},
			// 显示人员添加面板
			showMemberAdd(dataName, index) {
				this.nowSeting = {
					name: dataName,
					index
				}
				console.log('赋值', this.nowSeting);
				this.MemberAdd = true
			},
			// 获取班级详情
			getClassInfo() {
				// console.log('获取课程详情');
				uni.showLoading({
					title: '正在加载'
				})
				$http.request({
						url: "common/class/getClassInfo",
						method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档
						data: {
							"classId": this.form.classId
						},
						header: { //默认 无 说明：请求头
							'Content-Type': 'application/json'
						},
					})
					.then(res => {
						this.refresh = false
						if (res.code == 0) {
							if (res.result.admins.length > 0) {
								var scorerIndex = 0
								var counterIndex = 0
								res.result.admins.forEach(item => {
									if (item.role == '1') {
										this.form.monitor = item.user
									}
									if (item.role == '2') {
										this.form.dmonitor = item.user
									}
									if (item.role == '3') {
										this.form.learner = item.user
									}
									if (item.role == '4') {
										this.form.scorer[scorerIndex] = item.user
										scorerIndex += 1
									}
									if (item.role == '5') {
										this.form.counter[counterIndex] = item.user
										counterIndex += 1
									}

								})
							}
							console.log('this.form.scorer', this.form.scorer.length);
						}
						console.log('this.form', this.form);
						uni.hideLoading()
					}).catch(e => {
						uni.hideLoading()
						console.log(e, '数据报错')
						// this.status = 3
						uni.showToast({
							title: `获取数据失败`,
							icon: 'error'
						})
					});
			},
			getSearch() {
				$http.request({
					url: "book/user/getUserList",
					method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档		
					data: {
						// loadAnimate: 'none', // 请求加载动画
						page: 1,
						limit: 5,
						key: this.searchValue
					},
					header: { //默认 无 说明：请求头
						'Content-Type': 'application/json'
					},
				}).then(res => {
					console.log(res, '搜索结果')
					if (res.code == 0 && res.user.records.length > 0) {
						this.searchList = res.user.records
					}
				}).catch(e => {
					// this.titleList = []	
					this.searchList = []
					console.log(e)
				})
			},
			focus(e) {
				// uni.showToast({
				// 	title: 'focus事件，输出值为：' + e.value,
				// 	icon: 'none'
				// })
				// 等于1 就是有权限
				this.showSearchList = true

			},
			blur(res) {
				if (res == '') {
					this.showSearchList = false
					this.searchList = []
				} else {
					this.getSearch()
				}
			},
			clear(res) {
				// uni.showToast({
				// 	title: 'clear事件，清除值为：',
				// 	icon: 'none'
				// })
				this.searchValue = ''
				this.showSearchList = false
			},
			input(res) {
				console.log('----input:', res)
				if (res == '') {
					this.searchList = []
				} else {
					this.getSearch()
				}
			},
			delMemeber(dataName, index) {
				console.log(dataName, index);
				this.memeberRefsh = false
				switch (dataName) {
					case 'counter':
						this.form.counter[index] = undefined
						break;
					case 'scorer':
						this.form.scorer[index] = undefined
						break;
					case 'learner':
						this.form.learner = undefined
						break;
					case 'dmonitor':
						this.form.dmonitor = undefined
						break;
					case 'monitor':
						this.form.monitor = undefined
						break;
				}
				this.memeberRefsh = true

			},
			setMember(item) {
				console.log('选中了值', item);
				if (this.nowSeting.name != '') {
					switch (this.nowSeting.name) {
						case 'counter':
							this.form.counter[this.nowSeting.index] = item
							break;
						case 'scorer':
							this.form.scorer[this.nowSeting.index] = item
							break;
						case 'learner':
							this.form.learner = item
							break;
						case 'dmonitor':
							this.form.dmonitor = item
							break;
						case 'monitor':
							this.form.monitor = item
							break;
					}

				}
				this.MemberAdd = false
				setTimeout(() => {
					this.clearSearchData()
				}, 200)
			},
			clearSearchData() {
				console.log('走重置数据');
				this.showSearchList = false
				this.nowSeting = {
					name: '',
					index: 0
				}
				this.searchValue = ''
				this.searchList = []
			},
			search(res) {
				console.log(res, 'res')
				// uni.showToast({
				// 	title: '搜索：' + res,
				// 	icon: 'none'
				// })
			},


			relationInput(e) {
				// this.relationError = false
				// this.relationErrorPattern = false
			},
			telInput(e) {
				// console.log('键盘输入',e);
				this.telError = false
			},
			async checkPermision() {
				var result = await permission.premissionCheck("CAMERA_EXTERNAL_STORAGE")
				if (result != 1) {
					return false
				}
			},
			addPic(e) {
				console.log("添加图片");
				let that = this;
				uni.uploadFile({
					url: this.$baseUrl + "oss/fileoss",
					filePath: e.file.url,
					//files:e.file,
					name: "file",
					formData: {},
					success: (res) => {
						that.fileList1.push({
							url: JSON.parse(res.data).url,
						});

					},
					fail: (error) => {
						console.log("上传失败", error);
					},
				});
				// }
			},
			deletePic(event) {
				this.fileList1.splice(event.index, 1)
			},
			onSubmit() {
				console.log('form', this.form);
				if (!this.form.monitor) {
					uni.showToast({
						title: '请添加班长人选',
						icon: 'none'
					})
					return
				}
				// if(!this.form.dmonitor){
				// 	uni.showToast({
				// 		title: '请添加副班长人选',
				// 		icon: 'none'
				// 	})
				// 	return
				// }
				// this.$refs.form.validate().then(res => {
				var newScorer = [...this.form.scorer]
				var newCounter = [...this.form.counter]
				if (!this.form.scorer[0] && !this.form.scorer[1]) {
					newScorer = [0, 0]
				} else {
					console.log('newScorer', newScorer);
					this.form.scorer.forEach((item, index) => {
						console.log('item', item);
						if (!item || item == null) {
							console.log('进来了');
							newScorer[index] = {
								id: 0
							}
						}
					})
					// console.log('删除后的newScorer',newScorer);	
					if (newScorer[0].id == newScorer[1].id) {
						uni.showToast({
							title: '两名评分员不能是同一人',
							icon: 'none'
						})
						return
					}
					newScorer = newScorer.map(item => {
						return item.id
					})
					// console.log('删除后的newScorer',newScorer);						
				}

				if (!this.form.counter[0] && !this.form.counter[1]) {
					newCounter = [0, 0]
				} else {
					this.form.counter.forEach((item, index) => {
						if (!item || item == null) {
							newCounter[index] = {
								id: 0
							}
							// newCounter.splice(index, 1)
						}
					})
					if (newCounter[0].id == newCounter[1].id) {
						uni.showToast({
							title: '两名记分员不能是同一人',
							icon: 'none'
						})
						return
					}

					newCounter = newCounter.map(item => {
						return item.id
					})
					// console.log('删除后的newCounter',newCounter);	
				}

				var _url = 'common/class/setUserRole'
				// this.form.classId ? _url = 'common/class/editClass' : _url = "common/class/addClass"
				$http.request({
						url: _url,
						method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档
						data: {
							"classId": this.form.classId,
							"monitor": this.form.monitor.id + '', //班长
							"dmonitor": this.form.dmonitor ? this.form.dmonitor.id + '' : '0', //2班长
							"learner": this.form.learner ? this.form.learner.id + '' : '0', //学习委员
							"scorer": newScorer.join(','), //评分员
							"counter": newCounter.join(',') //记分员
						},
						header: { //默认 无 说明：请求头
							'Content-Type': 'application/json'
						},
					})
					.then(res => {
						uni.showToast({
							title: "操作成功",
							icon: 'success'
						});
						setTimeout(() => {
							uni.navigateBack({
								delta: 1
							});
						}, 1000)
					}).catch(e => {
						// console.log('表单错误信息：', err);
						uni.showToast({
							title: '操作失败',
							icon: 'error'
						})
					});
				// }).catch(err => {
				// 	console.log('表单错误信息：', err);
				// 	uni.showToast({
				// 		title: '页面有未填写的内容哦',
				// 		icon: 'none'
				// 	})
				// })
			}
		},
		//页面隐藏
		onHide() {},
		//页面卸载
		onUnload() {},
		//页面下来刷新
		onPullDownRefresh() {},
		//页面上拉触底
		onReachBottom() {},
		//用户点击分享
		onShareAppMessage(e) {
			return this.wxShare();
		}
	};
</script>
<style lang="scss" scoped>
	@import '@/style/mixin.scss';

	::v-deep .uni-forms-item {
		margin-bottom: 26rpx !important;
	}

	/deep/.uni-select__selector {
		top: unset;
		bottom: calc(100% + 12px);
	}

	/deep/.uni-select {
		border: none;
	}

	/deep/.uni-select__input-text {
		font-size: 14px;
		color: #7f7f7f //修改为你的字体颜色
	}

	/deep/.uni-select__input-placeholder {
		font-size: 14px;
		color: #7f7f7f //修改为你的字体颜色
	}

	/deep/.uni-popper__arrow {
		top: unset;
		bottom: -6px;
		transform: rotate(180deg);
	}

	/deep/.uni-popper__arrow::after {
		top: 0
	}

	.addType {
		width: 100%;
		margin-top: 40rpx;
		margin-bottom: 40rpx;
		border: 1px solid #eee;
	}

	.searchList {
		.item {
			color: #333333;
			font-size: 28rpx;
			padding: 20rpx;
			border-bottom: 1px solid #eee;
		}
	}

	.box6 {
		height: 50vh;
		overflow: scroll;

		.tips {
			color: #999;
			font-size: 26rpx;
			display: block;
			margin-bottom: 20rpx;
		}
	}

	.addBtnBox {
		.item {

			.box {
				color: #999;
				// margin: 20rpx;
				align-items: center;
				font-size: 28rpx;

				padding: 4rpx 8rpx;
				border-radius: 6rpx;
				justify-content: start;
				width: 100%;
				padding: 10rpx 8rpx;

				.haveNoPerson {
					height: 120rpx; border-radius: 10rpx;  align-items: center; justify-content: center;
					background-color: #eee;
				}

				.havePerson {
					width: 100%;
					padding: 20rpx;
					border-radius: 10rpx;
					border: 1px solid #eee;
				}

				.delBtn {
					display: block; padding: 20rpx 0; box-sizing: border-box;
				    width: 100%; text-align: center; background-color: #f1f1f1;
					color: #e60000 !important;
					font-size: 26rpx;
					margin-top: 20rpx;
					// display: inline-block;
					border-radius: 6rpx;
					

				}

				text {
					width: auto !important;
				}

				.span {
					display: inline-block;
					width: 40rpx;

					.addIcon {
						border: 1px solid #999;
					}
				}
			}
		}
	}

	.input_tit {
		font-weight: bold;
	}

	.page {
		background-color: #ffffff;
		padding: 0 65rpx;
		min-height: 100vh;

		.title {
			padding: 30rpx 0 40rpx 0;
			font-size: 40rpx;
			color: #333333;
		}

		.input_box {
			display: block;
			// justify-content: space-between;
			// overflow: hidden;
			// height: 100rpx;
			padding-top: 10rpx;

			// border-bottom: 1rpx solid #eeeeee;
			align-items: center;

			i {
				font-size: 24rpx;
				color: red;
				padding-right: 10rpx;
			}

			.in {
				border: 1rpx solid #eeeeee;
				border-radius: 8rpx;
				padding: 8rpx;
				margin-top: 10rpx;
			}

			text {
				font-size: 30rpx;
				width: 180rpx;
			}

			input {

				flex: 1;
				height: 50rpx;
				// line-height: 70rpx;
				font-size: 30rpx;
			}

			button {
				height: 78rpx;
				line-height: 78rpx;
				font-size: 30rpx;
				color: $themeColor;

				&:active {
					background-color: transparent;
				}
			}
		}

		.classmateImg {
			width: 60rpx !important;
			height: 60rpx !important;
			margin-right: 16rpx;

			image {
				width: 60rpx !important;
				height: 60rpx;
			}
		}

		.btn_box {
			margin-top: 70rpx;
			padding-bottom: 20rpx;

			button {
				font-size: 32rpx;
				@include theme('btn_bg') color: #fff;
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 50rpx;
			}
		}

		.protocol {
			font-size: 24rpx;
			color: #999999;
			text-align: center;
			margin-top: 20rpx;

			text {
				color: $themeColor;
			}
		}
	}
</style>