<template>
	<div class="component-qn-form">
		<Form ref="qnForm" :model="qnForm" label-position="top" :rules="ruleValidate" :disabled="!qnFormEdit">
			<FormItem label="问卷名称" prop="name">
				<Input :class="!qnFormEdit ? 'qn-form-disabled':''" v-model="qnForm.name" placeholder="请输入问卷名称"></Input>
			</FormItem>

			<FormItem label="问卷对象" prop="targetClassIds">
				<RadioGroup v-model="classType" @on-change="onClassTypeChange" v-if="qnFormEdit">
				        <Radio label="private">个人班级</Radio>
				        <Radio label="school">校本班级</Radio>
				</RadioGroup>
				<div v-if="!qnFormEdit && curQnItem" class="vote-class">
					<span v-for="item in curQnItem.targetClassIds" class="vote-class-item">{{ getTargetName(item) }}</span>
				</div>
				<Select multiple v-model="qnForm.targetClassIds" :class="!qnFormEdit ? 'qn-form-disabled':''" placeholder="请选择问卷发布对象" v-else>
					<!-- <Option v-for="(item,index) in classRooms" :value="item.id" :key="index">{{ item.name }}</Option> -->
						<Option v-for="item in classRooms.filter(i=>i.scope === classType)" :value="item.id" :key="item.id">{{ item.name }}</Option>
						<!-- <Option v-for="item in classRooms" :value="item.id" :key="item.id">{{ item.name }}</Option> -->
				</Select>
			</FormItem>

			<FormItem label="起止时间" prop="rangeTime">
				<DatePicker type="datetimerange" @on-change="onChangeRange" format="yyyy-MM-dd HH:mm" :class="!qnFormEdit ? 'qn-form-disabled':''"
				 :editable="isDateEdit" placeholder="请选择问卷起止时间" :value="[qnForm.startTime,qnForm.endTime]">

				</DatePicker>
			</FormItem>


			<FormItem label="问卷描述" prop="description">
				<div ref="descriptionEditor" style="text-align:left" v-show="qnFormEdit"></div>
				<div v-html="qnForm.description" v-show="!qnFormEdit" style="margin:10px;font-size:16px;font-weight:bold;color:#fff"></div>
			</FormItem>


			<!-- <FormItem v-show="qnFormEdit">
				<Button type="primary" class="btn-save" @click="handleSubmit('qnForm')" :loading="isBtnLoading">保存</Button>
				<Button @click="handleCancel('qnForm')" class="btn-reset" style="margin-left: 8px">取消</Button>
			</FormItem> -->
		</Form>

	</div>
</template>
<script>
	
	import E from 'wangeditor'
	export default {
		props: {
			editItem: {
				default: null,
				type: Object
			},
			editable: {
				default: false,
				type: Boolean
			}
		},
		data() {
			return {
				curQnItem:null,
				classType:'private',
				isFalse: false,
				isLoading: false,
				isRelatedContent: false,
				isAdd: true,
				isEdit: false,
				isBtnLoading: false,
				isDateEdit: false,
				qnFormEdit: false,
				currentState: 0,
				editInfo: null,
				userInfo: this.$store.state.userInfo,
				descriptionEditor: null,
				classRooms: [],
				uploadFileList: [],
				defaultFileList: [],
				relateFileList: [],
				uploadUrl: '',
				qnForm: {
					name: '',
					targetClassIds: [],
					endTime: '',
					publishModel: '0',
					rangeTime: [],
					startTime: '',
					description: '',
					isReset: [],
					other: []
				},
				defaultParams: {
					code: "",
					name: "",
					targetClassIds: [],
					publishModel: "0",
					startTime: 0,
					endTime: 0,
					resource: []
				},
				uploadList: [],
				ruleValidate: {
					name: [{
						required: true,
						message: '问卷名称不能为空',
						trigger: 'blur'
					}],
					publishModel: [{
						required: true,
						message: '问卷发布模式不能为空',
						trigger: 'change'
					}],
					description: [{
						required: true,
						message: '问卷描述不能为空',
						trigger: 'blur'
					}],
					targetClassIds: [{
						required: true,
						message: '问卷对象不能为空'
					}],
					rangeTime: [{
						required: true,
						message: '日期不能为空!',
						trigger: 'change',
						type: 'array'
					}]
				}
			}
		},
		methods: {
			onClassTypeChange(val){
				this.qnForm.targetClassIds = []
			},

			onChangeRange(arr) {
				if(arr[0] === ''){
					this.qnForm.rangeTime = null
					this.qnForm.startTime = ''
					this.qnForm.rangeTime = ''
				}else{
					this.qnForm.startTime = this.getTimestampByString(arr[0])
					this.qnForm.endTime = this.getTimestampByString(arr[1])
					this.qnForm.rangeTime = arr
				}
			},

			getTimestampByString(str) {
				str = str.substring(0, 19);
				str = str.replace(/-/g, '/'); //必须把日期'-'转为'/'
				var timestamp = new Date(str).getTime();
				return timestamp
			},
			/**
			 * 提交新增问卷表单
			 * @param name FormName
			 */
			handleSubmit(name) {
				return new Promise((resolve, reject) => {
					this.$refs[name].validate((valid) => {
						if (valid && this.getSimpleText(this.qnForm.description)) {
							console.log(this.qnForm)
							console.log(this.editInfo)
							console.log(this.isEdit)
							let params = JSON.parse(JSON.stringify(this.defaultParams))
							let target = []
							params.code = this.getCurCode
							params.scope = this.getCurScope
							params.name = this.qnForm.name
							// params.publishModel = this.qnForm.publishModel
							params.startTime = this.qnForm.startTime
							params.endTime = this.qnForm.endTime
							params.description = this.qnForm.description
							// params.other = this.qnForm.other
							if (this.isEdit && this.editInfo.id && this.editInfo.code) {
								params.id = this.editInfo.id
								params.createTime = this.editInfo.createTime
							}
							params.targetClassIds = this.qnForm.targetClassIds
							console.log(params)
							resolve(params)
						} else {
							this.$Message.error('请将信息填写完整')
						}
					})
				})
			},

			/**
			 * 获取当前教师的所有班级数据
			 * @param teacherId 老师的醍摩豆ID
			 */
			getClassrooms(teacherId) {
				return new Promise((r, j) => {
					this.$api.learnActivity.FindClassroomByTeacherId({
						id: teacherId,
						code: this.$store.state.userInfo.schoolCode
					}).then(res => {
						if (!res.error && res.courses) {
							r(res.courses)
						} else {
							j(500)
							this.$Message.error('获取数据失败')
						}
					})
				})
			},

			// 提取富文本内容中的文本
			getSimpleText(html) {
				var r = /<(?!img|video|audio).*?>/g;
				return html.replace(r, "");
			},

			/**
			 * 重置表单
			 * @param name
			 */
			handleCancel() {
				this.qnFormEdit = false
				this.doRender(this.editInfo)

			},

			/**
			 * 重置表单
			 * @param name
			 */
			handleReset(name) {
				this.$refs[name].resetFields();
				this.descriptionEditor.txt.clear()

			},

			/** 附件上传之前钩子 限制附件上传个数 */
			handleBeforeUpload() {
				const check = this.uploadList.length < 5;
				if (!check) {
					this.$Notice.warning({
						title: '最多只能上传5个附件'
					});
				}
				return check;
			},



			/**
			 * 回显问卷详情
			 * @param item
			 */
			doRender(item) {
				console.log(item)
				this.qnForm = {
					name: item.name,
					targetClassIds: item.targetClassIds || [],
					startTime: item.endTime ? item.startTime : '',
					endTime: item.endTime ? item.endTime : '',
					description: item.description,
					rangeTime: item.endTime ? [item.startTime,item.endTime] : null
				}
				this.currentState = item.state
				this.$nextTick(() => {
					this.curQnItem = JSON.parse(JSON.stringify(item))
					if(item.targetClassIds.length){
						let isExist = this.classRooms.filter(i => i.id === item.targetClassIds[0])
						this.classType = isExist ? isExist[0].scope : 'private'
					}
				})
				this.descriptionEditor.txt.html(item.description)
			},
			
			/* 根据班级ID获取班级名称 */
			getTargetName(classId){
				if(this.classRooms.length){
					let targetIndex = this.classRooms.map(i => i.id).indexOf(classId)
					return targetIndex > -1 ?  this.classRooms[targetIndex].name : '未匹配数据'
				}else{
					this.getClassrooms(this.userInfo.TEAMModelId).then(res => {
						return res.filter(i => i.id === classId)[0].name
					})
				}
			}

		},
		mounted() {
			/** 获取可选班级列表 */
			this.getClassrooms(this.userInfo.TEAMModelId).then(res => this.classRooms = res)

			/** 初始化问卷详情的富文本编辑器 */
			let descriptionEditor = new E(this.$refs.descriptionEditor)
			descriptionEditor.config.onchange = (html) => {
				this.qnForm.description = html
			}
			this.$editorTools.initMyEditor(descriptionEditor)
			descriptionEditor.create()
			this.descriptionEditor = descriptionEditor
		},
		computed: {
			getDisableDays() {
				return this.qnForm.startTime
			},
			getCurCode() {
				return this.$route.name === 'personalSurvey' ? this.$store.state.userInfo.TEAMModelId : this.$store.state.userInfo.schoolCode
			},
			getCurScope() {
				return this.$route.name === 'personalSurvey' ? 'private' : 'school'
			}
		},
		watch: {
			editItem: {
				handler(newValue) {
					/** 编辑回显 */
					if (newValue) {
						console.log(newValue)
						this.doRender(JSON.parse(JSON.stringify(newValue)))
						this.isEdit = true
						this.editInfo = newValue
					} else {
						/** 新增 */
						this.handleReset('qnForm')
						this.isEdit = false
						this.editInfo = null
					}
				},
				// deep: true,
				// immediate:true
			}
		}
	}
</script>

<style lang="less">
	@import "./BaseQnForm.less";
</style>

<style>
	/* 修改iview Modal样式 */

	.related-modal .ivu-modal-content {
		background: #3c3c3c;
		overflow: hidden;
		color: #fff;
	}

	.related-modal .ivu-modal-body {
		height: 400px;
		padding: 20px;
	}

	.related-modal .ivu-modal-body {
		height: 700px;
	}

	.related-modal .ivu-modal-header {
		border-bottom: none;
		font-size: 18px;
		font-weight: bold;
		padding: 25px;
	}

	.related-modal .modal-content {
		padding: 0 35px 30px 35px;
	}

	.related-modal .modal-btn {
		margin-left: 2%;
		width: 96%;
		height: 40px;
		background: rgb(11, 151, 117);
		border: none;
		color: #fff;
		margin-top: 30px;
	}

	.related-modal .choose-content {
		height: 85%;
	}
</style>
