<template>
    <div class="component-vote-form">
        <Form ref="voteForm" :model="voteForm" label-position="top" :rules="ruleValidate" :disabled="!voteFormEdit">
            <FormItem label="投票名称" prop="name">
                <Input :class="!voteFormEdit ? 'vote-form-disabled':''" v-model="voteForm.name" placeholder="请输入投票名称"></Input>
            </FormItem>
            <FormItem label="投票对象" prop="targetClassIds">
				<RadioGroup v-model="classType" @on-change="onClassTypeChange" v-if="voteFormEdit">
				        <Radio label="private">个人班级</Radio>
				        <Radio label="school">校本班级</Radio>
				</RadioGroup>
				<div v-if="!voteFormEdit && curVoteItem" class="vote-class">
					<span v-for="item in curVoteItem.targetClassIds" class="vote-class-item">{{ getTargetName(item) }}</span>
				</div>
				<Select multiple v-model="voteForm.targetClassIds" :class="!voteFormEdit ? 'vote-form-disabled':''" placeholder="请选择投票发布对象" not-found-text="暂未创建班级" v-else>
				   	<Option v-for="item in classRooms.filter(i=>i.scope === classType)" :value="item.id" :key="item.id">{{ item.name }}</Option>
				</Select>
            </FormItem>
			
			<FormItem label="起止时间" prop="rangeTime">
			    <!-- <DatePicker type="datetime" :class="!voteFormEdit ? 'vote-form-disabled':''" :editable="isDateEdit" placeholder="请选择投票结束时间" v-model="voteForm.endTime"  :options="endTimeOptions"></DatePicker> -->
				<DatePicker type="datetimerange" transfer @on-change="onChangeRange" format="yyyy-MM-dd HH:mm" :class="!voteFormEdit ? 'vote-form-disabled':''" :editable="isDateEdit" :value="[voteForm.startTime,voteForm.endTime]" placeholder="请选择投票结束时间"></DatePicker>
			</FormItem>

            <FormItem label="投票描述" 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="选项设置" 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" />添加选项</p>
            </FormItem>

            <!--<FormItem label="投票记录" prop="isReset" v-show="editable && isEdit">
                <CheckboxGroup v-model="voteForm.isReset">
                    <Checkbox label="reset">清空投票提交记录</Checkbox>
                </CheckboxGroup>
            </FormItem>-->

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

            <FormItem label="其他" prop="secret">
                <CheckboxGroup v-model="voteForm.secret">
                    <Checkbox label="secret">开启匿名投票</Checkbox>
                </CheckboxGroup>
            </FormItem>

            <FormItem v-show="voteFormEdit">
                <Button type="primary" class="btn-save" @click="handleSubmit('voteForm')" :loading="isBtnLoading">保存</Button>
                <Button @click="handleCancel('voteForm')" class="btn-reset" style="margin-left: 8px">取消</Button>
            </FormItem>
        </Form>
    </div>
</template>
<script>
    import E from 'wangeditor'
    export default {
        props: {
            editItem: {
                type: Object,
                default: null
            },
            editable: {
                type: Boolean,
                default: false
            }
        },
        data() {
            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:[],
                voteForm: {
                    name: '',
                    targetClassIds: [],
                    endTime: '',
                    publishModel:'0',
                    startTime:'',
					rangeTime:null,
                    description: '',
                    isReset: [],
                    selectMax:1,
                    secret: []
                },
                defaultParams: {
                    code: "",
                    name: "",
                    targetClassIds: [],
                    publishModel: "0",
					status:0,
                    startTime: 0,
                    endTime: 0,
                },
                uploadList:[],
				startTimeOptions: {
					disabledDate : date => {
						return date && date.valueOf() < Date.now() - 86400000;
					}
				},
				endTimeOptions: {
					disabledDate : date => {
						return date && date.valueOf() < this.getDisableDays;
					}
				},
                ruleValidate: {
                    name: [
                        { required: true, message: '投票名称不能为空', trigger: 'blur' }
                    ],
                    publishModel: [
                        { required: true, trigger: 'change' }
                    ],
                    description: [
                        { required: true, message: '投票描述不能为空', trigger: 'blur' }
                    ],
                    targetClassIds: [
                        { required: true, message: '投票对象不能为空' }
                    ],
                    endTime: [
                        { required: true, type: 'date', message: '请设置起止时间', trigger: 'change' }
                    ],
                    startTime: [
                        { required: true, type: 'date', message: '请设置起止时间', trigger: 'change' }
                    ],
                    rangeTime: [{
                    	required: true,
                    	message: '日期不能为空!',
                    	trigger: 'change',
                    	type: 'array'
                    }]
                    
                }
            }
        },
		created() {
			/** 获取可选班级列表 */
			this.getClassrooms(this.userInfo.TEAMModelId).then(res => this.classRooms = res)
		},
        methods: {
			onClassTypeChange(val){
				this.voteForm.targetClassIds = []
			},
			onChangeRange(arr) {
				if(arr[0] === ''){
					this.voteForm.rangeTime = null
				}else{
					this.voteForm.startTime = this.getTimestampByString(arr[0])
					this.voteForm.endTime = this.getTimestampByString(arr[1])
					this.voteForm.rangeTime = arr
				}
				console.log(this.rangeTime)
			},
			
			getTimestampByString(str){
				str = str.substring(0,19);
				str = str.replace(/-/g,'/'); //必须把日期'-'转为'/'
				var timestamp = new Date(str).getTime();
				return timestamp
			},
            /**
             * 提交新增投票表单
             * @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) {
						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.getCurScope,
                        params.name = this.voteForm.name
                        params.startTime = this.voteForm.startTime
                        params.endTime = this.voteForm.endTime
                        params.description = this.voteForm.description
                        params.selectMax = this.voteForm.selectMax
                        params.secret = this.voteForm.secret.indexOf('secret') > -1
                        params.options = this.voteOptionsContent
                        if (this.isEdit && this.editInfo.id && this.editInfo.code) {
                            params.id = this.editInfo.id
                        }                                   
                        params.targetClassIds = this.voteForm.targetClassIds
						console.log(params)
						/* 保存BLOB以及COSMOS */
						this.saveorUpdateVote({ vote: params, reset: isReset }).then(res => {
						    this.$Message.success((this.isEdit && this.editInfo.id) ? '修改成功！' : '添加成功！')
						    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('请将信息填写完整')
						}else{
							this.$Message.error('投票选项个数不能为空！')
						}
                    }
                })
            },

            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')
                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.create()
                    })
                } else {
                    this.$Message.warning('最多只有10个选项！')
                }
            },

            /**
             * 获取当前教师的所有班级数据
             * @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
             */
            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: '最多只能上传5个附件'
                    });
                }
                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
             */
            doRender(item) {
				console.log(item)
				this.voteOptionsContent = []
				this.voteOptions = []
				this.initEditors()
                this.voteForm = {
                    name: item.name,
					code:item.code,
                    targetClassIds: item.targetClassIds || [],
                    startTime: item.startTime,
                    endTime: item.endTime,
					rangeTime: item.endTime ? [item.startTime,item.endTime] : null,
                    description: item.description,
                    secret: item.secret ? ['secret'] : [],
                    selectMax: item.selectMax,
                    isReset:[]
                }
                this.descriptionEditor.txt.html(item.description)
                this.voteOptionsContent = item.options
                this.voteOptions = item.options.map((item, index) => index)
                this.$nextTick(() => {
                    this.initEditors()
					if(item.targetClassIds.length){
						let isExist = this.classRooms.filter(i => i.id === item.targetClassIds[0])
						this.classType = isExist ? isExist[0].scope : 'private'
					}
					this.curVoteItem = JSON.parse(JSON.stringify(item))
                })
            },

			/* 根据班级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.initEditors()
            let descriptionEditor = new E(this.$refs.descriptionEditor)
            descriptionEditor.config.onchange = (html) => { this.voteForm.description = html }
			this.$editorTools.initMyEditor(descriptionEditor)
            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>
