<template>
    <div class="component-hw-table">
        <Table border size='small' ref="selection" :columns="isSimpleColumns ? simpleColumns : columns" :data="tableData" stripe></Table>

        <!-- 评分以及评价弹窗 -->
        <Modal v-model="setScoreModal"
               class-name="score-modal"
               title="教师点评"
               footer-hide
               width="600px">
            <div class="score-modal-container">
                <div class="score-modal-item">
                    <span>评分</span>
                    <InputNumber :max="100" :min="1" v-model="currentScore"></InputNumber>
                </div>
                <div class="score-modal-item">
                    <span style="vertical-align: top;margin-top:6px;display: inline-block;">评语</span>
                    <Input v-model="currentComment" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入评语" />
                    <Checkbox v-model="isSaveComment">保存为常用评语</Checkbox>
                    <div class="used-comments">
                        <p>常用评语</p>
                        <Select v-model="currentUsedComment" @on-change="onUsedCommentChange" filterable allow-create @on-create="onCreateComment">
                            <Option v-for="(item,index) in usedCommentList" :value="item" :key="index" :label="item">
								<span>{{ item }}</span>
								<span style="float:right;color:#ccc" @click.stop="onDeleteComment(index)"><Icon type="md-trash" size="20" color="#7b7b7b"/></span>
							</Option>
                        </Select>
                    </div>

                </div>
                <div class="score-modal-item">
                    <Button @click="onSetScore" :loading="isScoreLoading">提交</Button>
                </div>
            </div> 
        </Modal>

        <!-- 查看互评弹窗 -->
        <Modal v-model="mutualEvaluationModal"
               class-name="score-modal mutual-modal"
               title="查看互评"
               footer-hide
               width="700px">
            <div v-if="commentList.length === 0">
                <EmptyData :top="0"></EmptyData>
            </div>
            <div class="mutual-comment-list" v-else>
                <vuescroll>
                    <div style="padding:0 20px 50px 20px">
                        <span>互评分数</span>
                        <div class="mutual-comment-rate">
                            <Rate v-model="currentRateValue" allow-half icon="md-star" disabled />
                            <span class="mutual-score">{{currentRateValue}}</span>
                        </div>
                        <p>全部评论</p>
                        <div class="comment-item" v-for="(item,index) in commentList" :key="index">
                            <div class="comment-item-left">
                                <img src="@/assets/icon/icon_header.png" width="40" />
                                <p class="comment-item-left-name">{{ item.fromId }}</p>
                                <p class="comment-item-left-level">{{ index + 1 }} 楼</p>
                            </div>
                            <div class="comment-item-right">
                                <span class="comment-item-right-content">{{ item.comment }}</span>
                                <span class="comment-item-right-time">发布时间：{{ $tools.formatTime(item.createTime) }}</span>
                                <span class="comment-item-right-score">
                                    <span style="margin-right:10px;display: inline-block;margin-top: 5px;">评分:</span>
                                    <Rate v-model="item.score" icon="md-star" allow-half disabled />
                                    <span style="margin:0 10px;display: inline-block;margin-top: 5px;color:#E9A607">{{ parseInt(item.score) === item.score ? item.score + '.0' : item.score }}</span>
                                </span>
                            </div>
                        </div>
                    </div>
                </vuescroll>
            </div>
        </Modal>

        <!-- 下载附件弹窗 -->
        <Modal v-model="downloadModal"
               class-name="score-modal download-modal component-hw-table"
               title="提交详情"
               footer-hide
               width="600px">

            <p class="download-title">提交内容</p>
            <div class="download-hw-content" v-html="currentAnswer || '暂无提交内容'"></div>
            <p class="download-title">附件内容</p>
            <Table border size='small'
                   ref="fileTable"
                   :columns="fileColumns"
                   :data="currentFileList"
                   @on-selection-change="onFileSelectChange"
                   stripe></Table>
            <div class="download-btn-wrap">
                <Button :disabled="downloadList.length !== 1" type="info" @click="onDownloadFile(downloadList)">下载所选文件</Button>
                <BasePackage v-show="downloadList.length > 1" text='打包下载' :urlList="downloadList" :student="currentStudent"></BasePackage>
            </div>
        </Modal>


    </div>
</template>
<script>
    export default {
		props:{
			studentsList:{
				type:Array,
				default:[]
			},
			hwId:{
				type:String,
				default:null
			},
			isSimpleColumns:{
				type:Boolean,
				default:true
			}
		},
        data() {
            return {
                setScoreModal: false,
                downloadModal: false,
                sasString:'',
                mutualEvaluationModal: false,
                isSaveComment: false,
                currentUsedComment:'',
                isScoreLoading: false,
                currentStudent: null,
                currentHw: null,
                currentScore: 100,
                currentComment: '',
                currentFileList: [],
                currentAnswer:'',
                currentRateValue:0,
                downloadList: [],
                filterData:[],
                usedCommentList: [],
                fileColumns: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center'
                    },
                    {
                        title: '文件名',
                        key: 'fileName'
                    },
                    {
                        title: '大小',
                        width: 100,
                        key: 'size',
                        render: (h, params) => {
                            return h('span', this.$tools.bytesToSize(params.row.size))
                        }
                    }
                ],
                columns: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center'
                    },
                    {
                        title: '姓名',
                        width: 100,
                        key: 'name'
                    },
                    {
                        title: '班级',
                        width: 100,
                        filters: [],
                        filterMultiple: false,
                        filterMethod (val, row) {
                            return row.classroomName === val
                        },
                        render: (h, params) => {
                            return h('span', params.row.classroomName)
                        },
                    },
                    {
                        title: '缴交',
                        width: 80,
                        align: 'center',
                        render: (h, params) => {
                            return !params.row.submissionBool ?
                                h('span', '——') :
                                h('Icon', {
                                    props: {
                                        type: 'md-checkmark',
                                        color: '#07A856',
                                        size: 24

                                    },
                                    domProps: {
                                        title: '已提交'
                                    }
                                })
                        }
                    },
                    {
                        title: '提交时间',
                        key: 'submitTime',
                        width: 180,
                        render: (h, params) => {
                            return h('span', params.row.submissionBool ? this.$tools.formatTime(params.row.submissionTime,'yyyy-MM-dd hh:mm') : '——')
                        },
                    },
                    {
                        title: '分数',
                        width: 80,
                        render: (h, params) => {
                            let that = this
                            return params.row.submissionBool  ?
                                h('span', {
                                    domProps: {
                                        title: '评分'
                                    },
                                    style: {
                                        cursor: 'pointer',
                                        color: '#07A856',
                                        fontWeight:'bold'
                                    },
                                    on: {
                                        click: function () {
											that.curStuIndex = params.index
                                            that.currentStudent = params.row
                                            that.currentScore = params.row.score
                                            that.currentComment = params.row.teacherComments ? params.row.teacherComments.comment : ''
											that.getLatestComments()
                                            that.setScoreModal = true
                                        }
                                    },
                                }, params.row.score) : 
                                h('Icon', {
                                    props: {
                                        type: 'md-create',
                                        size:18
                                    },
                                    style: {
                                        cursor:'pointer'
                                    },
                                    domProps: {
                                        title: '评分'
                                    },
                                    on: {
                                        click: function () {
                                            that.$Message.warning('暂未提交作业！无法进行评分！')
                                        }
                                    },
                                })

                        }
                    },
                    {
                        title: '评语',
                        render: (h, params) => {
                            let that = this
                            return h('span', {
                                domProps: {
                                    //title: '下载作业'
                                },
                                style: {
                                    cursor: 'pointer',
                                    //color: '#07A856',
                                    fontWeight:'bold'
                                },
                                on: {
                                    click: function () {
										that.curStuIndex = params.index
                                        that.currentStudent = params.row
                                        that.currentScore = params.row.score
                                        that.currentComment = params.row.teacherComments ? params.row.teacherComments.comment : ''
										that.getLatestComments()
                                        that.setScoreModal = true
                                    }
                                },
                            }, params.row.teacherComments ? params.row.teacherComments.comment : '')
                        }
                    },
                    {
                        title: '操作',
                        key: '',
                        width: 150,
                        render: (h, params) => {
                            let that = this
                            return h('div',
                                {
                                    domProps: {
                                        className: 'table-tools-icon'
                                    }
                                }, [
                                h('Icon', {
                                    props: {
                                        type: 'ios-list-box-outline',
                                    },
                                    domProps: {
                                        title: '下载作业'
                                    },
                                    on: {
                                        click: function () {
                                            if (params.row.submissionBool) {
                                                that.currentStudent = params.row
                                                that.downloadModal = true
                                                that.currentFileList = params.row.content.length ? params.row.content[0].resource : []
                                                that.currentAnswer = params.row.content.length ? params.row.content[0].answers : ''
                                            } else {
                                                that.$Message.warning('暂无提交内容')
                                            }
                                            
                                        }
                                    },
                                }),
                                h('Icon', {
                                    props: {
                                        type: 'ios-chatbubbles-outline'
                                    },
                                    domProps: {
                                        title: '查看互评'
                                    },
                                    on: {
                                        click: function () {
                                            that.mutualEvaluationModal = true
                                            that.commentList = params.row.studentComments
                                            if (that.commentList.length) {
                                                let nums = params.row.studentComments.map(i => i.score)
                                                that.currentRateValue = (nums.reduce((a, b) => a + b) / nums.length).toFixed(1)
                                            }
                                            
                                        }
                                    },
                                })
                            ]);
                        }
                    }
                ],
				simpleColumns: [
				    {
				        type: 'selection',
				        width: 60,
				        align: 'center'
				    },
				    {
				        title: '姓名',
				        width: 100,
				        key: 'name'
				    },
				    {
				        title: '班级',
				        filters: [],
				        filterMultiple: false,
				        filterMethod (val, row) {
				            return row.classroomName === val
				        },
				        render: (h, params) => {
				            return h('span', params.row.classroomName)
				        },
				    },
				    {
				        title: '缴交',
				        align: 'center',
				        render: (h, params) => {
				            return !params.row.submissionBool ?
				                h('span', '——') :
				                h('Icon', {
				                    props: {
				                        type: 'md-checkmark',
				                        color: '#07A856',
				                        size: 24
				
				                    },
				                    domProps: {
				                        title: '已提交'
				                    }
				                })
				        }
				    },
				    {
				        title: '提交时间',
				        key: 'submitTime',
				        render: (h, params) => {
				            return h('span', params.row.submissionBool ? this.$tools.formatTime(params.row.submissionTime,'yyyy-MM-dd hh:mm') : '——')
				        },
				    }
				],
                tableData: [],
				curStuIndex:null,
                commentList: []
            }
        },
        created() {
        },
        methods: {
            /**
             * 全选操作
             * @param status
             */
            handleSelectAll(status) {
                this.$refs.selection.selectAll(status);
            },

            /**
             * 文件表格选择回调
             * @param list
             */
            onFileSelectChange(list) {
                this.downloadList = list.map(item => item.blobUrl)
            },


            /**
             * 查询当前教师的评语罐头
             * @param teacherId
             */
            findTeacherComments(teacherId) {
                return new Promise((r, j) => {
                    this.$api.learnActivity.FindTeacherComments({ code: teacherId }).then(res => {
                        if (!res.error && res.result.data) {
                            r(res.result.data)
                        } else {
                            j(500)
                        }
                    })
                })
            },
			

            /**
             * 常用评语切换
             * @param val
             */
            onUsedCommentChange(val) {
                this.currentComment = this.usedCommentList.length && val !== undefined  ? val : ''
            },

            /**
             * 选择常用评语
             * @param e
             */
            onChooseComment(e) {
                this.currentComment = e.target.innerText
            },

            /** 设置作业点评分数 */
            onSetScore() {
                if (!this.currentComment || !this.currentScore) {
                    this.$Message.warning('请填写完整！')
                } else {
                    this.isScoreLoading = true

                    let scoreParams = {
                        studentId: this.currentStudent.code,
                        homeWorkId: this.hwId,
                        TEAMModelId: this.$store.state.userInfo.TEAMModelId,
                        score: this.currentScore,
                        comments: this.currentComment
                    }

                    if (this.isSaveComment) {
                        let params = {
                            TEAMModelId: this.$store.state.userInfo.TEAMModelId,
                            comment: this.currentComment
                        }

                        this.onSaveComment(params).then(res => {
                            this.usedCommentList = res.comment
                            this.$Message.success('保存成功')
                        })
                    }

                    /* 同时发送评分以及评语请求 */
                    this.onApiScore(scoreParams).then(res => {
						this.currentStudent.score = res.score
						this.currentStudent.teacherComments = res.tchCmt
						// 打分之后 更新最新的 分数以及评语
                        this.$set(this.tableData, this.curStuIndex, this.currentStudent)
                        this.$Message.success('点评成功！')
                        this.isScoreLoading = false
                        this.setScoreModal = false
                        this.currentUsedComment = ''
                    }).catch(err => {
                        console.log(err)
                    })

                }
            },

            /**
             * 老师评分请求接口
             * @param params
             */
            onApiScore(params) {
                return new Promise((r, j) => {
                    this.$api.learnActivity.TeacherScoring(params).then(res => {
                        if (!res.error && res.result.data) {
                            r(res.result.data)
                        } else {
                            j(500)
                        }
                    })
                })
            },

            /**
             * 保存为常用评语
             * @param params
             */
            onSaveComment(params) {
                return new Promise((r, j) => {
                    this.$api.learnActivity.SaveOrUpdateTeacherComments(params).then(res => {
                        if (!res.error && res.result.data) {
                            r(res.result.data)
                        } else {
                            j(500)
                        }
                    })
                })
            },
			
			/* 回车添加新的评语到教师的评语罐头 */
			onCreateComment(val){
				if(this.usedCommentList.indexOf(val) === -1){
					this.onSaveComment({
					    TEAMModelId: this.$store.state.userInfo.TEAMModelId,
					    comment: val
					}).then(res => {
					    this.usedCommentList = res.comment
						this.currentUsedComment = ''
						this.currentComment = val
					    this.$Message.success('保存成功')
					})
				}else{
					this.currentComment = val
				}
			},
			
			/* 删除教师的某个评语操作 */
			onDeleteComment(index){
				this.$Modal.confirm({
				    title: '删除常用评语',
				    content: '<p>确认删除该评语？</p>',
				    okText: '确认',
				    cancelText: '取消',
				    onOk: () => {
						this.usedCommentList.splice(index,1)
						this.$api.learnActivity.UpsertTeacherComments({ code: this.$store.state.userInfo.TEAMModelId,comment:this.usedCommentList }).then(res => {
						    if (!res.error && res.result.data) {
						        this.usedCommentList = res.result.data.comment
								this.$Message.success('删除成功！')
						    }
						})
						
				    }
				})
			},

           

            /**
             * 下载附件
             * @param blobUrl
             */
            onDownloadFile(downloadList) {
                downloadList.forEach(async item => {
					let fileSas = await this.$tools.getFileSas(item)
					console.log(fileSas)
                    window.location.href = item + '?' +  fileSas.sas
                })
            },

            /**
             * 获取blob授权信息
             * */
            getSasStr() {
                this.$api.blob.getContainerSAS().then(
                    (res) => {
                        if (res.error == null) {
                            this.sasString = res.result.data.SAS
                        } else {
                            this.$Message.error('API error!')
                        }
                    },
                    (err) => {
                        this.$Message.error('API error!')
                    }
                )
            },
			
			// 获取教师最新的常用评语
			getLatestComments(){
				this.currentUsedComment = ''
				this.findTeacherComments(this.$store.state.userInfo.TEAMModelId).then(res => {
				    this.usedCommentList = res.length ? res[0].comment : []
				})
			}

        },

        mounted() {
            this.getLatestComments()
        },
        watch: {
            studentsList: {
                handler(newValue) {
                    /** 编辑回显 */
                    if (newValue) {
                        this.tableData = newValue
                        this.filterData = []
                        let list = newValue.map(item => item.classroomName)
                        list.forEach(i => {
                            if (this.filterData.map(j => j.value).indexOf(i) === -1) {
                                this.filterData.push({ 
									value :i,
									label :i
								})
                            }
                        })
                        this.columns[2].filters = this.filterData
                    }
                },
                deep: true
            }
        }
    }
</script>

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