<template>
    <div class="component-hw-form">
        <Form ref="hwForm" :model="hwForm" label-position="top" :rules="ruleValidate" :disabled="!hwFormEdit">
            <FormItem label="作业名称" prop="name">
                <Input :class="!hwFormEdit ? 'hw-form-disabled':''" v-model="hwForm.name" placeholder="请输入作业名称"></Input>
            </FormItem>
            <FormItem label="" prop="other">
                <CheckboxGroup v-model="hwForm.other">
                    <Checkbox label="view">开放观摩</Checkbox>
                    <Checkbox label="comment">开放互评</Checkbox>
                </CheckboxGroup>
            </FormItem>
            <FormItem label="作业对象" prop="target">
                <Select multiple v-model="hwForm.target" :class="!hwFormEdit ? 'hw-form-disabled':''" placeholder="请选择作业发布对象">
                    <OptionGroup label="个人班级">
                    	<Option v-for="item in classRooms.filter(i=>i.scope === 'private')" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </OptionGroup>
                    <OptionGroup label="校本班级">
                    	<Option v-for="item in classRooms.filter(i=>i.scope === 'school')" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </OptionGroup>
                </Select>
            </FormItem>
            <FormItem label="发布时间" prop="publishModel">
                <RadioGroup v-model="hwForm.publishModel" v-show="hwFormEdit">
                    <Radio label="0" :disabled="currentState !== 100 && !isAdd">立即发布</Radio>
                    <Radio label="1" :disabled="currentState !== 100 && !isAdd">定时发布</Radio>
                </RadioGroup>

                <DatePicker type="datetime"
                            :class="!hwFormEdit ? 'hw-form-disabled':''"
                            :editable="isDateEdit"
                            :disabled="(currentState !== 100 && !isAdd) || hwForm.publishModel === '0'"
                            placeholder="请选择发布时间"
                            v-model="hwForm.startTime"
                            style="margin-top:10px"></DatePicker>

            </FormItem>

            <FormItem label="结束时间" prop="endTime">
                <DatePicker :class="!hwFormEdit ? 'hw-form-disabled':''" type="datetime" :editable="isDateEdit && hwForm.startTime" placeholder="请选择作业结束时间" v-model="hwForm.endTime" :options="endTimeOptions"></DatePicker>
            </FormItem>
			
			<!-- <FormItem label="起止时间" prop="endTime">
				<DatePicker type="datetimerange" @on-change="onDateRangeChange" placeholder="Select date and time" style="width: 300px"></DatePicker>
			</FormItem> -->

            <FormItem label="作业描述" prop="description">
                <!-- <div ref="descriptionEditor" style="text-align:left" v-show="hwFormEdit"></div> -->
				<Input v-model="hwForm.description" type="textarea" placeholder="" :class="!hwFormEdit ? 'hw-form-disabled':''" v-show="hwFormEdit"/>
                <div v-html="hwForm.description" v-show="!hwFormEdit" style="margin:10px;font-size:16px;font-weight:bold;color:#fff"></div>
                <!--<Input v-model="hwForm.description" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入作业内容描述">--></Input>
            </FormItem>

            <FormItem label="作业附件" prop="attachment" v-show="hwFormEdit" style="position:relative">
                <span class="btn-choose-content" @click="onRelateContent">关联内容</span>
                <UploadFile ref="uploadRef"
                            @successData="getFileUrl"
                            :uploadUrl="uploadUrl"
                            :defaultFileList="defaultFileList"
                            :pathName="userInfo.TEAMModelId.replace('#','')"
                            :quality="1"></UploadFile>
            </FormItem>

            <FormItem label="作业附件" v-show="!hwFormEdit">
                <div v-for="item in defaultFileList" :key="item.id" style="margin:10px 0">
                    <span><Icon type="md-checkmark" color="#1BC6B0" size="20" /></span>
                    <span style="margin-left:10px">{{ item.fileName }}</span>
                </div>
                <span v-show="!defaultFileList.length" style="margin-left:10px">暂无数据</span>
            </FormItem>

            <FormItem label="作业记录" prop="isReset" v-show="editable && isEdit">
                <CheckboxGroup v-model="hwForm.isReset">
                    <Checkbox label="reset">清空作业提交记录</Checkbox>
                </CheckboxGroup>
            </FormItem>

            <FormItem v-show="hwFormEdit">
                <Button type="primary" class="btn-save" @click="handleSubmit('hwForm')" :loading="isBtnLoading">保存</Button>
                <Button @click="handleCancel('hwForm')" class="btn-reset" style="margin-left: 8px">取消</Button>
            </FormItem>
        </Form>

        <!-- 关联内容弹窗 -->
        <Modal v-model="isRelatedContent" width="880" footer-hide class="relate-modal related-modal">
            <div class="modal-header" slot="header">内容关联</div>
            <ChooseContent :showSyllabus="isFalse"
                           :showOther="isFalse"
                           :showQuestion="isFalse"
                           @on-file-change="onSelectFile"></ChooseContent>

            <Button class="modal-btn" :loading="isLoading" @click="onConfirmRelate">确认</Button>
        </Modal>
    </div>
</template>
<script>
    import E from '@/utils/wangEditor.js'
    import UploadFile from '@/common/UploadFile.vue'
    import ChooseContent from '@/components/selflearn/NewChooseContent'
    export default {
        props: {
            editItem: {
                default: null,
                type: Object
            },
            editable: {
                default: false,
                type: Boolean
            }
        },
        components: { UploadFile, ChooseContent },
        data() {
            return {
                isFalse:false,
                isLoading:false,
                isRelatedContent:false,
                isAdd:true,
                isEdit: false,
                isBtnLoading: false,
                isDateEdit: false,
                hwFormEdit:false,
                currentState:0,
                editInfo: null,
                userInfo:this.$store.state.userInfo,
                descriptionEditor: null,
                classRooms: [],
                uploadFileList: [],
                defaultFileList: [],
                relateFileList:[],
                uploadUrl:'',
                defaultConfig: {
                  showLinkImg: false, // 是否展示网络图片链接上传
                  uploadFileName: 'files', // 上传图片后台获取的文件名
                  menus:this.$tools.wangEditorMenuSimple

                },
                hwForm: {
                    name: '',
                    target: [],
                    endTime: '',
                    publishModel:'0',
                    startTime:'',
                    description: '',
                    isReset:[],
                    other: []
                },
                defaultParams: {
                    code: "",
                    name: "",
                    target: [],
                    publishModel: "0",
                    startTime: 0,
                    endTime: 0,
                    resource: []
                },
                uploadList:[],
				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' }
                    ],
                    target: [
                        { required: true, message: '作业对象不能为空' }
                    ],
                    endTime: [
                        { required: true, type: 'date', message: '请设置结束时间', trigger: 'change' }
                    ]
                    
                }
            }
        },
        methods: {
            /**
             * 提交新增作业表单
             * @param name FormName
             */
            handleSubmit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid && this.getSimpleText(this.hwForm.description)) {
                        let params = Object.assign({}, this.defaultParams)
                        let target = []
                        let isReset = this.hwForm.isReset.length > 0
                        params.code = this.userInfo.TEAMModelId
                        params.name = this.hwForm.name
                        params.publishModel = this.hwForm.publishModel
                        params.startTime = this.hwForm.publishModel === '1' ? Math.round(this.hwForm.startTime.getTime()) : new Date().getTime()
                        params.endTime = Math.round(this.hwForm.endTime.getTime())
                        params.description = this.hwForm.description
                        params.other = this.hwForm.other
                        params.resource = this.defaultFileList
                        if (this.isEdit && this.editInfo.id) {
                            params.id = this.editInfo.id
                            params.createTime = this.editInfo.createTime
                        }

                        /** 替换作业对象格式 */
                        this.hwForm.target.forEach(item => {
                            target.push({
                                classroomCode: item,
                                classroomName: this.classRooms.filter(i => i.classroomCode === item)[0].classroomName,
                                code: this.classRooms.filter(i => i.classroomCode === item)[0].scopeCode
                            })
                        })

                        params.target = target
                        this.isBtnLoading = true
                        this.saveorUpdataHw({ homeWork: params, reset: isReset }).then(res => {
                            this.$Message.success((this.isEdit && this.editInfo.id) ? '修改成功！' : '添加成功！')
                            this.hwFormEdit = false
                            this.$emit('onAddSuccess')
                            this.isBtnLoading = false
                        }).catch(error => {
                            console.log(error)
                            this.isBtnLoading = false
                        })
                    } else {
                        this.$Message.error('请将信息填写完整')
                    }
                })
            },

            onRelateContent() {
                this.isRelatedContent = true
            },

            onConfirmRelate() {
                this.isRelatedContent = false
                console.log(this.relateFileList)
                console.log(this.defaultFileList)
                this.defaultFileList = this.defaultFileList.concat(this.relateFileList)
            },


            onSelectFile(val) {
                this.relateFileList = val.files
                
            },

            /**
             * 获取当前教师的所有班级数据
             * @param teacherId 老师的醍摩豆ID
             */
            getClassrooms(teacherId) {
                return new Promise((r, j) => {
                    this.$api.learnActivity.FindClassroomByTeacherId({ code:teacherId }).then(res => {
                        if (!res.error && res.result.data) {
                            r(res.result.data)
                        } else {
                            j(500)
                            this.$Message.error('获取数据失败')
                        }
                    })
                })
                
            },

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

            /**
             * 重置表单
             * @param name
             */
            handleCancel() {
                this.hwFormEdit = false
                this.doRender(this.editInfo)

            },

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

            },

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

            /**
             * 新增作业或者编辑作业
             * @param data
             */
            saveorUpdataHw(data) {
                return new Promise((r, j) => {
                    this.$api.learnActivity.SaveorUpdataHomeWork(data).then(res => {
                        if (!res.error) {
                            r(res.result.data)
                        } else {
                            j(res.error)
                        }
                    })
                })
                
            },

            /**
             * 回显作业详情
             * @param item
             */
            doRender(item) {
                console.log(item)
                
                this.hwForm = {
                    name: item.name,
                    target: item.target.map(item => item.classroomCode),
                    publishModel: item.publishModel,
                    startTime: item.publishModel === '0' ? new Date(new Date().getTime()) : new Date(item.startTime),
                    endTime: item.endTime ? new Date(item.endTime) : '',
                    description: item.description,
                    other: item.other,
                    isReset:[]
                }
                this.currentState = item.state
                this.defaultFileList = item.resource
                this.defaultFileList = JSON.parse(JSON.stringify(item.resource))
                // this.descriptionEditor.txt.html(item.description)
                //this.uploadFileList = item.resource.length ? item.resource : []
            },


            getFileUrl(file) { // 获取文件地址
                //if (this.isEdit && this.uploadFileList.length) return
                //this.uploadFileList.push({
                //    fileName: file.fileName,
                //    type: file.type,
                //    size: file.size,
                //    blobUrl: file.blobUrl,
                //    sha1Code: file.sha1Code,
                //    compressUrl: file.compressUrl
                //})
                //console.log(this.uploadFileList)
            },
        },
        mounted() {

            /** 获取可选班级列表 */
            this.getClassrooms(this.userInfo.TEAMModelId).then(res => this.classRooms = res)


            /** 初始化作业详情的富文本编辑器 */
            // let descriptionEditor = new E(this.$refs.descriptionEditor)
            // descriptionEditor.customConfig = this.defaultConfig
            // descriptionEditor.customConfig.onchange = (html) => { this.hwForm.description = html }
            // descriptionEditor.create()
            // this.descriptionEditor = descriptionEditor
        },
        computed:{
			getDisableDays(){
				return this.hwForm.startTime
			}
		},
		watch: {
            editItem: {
                handler(newValue) {
                    /** 编辑回显 */
                    if (newValue) {
                        this.doRender(JSON.parse(JSON.stringify(newValue)))
                        this.isEdit = true
                        this.editInfo = newValue
                    } else {
                        /** 新增 */
                        this.handleReset('hwForm')
                        this.isEdit = false
                        this.editInfo = null
                    }
                },
                deep: true
            }
        }
    }
</script>

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