<template>
	<div class="component-qn-form light-iview-form light-el-input">
		<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" v-if="getCurScope === '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 classNameArr" class="vote-class-item">{{ item.name }}</span>
				</div>
				<div v-else>
					<div v-if="isAreaSurvey">
						<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' && curQnItem"></BaseClassSelect>
						<BaseClassSelectPri :classes="classTargets" :scope="classType" @onChange="onTargetChange"
							ref="classSelectRef" v-if="getCurScope === 'private' && curQnItem"></BaseClassSelectPri>
					</div>
				</div>
			</FormItem>

			<FormItem :label="$t('learnActivity.createEv.publishType')" prop="publishModel" v-show="qnFormEdit && !isAreaSurvey">
				<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;">
					{{ $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;">
					{{ $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;"></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 {
				props: {
					multiple: true,
					value: 'id',
					label: 'name',
				},
				schoolTarget: [],
				classTargets: [],
				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: [],
					stuLists: [],
					startTime: 0,
					endTime: 0,
					resource: []
				},
				classNameArr: [],
				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
					}
				},
				classIds: [],
				groupList: [],
				targetType: '',
				schList: [],
				csOptions: [],
				areaId: sessionStorage.getItem('areaId'),
			}
		},
		created() {
			if (this.isAreaSurvey) {
				this.getAreaTargets()
			} else {
				this.findResearchList()
			}
		},
		methods: {
			treeChange(data) {
				console.log('选择数据', this.schoolTarget)
			},
			getAreaTargets() {
				this.$api.ability.findAreaGroup({
					id: this.areaId
				}).then(
					res => {
						console.log(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 => {
									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)
							})
						}

					},
					err => {
						console.log(err)
					}
				)
			},
			/* 查找学校检验组信息 */
			findResearchList() {
				this.$api.schoolUser.getResearchGroup({
					code: this.$store.state.userInfo.schoolCode,
					scope: 'school'
				}).then(res => {
					this.groupList = res.tchLists
				})
			},

			onClassTypeChange(val) {
				this.qnForm.classes = []
			},

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

			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) => {
						let hasTargets = (!this.isAreaSurvey && this.qnForm.classes.length) || (this.isAreaSurvey && this.schoolTarget.length)
						if (valid && this.getSimpleText(this.qnForm.description) && hasTargets) {
							let params = JSON.parse(JSON.stringify(this.defaultParams))
							let areaParams = null
							let target = []
							let classSelectScope = this.isAreaSurvey ? 'school' : this.$refs.classSelectRef.evaluationInfo.scope
							let isSchoolClass = this.isAreaSurvey ? false : this.$refs.classSelectRef.evaluationInfo.scope ===
								'school' && this.$refs.classSelectRef.privateClassType === 'school'
							let isPersonal = this.$route.name === 'personalSurvey' && classSelectScope ===
								'private'
							let isSchool = this.$route.name === 'manageQuestionnaire'
							params.code = this.getCurCode
							// 如果个人问卷的班级是校本班级 那么也要把scope置为school
							params.scope = isPersonal ? '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.targets = this.qnForm.targets
							// 新增参数
							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

							params.tchLists = []
							params.classes = []
							params.stuLists = []
							// 如果是编辑状态 则直接复制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()
							}
							
							// 如果是发布的区级投票 则需要修改保存参数
							if (this.isAreaSurvey) {
								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.qnForm.classes
								delete this.qnForm.targets
								delete this.qnForm.teachers
								delete this.qnForm.stuLists
								areaParams = {
									"id": this.areaId,
									"para": para,
									"survey": params
								}
							}else{
								// 如果是校本投票 则需要进一步确定发布对象是教研组还是学生名单
								if (isSchool && this.$refs.classSelectRef.targetType === 'research') {
									params.tchLists = this.qnForm.classes
									params.targetType = 'research'
								} else if (isSchoolClass) {
									params.classes = this.qnForm.classes
									params.targetType = 'student'
								} else {
									params.stuLists = this.qnForm.classes
									params.targetType = 'student'
								}
							}
							let finalParams = this.isAreaSurvey ? areaParams : params
							console.log(finalParams)
							resolve(finalParams)
						} else {
							if (!hasTargets) {
								this.$Message.error(this.$t('survey.form.ruleClasses'))
							}else if(!this.getSimpleText(this.qnForm.description)){
								this.$Message.error('问卷描述不能为空！')
							} 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()

			},

			/* 根据班级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)
					})
				})
			},
			/** 
			 * 回显问卷详情
			 * @param item
			 */
			async doRender(item) {
				console.log(item)
				// 如果是区级投票
				if(this.isAreaSurvey){
					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.classTargets = item.targetType === 'research' ? item.tchLists : this.getCurScope === 'school' ?
					item.classes : item.targets
				this.classType = item.classes.length ? 'school' : 'private'
				this.targetType = item.targetType
				this.qnForm = {
					name: item.name,
					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,
					rangeTime: item.endTime ? [item.startTime, item.endTime] : null
				}
				console.log(this.qnForm)
				this.isImmediate = item.isImmediate || false
				this.currentState = item.state
				this.$nextTick(() => {
					this.curQnItem = JSON.parse(JSON.stringify(item))
					this.$refs.qnForm.validateField('name')
					this.$refs.qnForm.validateField('classes')
					this.$refs.qnForm.validateField('description')
				})
				this.descriptionEditor.txt.html(item.description)
			},

			/* 根据班级ID获取班级名称 */
			getTargetName(classId) {
				return this.classNameArr.find(i => i.id === classId) ? this.classNameArr.find(i => i.id === classId).name :
					this.$t('vote.form.noMatchDataTip')
			}

		},
		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'
			},
			isAreaSurvey() {
				return this.$route.name === 'manageAreaQuestionnaire'
			},
		},
		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>
