<template>
	<div class="component-vote-form light-iview-form light-el-input">
		<Form ref="voteForm" :model="voteForm" label-position="top" :rules="ruleValidate" :disabled="!voteFormEdit"
			hide-required-mark>
			<FormItem :label="$t('vote.form.name')" prop="name">
				<Input :class="!voteFormEdit ? 'vote-form-disabled':''" v-model="voteForm.name"
					:placeholder="$t('vote.form.namePlace')"></Input>
			</FormItem>
			<FormItem :label="$t('vote.form.target')" prop="classes">
				<!-- 预览状态 -->
				<div v-if="!voteFormEdit && curVoteItem" class="vote-class">
					<span v-for="item in classNameArr" class="vote-class-item">{{ item.name }}</span>
				</div>
				<!-- 编辑状态 -->
				<div v-else>
					<!-- 区级选学校 -->
					<div v-if="isAreaVote">
						<el-cascader size="small" :show-all-levels="false" clearable filterable v-model="schoolTarget"
							:options="csOptions" :props="props" @change="treeChange" style="width:100%;">
						</el-cascader>
					</div>
					<div v-else>
						<!-- 校级选教研组或者学生名单 -->
						<BaseClassSelect :classes="classTargets" :type="targetType" @onChange="onTargetChange"
							ref="classSelectRef" v-if="getCurScope === 'school' && curVoteItem"></BaseClassSelect>
						<BaseClassSelectPri :classes="classTargets" :scope="classType" @onChange="onTargetChange"
							ref="classSelectRef" v-if="getCurScope === 'private' && curVoteItem"></BaseClassSelectPri>
					</div>
				</div>
			</FormItem>
			<FormItem :label="$t('learnActivity.createEv.publishType')" prop="publishModel" v-show="voteFormEdit && !isAreaVote">
				<Checkbox v-model="isImmediate">{{$t('global.publishType1')}}</Checkbox>
			</FormItem>
			<FormItem :label="$t('learnActivity.createEv.startTime')" v-if="!isImmediate || !voteFormEdit"
				prop="startTime">
				<DatePicker v-show="voteFormEdit" type="datetime" :options="startOption" format="yyyy/MM/dd HH:mm"
					v-model="voteForm.startTime" split-panels :placeholder="$t('learnActivity.createEv.sTimeHolder')"
					style="width:100%" @on-change="onChangeSTime"></DatePicker>
				<div v-show="!voteFormEdit" style="margin:10px;font-size:16px;font-weight:bold;">
					{{ $tools.formatTime(voteForm.startTime,'yyyy-MM-dd hh:mm') }}
				</div>
			</FormItem>
			<FormItem :label="$t('learnActivity.createEv.endTime')" prop="endTime">
				<DatePicker v-show="voteFormEdit" type="datetime" :options="endOption" format="yyyy/MM/dd HH:mm"
					v-model="voteForm.endTime" split-panels @on-change="onChangeEndTime"
					:placeholder="$t('learnActivity.createEv.eTimeHolder')" style="width:100%"></DatePicker>
				<div v-show="!voteFormEdit" style="margin:10px;font-size:16px;font-weight:bold;">
					{{ $tools.formatTime(voteForm.endTime,'yyyy-MM-dd hh:mm') }}
				</div>
			</FormItem>

			<FormItem :label="$t('vote.form.description')" prop="description">
				<div ref="descriptionEditor" style="text-align:left" v-show="voteFormEdit"></div>
				<div v-html="voteForm.description" v-show="!voteFormEdit"
					style="margin:10px;font-size:16px;font-weight:bold;"></div>
			</FormItem>

			<FormItem :label="$t('vote.form.optionSetting')" prop="attachment" ref="optionsBox">
				<div v-if="voteOptions.length">
					<div v-for="(item,index) in voteOptions" :key="index" class="option-editor-wrap">
						<div v-show="voteFormEdit" style="display: flex;">
							<span class="option-order">{{ index + 1 }}
								<Icon type="md-trash" @click="deleteOption(index)" />
							</span>
							<div :ref="'voteOption'+index" style="text-align:left" class="option-editor"
								@click="optionClick(index)"></div>
						</div>
						<div v-show="!voteFormEdit">
							<span style="margin-left: 10px;">{{ index + 1 }} .</span>
							<div v-html="(voteOptionsContent[index]) ? voteOptionsContent[index].value : ''"
								v-show="!voteFormEdit"
								style="margin:10px;font-size:16px;font-weight:bold;display: inline-block;vertical-align: middle;">
							</div>
						</div>
					</div>
				</div>

				<p style="float:right;color:#757575;cursor:pointer" @click="onAddOption" v-show="voteFormEdit">
					<Icon type="md-add" />{{ $t('vote.form.addOption') }}
				</p>
			</FormItem>

			<FormItem :label="$t('vote.form.times')">
				<Select v-model="voteForm.times" :class="!voteFormEdit ? 'vote-form-disabled':''">
					<Option value="once">{{ $t('vote.form.once') }}</Option>
					<Option value="day">{{ $t('vote.form.day') }}</Option>
					<Option value="week">{{ $t('vote.form.week') }}</Option>
					<Option value="month">{{ $t('vote.form.month') }}</Option>
					<Option value="year">{{ $t('vote.form.year') }}</Option>
				</Select>
			</FormItem>

			<FormItem :label="$t('vote.form.selectNum')" prop="selectMax">
				<!--<Input :class="!voteFormEdit ? 'vote-form-disabled':''" v-model="voteForm.count" placeholder="请输入投票名称"></Input>-->
				<InputNumber :min="1" v-model="voteForm.selectMax"></InputNumber>
			</FormItem>

			<FormItem :label="$t('vote.form.other')" prop="secret">
				<CheckboxGroup v-model="voteForm.secret">
					<Checkbox label="secret">{{ $t('vote.form.openSecret') }}</Checkbox>
				</CheckboxGroup>
				<CheckboxGroup v-model="voteForm.repeat" v-if="voteForm.selectMax > 1">
					<Checkbox label="repeat">{{ $t('vote.form.openRepeat') }}</Checkbox>
				</CheckboxGroup>
			</FormItem>

			<FormItem v-show="voteFormEdit">
				<Button type="primary" class="btn-save" @click="handleSubmit('voteForm')"
					:loading="isBtnLoading">{{ $t('vote.form.save') }}</Button>
				<Button @click="handleCancel('voteForm')" class="btn-reset"
					style="margin-left: 8px">{{ $t('vote.form.cancel') }}</Button>
			</FormItem>
		</Form>
	</div>
</template>
<script>
	import E from 'wangeditor'
	export default {
		props: {
			editItem: {
				type: Object,
				default: null
			},
			editable: {
				type: Boolean,
				default: false
			}
		},
		data(vm) {
			const _this = this
			return {
				props: {
					multiple: true,
					value: 'id',
					label: 'name',
				},
				schoolTarget: [],
				classTargets: [],
				classNameArr: [],
				classType: 'private',
				curVoteItem: null,
				isAdd: true,
				isEdit: false,
				isBtnLoading: false,
				isDateEdit: false,
				voteFormEdit: true,
				currentState: 0,
				editInfo: null,
				userInfo: this.$store.state.userInfo,
				descriptionEditor: null,
				classRooms: [],
				uploadFileList: [],
				uploadUrl: '',
				defaultConfig: {
					uploadImgShowBase64: true,
					menus: this.$tools.wangEditorMenuSimple,
				},
				voteOptions: [...new Array(2).keys()], // 默认四个选项,
				voteOptionsContent: [],
				isImmediate: true,
				voteForm: {
					name: '',
					classes: [],
					endTime: '',
					publishModel: '0',
					startTime: '',
					rangeTime: null,
					description: '',
					isReset: [],
					selectMax: 1,
					secret: [],
					repeat: [],
					times: 'once',
					voteNum: '1'
				},
				defaultParams: {
					code: "",
					name: "",
					classes: [],
					publishModel: "0",
					status: 0,
					startTime: 0,
					endTime: 0,
				},
				uploadList: [],
				options3: {
					disabledDate: (date) => {
						//这里写上自己的逻辑，返回true，表示当前日期需要设置为不可选
						return date && date.valueOf() < Date.now() - 86400000;
					}
				},
				ruleValidate: {
					name: [{
						required: true,
						message: vm.$t('vote.form.ruleName'),
						trigger: 'blur'
					}],
					// description: [{
					// 	// required: true,
					// 	message: vm.$t('vote.form.ruleDescription'),
					// 	trigger: 'blur'
					// }],
					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.voteForm.startTime ? _this.voteForm.startTime : Date.now()
						return data && data > date.valueOf() + 86400000
					}
				},
				classIds: [],
				groupList: [],
				targetType: '',
				schList: [],
				csOptions: [],
				areaId: sessionStorage.getItem('areaId'),
			}
		},
		created() {
			/** 获取可选班级列表 */
			this.getClassrooms(this.userInfo.TEAMModelId).then(res => {
				console.log(res)
				this.classRooms = res
			})

			this.findResearchList()
			if (this.isAreaVote) {
				this.getAreaTargets()
			}
		},
		methods: {
			treeChange(data) {
				console.log('选择数据', this.schoolTarget)
			},
			getAreaTargets() {
				this.$api.ability.findAreaGroup({
					id: this.areaId
				}).then(
					res => {
						if (res.gr && res.gr.length) {
							this.schList = res.gr
							this.csOptions = []
							res.gr.forEach(sItem => {
								let i = {
									id: sItem.id,
									name: sItem.sname,
									children: []
								}
								sItem.name.forEach((gItem,gIndex) => {
									i.children.push({
										id: sItem.sname + '-' + gItem,
										name: sItem.sname + '-' + gItem,
									})
								})
								if (!i.children.length) {
									i.children.push({
										id: sItem.sname + '-' + '所有老师（未分组）',
										name: sItem.sname + '-' + '所有老师（未分组）'
									})
								}
								this.csOptions.push(i)
							})
						}
						console.log(this.schList)

					},
					err => {
						console.log(err)
					}
				)
			},
			onClassTypeChange(val) {
				this.voteForm.classes = []
			},

			onTargetChange(data) {
				this.voteForm.classes = this.getCurScope === 'school' ? data : data.map(i => i.split('/')[1])
				this.voteForm.targets = this.getCurScope === 'school' ? [] : data
			},

			onChangeSTime(val) {
				let endTime = this.voteForm.endTime || Date.now()
				if (new Date(val).getTime() >= new Date(endTime).getTime()) {
					this.voteForm.endTime = null
				}
			},

			onChangeEndTime(val) {
				if (val.indexOf('00:00') > 0) {
					val = val.replace('00:00', '23:59')
					this.voteForm.endTime = val
				}
			},
			/**
			 * 提交新增投票表单
			 * @param name FormName
			 */
			async handleSubmit(name) {
				this.isBtnLoading = true
				let hasTargets = (!this.isAreaVote && this.voteForm.classes.length) || (this.isAreaVote && this.schoolTarget.length)
				let optionComplete = this.voteOptionsContent.length && this.voteOptionsContent.every(i => i.value !== '')
				this.$refs[name].validate(async (valid) => {
					if (valid && this.getSimpleText(this.voteForm.description) && optionComplete && hasTargets) {
						if (this.voteForm.selectMax > this.voteOptionsContent.length && this.voteForm
							.repeat.indexOf('repeat') === -1) {
							this.$Message.warning(this.$t('vote.optionMaxTip'))
							this.isBtnLoading = false
						} else {
							if (this.voteForm.selectMax === 1) {
								this.voteForm.repeat = []
							}
							console.log(this.voteForm)
							let classSelectScope = this.isAreaVote ? 'school' : this.$refs.classSelectRef
								.evaluationInfo.scope
							let isSchoolClass = this.isAreaVote ? false : (this.$refs.classSelectRef.evaluationInfo.scope === 'school' && this.$refs.classSelectRef.privateClassType === 'school')
							let params = Object.assign({}, this.defaultParams)
							let areaParams = null
							let target = []
							let fileName = this.$tools.guid()
							let isReset = this.voteForm.isReset.length > 0
							let isPersonal = this.$route.name === 'personalVote' && classSelectScope ===
								'private'
							let isSchool = this.$route.name === 'manageVote'

							params.code = this.getCurCode
							params.scope = isPersonal ? 'private' : 'school'
							params.name = this.voteForm.name
							params.startTime = !this.isImmediate ? new Date(this.voteForm.startTime).getTime() : -1
							params.endTime = new Date(this.voteForm.endTime).getTime()
							params.description = this.voteForm.description
							params.targets = this.voteForm.targets
							params.selectMax = this.voteForm.selectMax || 1
							params.secret = this.voteForm.secret.indexOf('secret') > -1
							params.repeat = this.voteForm.repeat.indexOf('repeat') > -1
							params.options = this.voteOptionsContent
							// 新增参数
							params.owner = isSchool ? 'school' : 'teacher'
							params.creatorId = this.$store.state.userInfo.TEAMModelId
							params.voteNum = this.voteForm.selectMax
							params.times = this.voteForm.times
							params.school = params.scope === 'school' ? this.$store.state.userInfo.schoolCode : null
							params.tchLists = []
							params.classes = []
							params.stuLists = []
							if (this.isEdit && this.editInfo.id && this.editInfo.code) {
								params.id = this.editInfo.id
							}

							// 如果是发布的区级投票 则需要修改保存参数
							if (this.curVoteItem.owner === 'area') {
								let schArr = [...new Set(this.schoolTarget.map(i => i[0]))]
								let para = []
								schArr.forEach((i, index) => {
									para.push({
										sId: i,
										sName: this.schList.find(j => j.id === i).sname,
										gName: [],
										gId:[]
									})
									// 如果是区级活动 需要拼接学校加教研组信息
									this.schoolTarget.forEach(j => {
										if (j[0] === i) {
											let groupName = j[1].split('-')[1]
											if (groupName === '所有老师（未分组）') {
												para[index].gName = []
												para[index].gId = ['default']
											} else {
												let curSch = this.schList.find(sch => sch.id === i)
												let groupId = curSch.gId[curSch.name.indexOf(groupName)]
												para[index].gName.push(groupName)
												para[index].gId.push(groupId)
											}
										}
									})
								})
								delete this.voteForm.classes
								delete this.voteForm.targets
								delete this.voteForm.teachers
								delete this.voteForm.stuLists
								areaParams = {
									"id": this.areaId,
									"para": para,
									"vote": params
								}
							}else{
								// 如果是校本投票 则需要进一步确定发布对象是教研组还是学生名单
								if (isSchool && this.$refs.classSelectRef.targetType === 'research') {
									params.tchLists = this.voteForm.classes
									params.targetType = 'research'
								} else if (isSchoolClass) {
									params.classes = this.voteForm.classes
									params.targetType = 'student'
								} else {
									params.stuLists = this.voteForm.classes
									params.targetType = 'student'
								}
							}
							
							let finalParams = this.isAreaVote ? areaParams : params
							console.log('提交的投票对象', finalParams)
							/* 保存BLOB以及COSMOS */
							this.saveorUpdateVote(finalParams).then(res => {
								this.$Message.success((this.isEdit && this.editInfo.id) ? this.$t(
									'vote.form.editSuc') : this.$t(
									'vote.form.addSuc'))
								this.$emit('onAddSuccess')
								this.isBtnLoading = false
							}).catch(error => {
								this.isBtnLoading = false
								console.log(error)
							})
						}
					} else {
						this.isBtnLoading = false
						if (!optionComplete) {
							this.$Message.error(this.$t('vote.form.noOptionTip'))
						} else if (!hasTargets) {
							this.$Message.error(this.$t('vote.form.ruleClasses'))
						} else if(!this.getSimpleText(this.voteForm.description)){
							this.$Message.error('投票详情不能为空！')
						} else {
							this.$Message.error(this.$t('vote.form.noCompleteTip'))
						}
					}
				})
			},

			initEditors() {
				console.log('进入编辑起初始化')
				console.log(this.voteOptions)
				console.log(this.voteOptionsContent)
				this.$nextTick(() => {
					// Editor默认配置
					if (this.voteOptions.length > 0) {
						this.voteOptions.forEach((item, i) => {
							let that = this
							let editor = new E(that.$refs['voteOption' + i][0])
							this.$editorTools.initSimpleEditor(editor)
							// 选项编辑器失焦隐藏工具栏
							editor.config.onblur = function() {
								let allToolbars = document.getElementsByClassName('option-editor')
								for (let i = 0; i < allToolbars.length; i++) {
									if (allToolbars[i].children.length) {
										allToolbars[i].children[0].style.visibility = 'hidden'
									}
								}
							}

							// 选项编辑器内容发生变化时
							editor.config.onchange = (html) => {
								let key = String.fromCharCode(64 + parseInt(i + 1))
								let codeArr = this.voteOptionsContent.map(item => item.code)
								// 如果已经编辑过则 修改选项内容
								if (codeArr.indexOf(key) !== -1) {
									this.voteOptionsContent[codeArr.indexOf(key)].value = html
								} else { // 否则创建新选项
									let option = {
										code: key,
										value: html
									}
									this.voteOptionsContent.push(option)
								}
							}
							editor.create()

							// 如果是编辑状态 则将选项内容回显
							if (this.editInfo) {
								editor.txt.html(this.voteOptionsContent[i].value)
							}
						})
					}
				})
			},

			// 模拟选项聚焦事件
			optionClick(index) {
				console.log(index)
				let allToolbars = document.getElementsByClassName('option-editor')
				console.log(allToolbars)
				let that = this
				for (let i = 0; i < allToolbars.length; i++) {
					allToolbars[i].children[0].style.visibility = 'hidden'
				}
				setTimeout(function() {
					let currentToolBar = that.$refs['voteOption' + index][0].children[0]
					if (currentToolBar.clientHeight > 50) {
						currentToolBar.style.top = '-90px'
					}
					currentToolBar.style.visibility = 'visible'
				}, 100)
			},

			// 删除选项
			deleteOption(index) {
				this.voteOptions.splice(index, 1)
				this.voteOptionsContent.splice(index, 1)
				console.log(this.voteOptions)
				console.log(this.voteOptionsContent)
				this.$nextTick(() => {
					this.initEditors()
				})
			},

			// 添加选项
			onAddOption() {
				let that = this
				let newIndex = this.voteOptions.length
				let optionsLength = this.voteOptions.length
				console.log(this.voteOptionsContent)
				if (optionsLength < 10) {
					this.voteOptions.push(newIndex)
					this.$nextTick(() => {
						let editor = new E(that.$refs['voteOption' + newIndex][0])
						this.$editorTools.initSimpleEditor(editor)
						editor.config.onchange = (html) => {
							let key = String.fromCharCode(64 + parseInt(newIndex + 1))
							let codeArr = this.voteOptionsContent.map(item => item.code)
							// 如果已经编辑过则 修改选项内容
							if (codeArr.indexOf(key) !== -1) {
								this.voteOptionsContent[codeArr.indexOf(key)].value = html
							} else { // 否则创建新选项
								let option = {
									code: key,
									value: html
								}
								this.voteOptionsContent.push(option)
							}
						}
						editor.config.onblur = function() {
							let allToolbars = document.getElementsByClassName('option-editor')
							for (let i = 0; i < allToolbars.length; i++) {
								if (allToolbars[i].children.length) {
									allToolbars[i].children[0].style.visibility = 'hidden'
								}
							}
						}
						editor.create()
					})
				} else {
					this.$Message.warning(this.$t('vote.form.optionNumsTip'))
				}
			},

			/**
			 * 获取当前教师的所有班级数据
			 * @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
								// console.log(schoolClasses)
								r(res.courses)
							}).catch(err => {
								r([])
							})

						} else {
							j(500)
							this.$Message.error(this.$t('vote.form.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 name
			 */
			handleCancel() {
				// 如果是新增的问卷点击取消编辑 则需要进行特殊处理
				if (!this.curVoteItem.id) {
					this.$emit('onCancelVote')
				}
				this.voteFormEdit = false
				this.doRender(this.editInfo)

			},

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

			/**
			 * 新增投票或者编辑投票
			 * @param data
			 */
			saveorUpdateVote(data) {
				return new Promise((r, j) => {
					if (this.curVoteItem.owner === 'school') {
						this.$api.learnActivity.SaveorUpdataVote(data).then(res => {
							if (!res.error) {
								r(res)
							} else {
								j(res.error)
							}
						}).catch(e => j(e))
					} else {
						this.$api.ability.saveAreaVote(data).then(res => {
							if (!res.error) {
								r(res)
							} else {
								j(res.error)
							}
						}).catch(e => j(e))
					}
				})

			},

			/**
			 * 回显投票详情
			 * @param item
			 */
			async doRender(item) {
				console.log('需要渲染的投票对象', item)
				
				// 如果是区级投票
				if(this.isAreaVote){
					this.classNameArr = item.targets.map(i => {
						return {
							name:i
						}
					})
				}else{
					if (item.targetType === 'research') {
						console.log(this.groupList);
						let groupNameArr = []
						item.tchLists.forEach(i => {
							let findObj = this.groupList.find(j => j.id === i)
							if (findObj) {
								groupNameArr.push(findObj)
							}
						})
						this.classNameArr = groupNameArr
					} else {
						this.classNameArr = item.classes.length ? await this.getClassNameByIds(item.classes) : item
							.stuLists.length ? await this.getClassNameByIds(item.stuLists) : []
					}
				}
				
				console.log(this.classNameArr);
				
				
				this.classType = item.classes.length ? 'school' : 'private'
				this.classTargets = item.targetType === 'research' ? item.tchLists : this.getCurScope === 'school' ?
					item.classes : item.targets
				this.targetType = item.targetType
				console.log(this.classNameArr)
				this.voteForm = null
				this.voteOptionsContent = []
				this.voteOptions = []
				this.initEditors()
				this.voteForm = {
					name: item.name,
					code: item.code,
					targets: item.targets,
					classes: item.targetType === 'research' ? item.tchLists : item.classes.length ? item.classes :
						item.stuLists,
					startTime: item.startTime ? new Date(item.startTime) : '',
					endTime: item.endTime ? new Date(item.endTime) : '',
					description: item.description,
					secret: item.secret ? ['secret'] : [],
					repeat: item.repeat ? ['repeat'] : [],
					selectMax: item.voteNum || 1,
					times: item.times || 'once',
					voteNum: item.voteNum || 1,
					isReset: []
				}
				this.isImmediate = item.isImmediate || false
				this.descriptionEditor.txt.html(item.description)
				this.voteOptionsContent = item.options
				this.voteOptions = item.options.map((item, index) => index)

				this.$nextTick(() => {
					this.initEditors()
					this.curVoteItem = JSON.parse(JSON.stringify(item))
					this.$refs.voteForm.validateField('name')
					this.$refs.voteForm.validateField('classes')
					this.$refs.voteForm.validateField('description')
				})
			},

			/* 根据班级ID集合换取班级名称 */
			getClassNameByIds(ids) {
				return new Promise((r, j) => {
					this.$api.learnActivity.getClassNameByIds({
						classes: ids,
						school: this.$store.state.userInfo.schoolCode
					}).then(res => {
						if (!res.error) {
							r(res.classInfos)
						}
					}).catch(e => {
						j(e)
					})
				})
			},

			/* 根据班级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('vote.form.noMatchDataTip')
				// } else {
				// 	this.getClassrooms(this.userInfo.TEAMModelId).then(res => {
				// 		return res.filter(i => i.id === classId)[0].name
				// 	})
				// }
				console.log(classId);
				return this.classNameArr.find(i => i.id === classId) ? this.classNameArr.find(i => i.id === classId).name :
					this.$t('vote.form.noMatchDataTip')
			},

			/* 查找学校检验组信息 */
			findResearchList() {
				this.$api.schoolUser.getResearchGroup({
					code: this.$store.state.userInfo.schoolCode,
					scope: 'school'
				}).then(res => {
					this.groupList = res.tchLists
				})
			},
		},
		mounted() {
			//this.initEditors()
			let descriptionEditor = new E(this.$refs.descriptionEditor)
			descriptionEditor.config.onchange = (html) => {
				this.voteForm.description = html
			}
			this.$editorTools.initSimpleEditor(descriptionEditor, this)
			descriptionEditor.create()
			this.descriptionEditor = descriptionEditor


			if (this.editItem && this.editItem.name) {
				console.log(this.editItem)
				this.editInfo = JSON.parse(JSON.stringify(this.editItem))
				this.doRender(this.editInfo)
			} else {
				this.voteOptions = [...new Array(2).keys()]
				this.initEditors()
			}

		},
		computed: {
			isAreaVote() {
				return this.$route.name === 'manageAreaVote'
			},
			getDisableDays() {
				return this.voteForm.startTime
			},
			getCurCode() {
				return this.$route.name === 'personalVote' ? this.$store.state.userInfo.TEAMModelId : this.$store.state
					.userInfo.schoolCode
			},
			getCurScope() {
				return this.$route.name === 'personalVote' ? 'private' : 'school'
			},
		},
		watch: {
			editItem: {
				handler(newValue) {
					/** 编辑回显 */
					if (newValue) {
						console.log(newValue)
						this.doRender(JSON.parse(JSON.stringify(newValue)))
						this.isEdit = true
						this.editInfo = JSON.parse(JSON.stringify(newValue))

					} else {
						/** 新增 */
						console.log(newValue)
						this.handleReset('voteForm')
						this.isEdit = false
						this.editInfo = null
					}
				},
				// deep: true,
				// immediate:true
			}
		}
	}
</script>

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