<template>
	<view class="page">
		<z-nav-bar :title="`${pageType}班级`"></z-nav-bar>
		<!-- 公共组件-每个页面必须引入 -->		
		<public-module></public-module>
		<uni-forms :modelValue="form" :rules="rules" ref="form">
			<!-- <view class="input_box " style="" v-if="!form.id">
				<uni-forms-item label="" name="modelId" label-width="0">
					<view class="">
						<text class="input_tit"><i>*</i>班级类型：</text>
					</view>
					<view class="in" style="flex: 1; border: none;">
										
						<uni-data-select placeholder="请选择班级类型"
						class="addType"
						      v-model="form.type"
						      :localdata="range"
						      @change="selectChange"
							  placement="top"
						    ></uni-data-select>
					</view>
				</uni-forms-item>
			</view> -->
			<!-- <view class="input_box " style="" v-if="!form.id">
				<uni-forms-item label="" name="modelId" label-width="0">
					<view class="">
						<text class="input_tit"><i>*</i>班级模型：</text>
					</view>
					<view class="in" style="flex: 1; border: none;">
						
						<uni-data-select style="width: 100%;" v-model="form.modelId" placeholder="请选择班级的模型"
							:localdata="modelLIst"></uni-data-select>
					</view>
				</uni-forms-item>
			</view> -->
			<view class="input_box">
				<uni-forms-item label="" name="title" label-width="0">
					<text class="input_tit"><i>*</i>班级名称:</text>
					<view class="in">
						<input placeholder-style="font-size:26rpx" type="text" v-model="form.title"
							placeholder="请输入班级名称" />
					</view>
				</uni-forms-item>
			</view>
			<view class="input_box">
				<text class="input_tit">班级封面:</text>
				<view class="in" style="border: none;" @click="checkPermision">
					<u-upload :fileList="fileList1" @afterRead="addPic" @delete="deletePic" :maxCount="1" width="100"
						height="100" :previewFullImage="true">
					</u-upload>
					<!-- <text style="font-size: 24rpx; color: #999;">可上传4张问题截图</text> -->
				</view>
				<!-- <input type="password" maxlength="8" v-model="confirmPassword" placeholder="请确认密码" /> -->
			</view>
			<view class="input_box">
				<text class="input_tit">群二维码:</text>
				<view class="in" style="border: none;" @click="checkPermision">
					<u-upload :fileList="fileList2" @afterRead="addPic2" @delete="deletePic2" :maxCount="1" width="100"
						height="100" :previewFullImage="true">
					</u-upload>					
				</view>				
			</view>
			<view class="input_box">
				<uni-forms-item label="" name="number" label-width="0">
					<text class="input_tit"><i>*</i>目标人数:</text>
					<view class="in">
						<input type="number" @input="relationInput" placeholder-style="font-size:26rpx"
							v-model="form.number" placeholder="请输入学员目标人数" />
					</view>					
				</uni-forms-item>
			</view>
			<view class="input_box">
				<uni-forms-item label="" name="content" label-width="0">
					<text class="input_tit">
						<!-- <i>*</i> -->
						班级简介:<span style="font-weight: normal; color: #999; font-size: 26rpx;">(600字以内)</span></text>
					<view class="in">
						<view class="uni-textarea">
							<!-- <view class='wrapper'> -->
								<view class="editor-wrapper">
									<editor id="editor" class="ql-container" placeholder="请输入班级简介..."
										show-img-size show-img-toolbar show-img-resize
										@statuschange="onStatusChange" :read-only="readOnly"
										@ready="onEditorReady">
									</editor>
								</view>
							<!-- </view> -->
							<!-- <textarea placeholder-style="font-size:26rpx" v-model="form.content" maxlength="600"
								placeholder="请输入您的班级简介600字以内" /> -->
						</view>
					</view>
				</uni-forms-item>
			</view>
		</uni-forms>
		<view class="btn_box"><button @click="onSubmit">提 交</button></view>
		<!-- <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 {
				fileList1: [],
				fileList2:[],
				playData: {},
				modeType:undefined,   // 模型type
				//手机号账号
				form: {
					id:undefined,    // 班级id
					modelId:undefined,
					title: '', // 账号
					content: '', // 描述
					icon: '', //封面
					number: '', // 联系电话	
					qrcode:'' // 群二维码
				},
				readOnly: false,
				formats: {},
				telError: false,
				range:[
					{ value: '0', text: "普通小班",name:"普通小班"},
					{ value: '1', text: "联合班" ,name:"普通小班"},
					{ value: '2', text: "精英班" ,name:"普通小班"},
				],
				rules: {
					title: {
						rules: [{
								required: true,
								errorMessage: '请输入班级名称',
							}

						]
					},					
					number: {
						rules: [{
								required: true,
								errorMessage: '请输入学员目标人数',
							}

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

		},
		beforeDestroy() {
			this.fileList1 = []
			this.fileList2 = []
		},
		onPullDownRefresh(){
			uni.stopPullDownRefresh()
		},
		computed: {
			...mapState(['userInfo']),			
		},
		//方法
		methods: {
			selectChange(e){
				
				console.log("e:", e);
				if(e != this.modeType){
					this.modeType = e
					console.log('formType',this.form.type)
					this.getUserModel()
				}
			},
			// 获取班级详情
			getClassInfo(){
				// console.log('获取课程详情');
				uni.showLoading({
					title: '正在加载'
				})
				$http.request({
						url: "common/class/getClassInfo",
						method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档
						data: {
							"classId": this.form.id // 班类型 0小班 1联合班 2精英班
						},
						header: { //默认 无 说明：请求头
							'Content-Type': 'application/json'
						},
					})
					.then(res => {
						this.refresh = false
						if (res.code == 0) {							
							this.form = res.result.class
							this.onEditorReady()
							if(this.form.icon != ''){
								this.fileList1.push({url:this.form.icon})
							}
							if(this.form.qrcode != ''){
								this.fileList2.push({url:this.form.qrcode})
							}
							this.form.modelId = res.result.classModel.id
						}
						console.log('this.form',res.result);
						uni.hideLoading()
					}).catch(e => {
						uni.hideLoading()
						console.log(e, '数据报错')
						// this.status = 3
						uni.showToast({
							title: `获取数据失败`,
							icon: 'error'
						})
					});
			},
			readOnlyChange() {
				this.readOnly = !this.readOnly
			},
			getHtml() {
				return new Promise((resolve, reject) => {
					this.editorCtx.getContents({
						success: (res) => {
							resolve(res);
						},
						fail: (error) => {
							reject(err);
						},
					});
				});
			},
			onEditorReady() {
				// #ifdef APP-PLUS || MP-WEIXIN || H5
				uni.createSelectorQuery().select('#editor').context((res) => {
					this.editorCtx = res.context
					if (this.form.content == '') return					
					res.context.setContents({
						html: this.form.content
					})
				}).exec()
				// #endif
			},
			undo() {
				this.editorCtx.undo()
			},
			redo() {
				this.editorCtx.redo()
			},			
			onStatusChange(e) {
				const formats = e.detail
				this.formats = formats
			},
			getUserModel() {
				console.log('获取用户的可添加模型列表');
				$http.request({
						url: "common/class/getClassModelByUserid",
						method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档
						data: {
							"userId": this.userInfo.id,
							'type': this.modeType
						},
						header: { //默认 无 说明：请求头
							'Content-Type': 'application/json'
						},
					})
					.then(res => {
						if(res && res.code == 0){
							res.classModelList.forEach(item => {
								item.value = item.id
								item.text = item.title
							})
							console.log('处理后的', res.classModelList);
							this.modelLIst = res.classModelList
						}
					}).catch(e => {
							// console.log('表单错误信息：', err);
							uni.showToast({
								title: '数据获取失败',
								icon: 'error'
							})
						})
					},
					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) => {
											// console.log("that.uploadPicLIst", res);
											that.fileList1.push({
												url: JSON.parse(res.data).url,
											});
											
											// console.log(that.fileList1, "that.uploadPicLIst");
										},
										fail: (error) => {
											console.log("上传失败", error);
										},
									});
								// }
							},
							deletePic(event) {
								this.fileList1.splice(event.index, 1)
							},
							addPic2(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) => {
												// console.log("that.uploadPicLIst", res);
												that.fileList2.push({
													url: JSON.parse(res.data).url,
												});
												
												// console.log(that.fileList1, "that.uploadPicLIst");
											},
											fail: (error) => {
												console.log("上传失败", error);
											},
										});
									// }
								},
								deletePic2(event) {
									this.fileList2.splice(event.index, 1)
								},
							async onSubmit() {
								this.$refs.form.validate().then(async res => {
									let data = await this.getHtml();
									var _data = data.html.replace(/<.*?>/g, "")
									// if (!_data || _data == '') {
									// 	uni.showToast({
									// 		title: '请输入您的答案',
									// 		icon: 'none'
									// 	})
									// 	return
									// }
									this.form.content = data.html
									if (this.fileList1.length > 0) {
										let _list = this.fileList1
										_list = _list.map(item => item.url)
										// console.log('this.fileList1',_list);
										this.form.icon = _list.join(',')
									}
									if (this.fileList2.length > 0) {
										let _list = this.fileList2
										_list = _list.map(item => item.url)
										// console.log('this.fileList1',_list);
										this.form.qrcode = _list.join(',')
									}
									if(this.form.number <= 0){
										uni.showToast({
											title: '目标人数必须大于0个人',
											icon: 'error'
										})
										return
									}
									console.log('*****',this.form.modelId);									
									var _url = ''
									this.form.id ? _url = 'common/class/editClass' : _url = "common/class/addClass"
									$http.request({
											url: _url,
											method: "POST", // POST、GET、PUT、DELETE，具体说明查看官方文档
											data: {
												// ...this.form
												'id':this.form.id, 
													"modelId": this.form.id ? undefined : this.form.modelId,
												    "title": this.form.title,
												    "icon": this.form.icon,
													"state": this.form.id ? this.form.state : undefined,
												    "content": this.form.content,
												    "number": Number(this.form.number),
													"qrcode": this.form.qrcode
											},
											header: { //默认 无 说明：请求头
												'Content-Type': 'application/json'
											},
										})										
										.then(res => {
											uni.showToast({
												title: "操作成功",
												icon:'success'});
											setTimeout(()=> {
												this.fileList1 = []
												this.fileList2 = []
												uni.navigateTo({
													url:`/pages/miniClass/miniClassMan?id=${this.form.modelId}&modelTitle=${this.modelTitle}`
												})
												// this.$nextTick(() => {
												// 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;
	}

	.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;
				}
			}
		}

		.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>