<template>
	<div class="component-vote-form">
		<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">
				<RadioGroup v-model="classType" @on-change="onClassTypeChange" v-if="voteFormEdit">
					<Radio label="private" v-if="getCurScope === 'private'">{{ $t('vote.form.privateClass') }}</Radio>
					<Radio label="school">{{ $t('vote.form.schoolClass') }}</Radio>
				</RadioGroup>
				<div v-if="!voteFormEdit && curVoteItem" class="vote-class">
					<span v-for="item in curVoteItem.classes" class="vote-class-item">{{ getTargetName(item) }}</span>
				</div>
				<Select multiple v-model="voteForm.classes" :class="!voteFormEdit ? 'vote-form-disabled':''" :placeholder="$t('vote.form.targetPlace')"
				 :not-found-text="$t('vote.form.noFoundText')" 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('vote.form.time')" prop="rangeTime">
				<DatePicker type="datetimerange" transfer @on-change="onChangeRange" @on-open-change="onOpenChange" :options="options3" format="yyyy-MM-dd HH:mm"
				 :class="!voteFormEdit ? 'vote-form-disabled':''" :editable="isDateEdit" :value="[voteForm.startTime,voteForm.endTime]"
				 :placeholder="$t('vote.form.endTimePlace')"></DatePicker>
			</FormItem> -->
			
			<FormItem :label="$t('learnActivity.createEv.publishType')" prop="publishModel" v-show="voteFormEdit">
				<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;color:#fff">
					{{ $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;color:#fff">
					{{ $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;color:#fff"></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="color:#fff;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;color:#fff;display: inline-block;vertical-align: middle;"></div>
						</div>
					</div>
				</div>

				<p style="float:right;color:#BDBDBD;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">
					<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 {
				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'
					}],
					classes: [{
						required: true,
						message: vm.$t('vote.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.voteForm.startTime ? _this.voteForm.startTime : Date.now()
					    return data && data > date.valueOf() + 86400000
					}
				}
			}
		},
		created() {
			/** 获取可选班级列表 */
			this.getClassrooms(this.userInfo.TEAMModelId).then(res => {
				console.log(res)
				this.classRooms = res
			})
		},
		methods: {
			onClassTypeChange(val) {
				this.voteForm.classes = []
			},
			
			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
				this.$refs[name].validate(async (valid) => {
					if (valid && this.getSimpleText(this.voteForm.description) && this.voteOptionsContent.length) {
						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 params = Object.assign({}, this.defaultParams)
							let target = []
							let fileName = this.$tools.guid()
							let isReset = this.voteForm.isReset.length > 0
							params.code = this.getCurCode
							params.scope = this.$route.name === 'personalVote' && this.classType === 'private' ? '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.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 = this.$route.name === 'personalVote' ? 'teacher' : 'school'
							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
							
							if (this.isEdit && this.editInfo.id && this.editInfo.code) {
								params.id = this.editInfo.id
							}
							params.classes = this.voteForm.classes
							console.log(params)
							/* 保存BLOB以及COSMOS */
							this.saveorUpdateVote(params).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 (this.voteOptionsContent.length) {
							this.$Message.error(this.$t('vote.form.noCompleteTip'))
						} else {
							this.$Message.error(this.$t('vote.form.noOptionTip'))
						}
					}
				})
			},

			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) => {
					this.$api.learnActivity.SaveorUpdataVote(data).then(res => {
						if (!res.error) {
							r(res)
						} else {
							j(res.error)
						}
					})
				})

			},

			/**
			 * 回显投票详情
			 * @param item
			 */
			async doRender(item) {
				console.log(item)
				if(!this.classRooms.length){
					this.classRooms = await this.getClassrooms(this.userInfo.TEAMModelId)
				}
				this.voteForm = null
				this.voteOptionsContent = []
				this.voteOptions = []
				this.initEditors()
				this.voteForm = {
					name: item.name,
					code: item.code,
					classes: item.classes || [],
					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 = false
				this.descriptionEditor.txt.html(item.description)
				this.voteOptionsContent = item.options
				this.voteOptions = item.options.map((item, index) => index)
				
				this.$nextTick(() => {
					this.initEditors()
					if (item.classes.length) {
						let isExist = this.classRooms.filter(i => i.id === item.classes[0])
						this.classType = isExist ? isExist[0].scope : 'private'
					}
					this.curVoteItem = JSON.parse(JSON.stringify(item))
					this.$refs.voteForm.validateField('classes')
					this.$refs.voteForm.validateField('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('vote.form.noMatchDataTip')
				} else {
					this.getClassrooms(this.userInfo.TEAMModelId).then(res => {
						return res.filter(i => i.id === classId)[0].name
					})
				}
			}
		},
		mounted() {
			//this.initEditors()
			let descriptionEditor = new E(this.$refs.descriptionEditor)
			descriptionEditor.config.onchange = (html) => {
				this.voteForm.description = html
			}
			this.$editorTools.initMyEditor(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: {
			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>
