<template>
	<div class="component-qn-form">
		<Form ref="qnForm" :model="qnForm" label-position="top" :rules="ruleValidate" :disabled="!qnFormEdit">
			<FormItem :label="$t('survey.form.name')" prop="name">
				<Input :class="!qnFormEdit ? 'qn-form-disabled':''" v-model="qnForm.name"
					:placeholder="$t('survey.form.namePlace')"></Input>
			</FormItem>

			<FormItem :label="$t('survey.form.target')" prop="classes">
				<RadioGroup v-model="classType" @on-change="onClassTypeChange" v-if="qnFormEdit">
					<Radio label="private">{{ $t('survey.form.privateClass') }}</Radio>
					<Radio label="school">{{ $t('survey.form.schoolClass') }}</Radio>
				</RadioGroup>
				<div v-if="!qnFormEdit && curQnItem" class="vote-class">
					<span v-for="item in curQnItem.classes" class="vote-class-item">{{ getTargetName(item) }}</span>
				</div>
				<Select multiple v-model="qnForm.classes" :class="!qnFormEdit ? 'qn-form-disabled':''"
					:placeholder="$t('survey.form.targetPlace')" v-else>
					<Option v-for="(item,index) in classRooms.filter(i=>i.scope === classType)" :value="item.id"
						:key="index">{{ item.name }}</Option>
				</Select>
			</FormItem>

			<!-- <FormItem :label="$t('survey.form.time')" prop="rangeTime">
				<RadioGroup v-model="publishModel" v-if="qnFormEdit">
				        <Radio label="0">立即发布</Radio>
				        <Radio label="1">定时发布</Radio>
				</RadioGroup>
				<DatePicker type="datetimerange" @on-change="onChangeRange" @on-open-change="onOpenChange" format="yyyy-MM-dd HH:mm" :class="!qnFormEdit ? 'qn-form-disabled':''"
				 :editable="isDateEdit" :placeholder="$t('survey.form.endTimePlace')" :value="[qnForm.startTime,qnForm.endTime]">
				</DatePicker>
			</FormItem> -->

			<FormItem :label="$t('learnActivity.createEv.publishType')" prop="publishModel" v-show="qnFormEdit">
				<Checkbox v-model="isImmediate">{{ $t('global.publishType1')}}</Checkbox>
			</FormItem>

			<FormItem :label="$t('learnActivity.createEv.startTime')" v-if="!isImmediate || !qnFormEdit"
				prop="startTime">
				<DatePicker v-show="qnFormEdit" type="datetime" :options="startOption" format="yyyy/MM/dd HH:mm"
					v-model="qnForm.startTime" split-panels :placeholder="$t('learnActivity.createEv.sTimeHolder')"
					style="width:100%" @on-change="onChangeSTime"></DatePicker>
				<div v-show="!qnFormEdit" style="margin:10px;font-size:16px;font-weight:bold;color:#fff">
					{{ $tools.formatTime(qnForm.startTime,'yyyy-MM-dd hh:mm') }}
				</div>
			</FormItem>

			<FormItem :label="$t('learnActivity.createEv.endTime')"  prop="endTime">
				<DatePicker v-show="qnFormEdit" type="datetime" :options="endOption" format="yyyy/MM/dd HH:mm" v-model="qnForm.endTime"
					split-panels @on-change="onChangeEndTime" :placeholder="$t('learnActivity.createEv.eTimeHolder')" style="width:100%"></DatePicker>
				<div v-show="!qnFormEdit" style="margin:10px;font-size:16px;font-weight:bold;color:#fff">
					{{ $tools.formatTime(qnForm.endTime,'yyyy-MM-dd hh:mm') }}
				</div>
			</FormItem>


			<FormItem :label="$t('survey.form.description')" 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>
		</Form>

	</div>
</template>
<script>
	import E from 'wangeditor'
	export default {
		props: {
			editItem: {
				default: null,
				type: Object
			},
			editable: {
				default: false,
				type: Boolean
			}
		},
		data(vm) {
			 const _this = this
			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: '',
				publishModel: '0',
				isImmediate: true,
				startTime: '',
				endTime: '',
				qnForm: {
					name: '',
					classes: [],
					endTime: '',
					publishModel: 0,
					rangeTime: [],
					startTime: '',
					description: '',
					isReset: [],
					other: []
				},
				defaultParams: {
					id: "",
					code: "",
					name: "",
					classes: [],
					startTime: 0,
					endTime: 0,
					resource: []
				},
				uploadList: [],
				ruleValidate: {
					name: [{
						required: true,
						message: vm.$t('survey.form.ruleName'),
						trigger: 'blur'
					}],
					description: [{
						required: true,
						message: vm.$t('survey.form.ruleDescription'),
						trigger: 'blur'
					}],
					classes: [{
						required: true,
						message: vm.$t('survey.form.ruleClasses')
					}],
					startTime: [{
						required: true,
						type: 'date',
						message: this.$t('learnActivity.createEv.errTips8'),
						trigger: 'change'
					}],
					endTime: [{
						required: true,
						type: 'date',
						message: this.$t('learnActivity.createEv.errTips9'),
						trigger: 'change'
					}]
				},
				startOption: {
					disabledDate(date) {
					    return date && date.valueOf() < Date.now() - 86400000
					}
				},
				endOption: {
					disabledDate(date) {
						let data = _this.qnForm.startTime ? _this.qnForm.startTime : Date.now()
					    return data && data > date.valueOf() + 86400000
					}
				}
			}
		},
		methods: {
			onClassTypeChange(val) {
				this.qnForm.classes = []
			},

			onChangeSTime(val) {
				let endTime = this.qnForm.endTime || Date.now()
				if (new Date(val).getTime() >= new Date(endTime).getTime()) {
					this.qnForm.endTime = null
				}
			},
			
			onChangeEndTime(val){
				if (val.indexOf('00:00') > 0) {
				    val = val.replace('00:00', '23:59')
					this.qnForm.endTime = val
				}
				let startTime = this.qnForm.startTime || Date.now()
				if (new Date(val).getTime() <= new Date(startTime).getTime()) {
					this.qnForm.endTime = null
					this.ruleValidate.endTime[0].message = this.$t('survey.form.ruleStartTime')
				}else{
					this.ruleValidate.endTime[0].message = this.$t('survey.form.ruleDate')
				}
			},

			/**
			 * 提交新增问卷表单
			 * @param name FormName
			 */
			handleSubmit(name) {
				return new Promise((resolve, reject) => {
					this.$refs[name].validate((valid) => {
						if (valid && this.getSimpleText(this.qnForm.description)) {
							let params = JSON.parse(JSON.stringify(this.defaultParams))
							let target = []
							params.code = this.getCurCode
							// 如果个人问卷的班级是校本班级 那么也要把scope置为school
							params.scope = this.$route.name === 'personalSurvey' && this.classType ===
								'private' ? 'private' : 'school'
							params.name = this.qnForm.name
							params.startTime = !this.isImmediate ? new Date(this.qnForm.startTime)
								.getTime() : -1
							params.endTime = new Date(this.qnForm.endTime).getTime()
							params.description = this.qnForm.description
							// 新增参数
							params.owner = this.$route.name === 'personalSurvey' ? 'teacher' : 'school'
							params.creatorId = this.$store.state.userInfo.TEAMModelId
							params.school = params.scope === 'school' ? this.$store.state.userInfo
								.schoolCode : null

							// 如果是编辑状态 则直接复制ID 如果是新增 则直接赋值新ID
							if (this.isEdit && this.editInfo.id && this.editInfo.code) {
								params.id = this.editInfo.id
								params.createTime = this.editInfo.createTime
							} else {
								params.id = this.$tools.guid()
							}
							params.classes = this.qnForm.classes
							console.log(params)
							resolve(params)
						} else {
							this.$Message.error(this.$t('survey.form.noCompleteTip'))
							reject(500)
						}
					})
				})
			},

			/**
			 * 获取当前教师的所有班级数据
			 * @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) {
							this.$store.dispatch('user/getSchoolProfile').then(schoolProfile => {
								// let schoolClasses =  schoolProfile.school_classes
								r(res.courses)
							}).catch(err => {
								r([])
							})
						} else {
							j(500)
							this.$Message.error(this.$t('survey.getDataFailTip'))
						}
					})
				})
			},

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

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

			},


			/** 
			 * 回显问卷详情
			 * @param item
			 */
			async doRender(item) {
				console.log(item)
				if (!this.classRooms.length) {
					this.classRooms = await this.getClassrooms(this.userInfo.TEAMModelId)
				}
				this.qnForm = {
					name: item.name,
					classes: item.classes || [],
					startTime: item.startTime ? new Date(item.startTime) : '',
					endTime: item.endTime ? new Date(item.endTime) : '',
					description: item.description,
					rangeTime: item.endTime ? [item.startTime, item.endTime] : null
				}
				this.isImmediate = false
				this.currentState = item.state
				this.$nextTick(() => {
					this.curQnItem = JSON.parse(JSON.stringify(item))
					if (item.classes.length) {
						let isExist = this.classRooms.filter(i => i.id === item.classes[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 : this.$t('survey.noMatchData')
				} 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.initSimpleEditor(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>
