<template>
    <div class="ev-scoring dark-iview-table">
        <vuescroll ref="score-main-warp">
            <SimpleAnalysis :examInfo="examInfo" v-show="!showTest" :overviewInfo="overviewInfo"></SimpleAnalysis>
            <div class="ev-target-box dark-iview-select">
                <span class="filter-label" v-show="examInfo.scope == 'school'">{{$t('learnActivity.score.gradeLabel')}}</span>
                <Select filterable v-model="chooseGrade" class="filter-select" size="small" v-show="examInfo.scope == 'school'" style="margin-right:5px" transfer>
                    <Option v-for="(item,index) in examInfo.grades" :value="item.id" :key="index">{{ item.name }}</Option>
                </Select>
                <span>{{$t('learnActivity.score.classLabel')}}</span>
                <Select filterable v-model="chooseClass" class="filter-select" style="width:140px;" @on-change="getClassStudent" size="small" transfer>
                    <Option v-for="(item,index) in classList" :value="item.id" :key="index">{{ item.name }}</Option>
                </Select>
                <span class="filter-label" v-show="examInfo.scope == 'school'">{{$t('learnActivity.score.subjectLabel')}}</span>
                <Select filterable v-model="chooseSubject" class="filter-select" size="small" @on-change="getCurPaper" v-show="examInfo.scope == 'school'" transfer>
                    <Option v-for="(item,index) in examInfo.subjects" :value="item.id" :key="index">{{ item.name }}</Option>
                </Select>
                <span style="margin-left:5px" v-show="showTest">{{$t('learnActivity.score.stuLabel')}}</span>
                <Select filterable v-model="chooseStudent.id" label-in-value class="filter-select" style="width:140px;" size="small" clearable @on-change="setStuInfo" v-show="showTest" transfer>
                    <Option v-for="(item,index) in students" :value="item.id" :key="index">
                        <span class="select-status-tag" :style="{'background':item.status == 1 ? '#ed4014' : item.status == 2 ? '#ff9900' : '#19be6b'}"></span>
                        {{ item.name }}
                    </Option>
                </Select>
                <span v-show="showTest" class="common-icon-text" style=" float: right; margin-right: 25px;" @click="toggleScoreStatus" icon="md-apps">
                    <Icon :custom="showTest ? 'iconfont icon-table':'iconfont icon-scoring'" style="margin-right:5px;" />
                    {{showTest ? $t('learnActivity.score.scoreView'):$t('learnActivity.score.scoring')}}
                </span>
            </div>
            <div class="scoring-main-wrap">
                <Table v-show="!showTest" class="score-box" border :columns="tableColumn" :data="tableData" :loading="tableLoading" @on-sort-change="onSortChange" :no-data-text="$t('learnActivity.score.classNoStu')">
                    <template slot-scope="{ row,index }" :slot="'qu'+qIndex" v-for="(item,qIndex) in quCount">
                        <div :key="'qu'+qIndex" @click="getStuScore(row,qIndex)" style="cursor:pointer;">
                            <span @click="noAnswer" v-if="row.data[qIndex] == -1 && row.status == 1">- -</span>
                            <Icon size="20" type="ios-create-outline" color="#2db7f5" v-else-if="row.data[qIndex] == -1 && row.status !== 1" />
                            <span style="color:#2db7f5;" v-else>{{row.data[qIndex]}}</span>
                        </div>
                    </template>
                    <!-- <template slot-scope="{ row,index }" slot="total">
                        <strong>{{getcount(studentScore[row._index].data)}}</strong>
                    </template> -->
                    <!-- 1: 未作答 2：未评分 3：已评分 -->
                    <template slot-scope="{ row,index }" slot="status">
                        <span class="stu-status-tag" @click="getStuScore(row,0)" :style="{'background':row.status == 1 ? '#c5c8ce' : row.status == 2 ? '#ff9900' : '#19be6b', 'cursor':row.status == 1 ? 'text':'pointer'}">
                            {{row.status == 1 ? $t('learnActivity.score.status1') : row.status == 2 ? $t('learnActivity.score.status2') : $t('learnActivity.score.status3')}}
                        </span>
                    </template>
                    <Loading slot="loading" :top="-50"></Loading>
                </Table>
                <!-- 分页 -->
                <div class="page-wrap dark-ivew-select">
                    <Page show-total size="small" :current="currentPage" :total="studentScore.length" :page-size="pageSize" :page-size-opts="pageSizeOpts" @on-change="pageChange" @on-page-size-change="pageSizeChange" show-sizer />
                </div>
                <div class="dark-iview-table scoring-handle-box" v-show="showTest">
                    <PaperScore ref="paperScore" :defaultIndex="defaultIndex" :examId="examInfo.id" :paper="paperInfo" :studentAnswer="chooseStudent" :subjectId="chooseSubject" @nextStu="getNextStu" style="color:#515a6e;"></PaperScore>
                    <Loading :top="200" type="1" style="text-align:center" v-show="dataLoading"></Loading>
                </div>
            </div>
        </vuescroll>
    </div>
</template>
<script>
import PaperScore from "./PaperScore.vue";
import SimpleAnalysis from "./SimpleAnalysis.vue";
export default {
    props: {
        examInfo: {
            type: Object,
            default: () => {
                return {}
            }
        }
    },
    components: {
        PaperScore, SimpleAnalysis
    },
    data() {
        return {
            originData: [],
            studentScore: [],
            tableData: [],
            currentPage: 1,
            pageSize: 10,
            pageSizeOpts: [5, 10, 20, 30, 40],
            overviewInfo: {
                total: 0,
                answered: 0,
                noAnswer: 0,
                scored: 0,
                noScore: 0
            },
            defaultIndex: 0,
            tableLoading: false,
            showTest: false, //是否评分
            studentData: [],
            dataLoading: false,
            chooseGrade: "",
            chooseClass: "",
            chooseSubject: "",
            chooseStudent: {
                id: "",
                name: "",
                scores: [],
                answers: []
            },
            scoreList: [
                {
                    title: this.$t('learnActivity.score.column1'),
                    key: "name",
                    fixed: "left",
                    align: "center",
                    minWidth: 150,
                },
                {
                    title: this.$t('learnActivity.score.column2'),
                    key: "total",
                    align: "center",
                    sortable: true,
                    fixed: "right",
                    width: 100
                },
                {
                    title: this.$t('learnActivity.score.column3'),
                    slot: "status",
                    align: "center",
                    fixed: "right",
                    width: 100,
                }
            ],
            tableColumn: [],

            quCount: [],
            paperInfo: {},
            students: [],
            privClassList: undefined,
            routerScope: ''

        }
    },
    methods: {
        // 排序操作
        onSortChange(data) {
            let order = data.order // 当前排序方式 升序、降序、正常
            let key = data.key // 当前排序依据
            switch (order) {
                case 'asc':
                    this.studentScore = this.originData.sort((a, b) => { return Number(a[key]) - Number(b[key]) })
                    break
                case 'desc':
                    this.studentScore = this.originData.sort((a, b) => { return Number(b[key]) - Number(a[key]) })
                    break
                case 'normal':
                    this.studentScore = this.students
                    break
                default:
                    break
            }
            console.log('1', this.studentScore[0].name)
            console.log(2, this.originData[0].name)
            this.pageChange(1)
        },
        // 页面size变化
        pageSizeChange(val) {
            this.pageSize = val
            this.pageChange(1)
        },
        // 分页页面变化
        pageChange(page) {
            let start = this.pageSize * (page - 1)
            let end = this.pageSize * page
            this.currentPage = page
            this.tableData = this.studentScore.slice(start, end)
        },
        toggleScoreStatus() {
            this.$refs['paperScore'].isComplete = false
            this.showTest = !this.showTest
        },
        getNextStu() {
            let flag = false
            for (let index in this.paperInfo[this.chooseClass].studentAns.studentScores) {
                if (this.paperInfo[this.chooseClass].studentAns.studentScores[index].indexOf(-1) >= 0) {
                    if (this.paperInfo[this.chooseClass].studentAns.studentAnswers[index].length) {
                        flag = true
                        this.chooseStudent.id = this.paperInfo[this.chooseClass].studentAns.studentIds[index]
                        let curStu = this.students.find(item => {
                            return item.id == this.chooseStudent.id
                        })
                        if (curStu) this.chooseStudent.name = curStu.name
                        this.chooseStudent.answers = this.paperInfo[this.chooseClass].studentAns.studentAnswers[index]
                        this.chooseStudent.scores = this.paperInfo[this.chooseClass].studentAns.studentScores[index]
                        this.chooseStudent.classId = this.chooseClass
                        this.chooseStudent.status = false
                        this.$refs['paperScore'].isComplete = false
                        break
                    }
                }
            }
            if (!flag) {
                this.showTest = false
                this.$Message.warning(this.$t('learnActivity.score.finishScore'))
            }
        },
        //学生未作答提示
        noAnswer() {
            this.$Message.warning(this.$t('learnActivity.score.unableScore'))
        },
        //获取当前学科的试卷信息
        getCurPaper() {
            let paperInfo = this.examInfo.papers.find((item) => {
                return item.subjectId == this.chooseSubject;
            });
            this.paperInfo = this._.cloneDeep(paperInfo)
            this.getClassStudent();
        },
        //点击学生题号前往评分页面
        getStuScore(data, qIndex) {
            if (data.status == 2 || data.status == 3) {
                this.$refs['paperScore'].isComplete = false
                this.showTest = true
                this.defaultIndex = qIndex
                this.chooseStudent.id = data.id
                this.chooseStudent.name = data.name
                this.chooseStudent.classId = this.chooseClass
                let answerIndex = this.paperInfo[this.chooseClass].studentAns.studentIds.indexOf(data.id)
                if (answerIndex >= 0) {
                    this.chooseStudent["scores"] = this.paperInfo[this.chooseClass].studentAns.studentScores[answerIndex]
                    this.chooseStudent["answers"] = this.paperInfo[this.chooseClass].studentAns.studentAnswers[answerIndex]
                    this.chooseStudent["status"] = false
                }
            }
        },
        //获取当前学生信息
        setStuInfo(data) {
            if (data) {
                this.chooseStudent.name = data.label;
                this.chooseStudent.classId = this.chooseClass
                let answerIndex = this.paperInfo[this.chooseClass].studentAns.studentIds.indexOf(data.value);
                if (answerIndex >= 0) {
                    this.chooseStudent["scores"] = this.paperInfo[this.chooseClass].studentAns.studentScores[answerIndex];
                    this.chooseStudent["answers"] = this.paperInfo[this.chooseClass].studentAns.studentAnswers[answerIndex];
                    this.chooseStudent["status"] = false;
                }
            }
        },
        //分数求和
        getcount(arr) {
            return arr.reduce((total, item) => {
                if (item !== -1) {
                    return total + item;
                } else {
                    return total;
                }
            }, 0);
        },
        // 获取班级名单
        getClassStudent() {
            this.showTest = false
            this.tableLoading = true
            if (!this.chooseClass) return;
            let requestData = {
                id: this.chooseClass,
                scope: this.examInfo.scope == 'private' ? 'private' : 'school',
                school_code: this.examInfo.scope == 'private' ? this.$store.state.userInfo.TEAMModelId : this.$store.state.userInfo.schoolCode,
            };
            this.$api.schoolSetting.getClassroomStudent(requestData).then((res) => {
                if (!res.error) {
                    if (!this.paperInfo[this.chooseClass]) {
                        this.paperInfo[this.chooseClass] = {}
                    }
                    this.$set(this.paperInfo[this.chooseClass], "students", res.classrooms[0])
                    this.students = []
                    this.tableData = []
                    this.studentScore = []
                    this.getStudentAnswer();
                } else {
                    this.$Message.error("API ERROR!");
                }
            })
        },
        //计算总览数据
        calcOverView(data) {
            //计算已作答未作答
            this.overviewInfo.noAnswer = 0
            data.studentAnswers.forEach(item => {
                if (item.length == 0) {
                    this.overviewInfo.noAnswer++
                }
            })
            this.overviewInfo.answered = data.studentAnswers.length - this.overviewInfo.noAnswer
            // 计算已评分未评分
            this.overviewInfo.noScore = 0
            data.studentScores.forEach(item => {
                let flag = item.find(item => {
                    return item == -1
                })
                if (flag) {
                    this.overviewInfo.noScore++
                }
            })
            this.overviewInfo.scored = data.studentScores.length - this.overviewInfo.noScore
            // 班级总人数
            this.overviewInfo.total = data.studentIds.length
        },
        getStudentAnswer() {
            this.dataLoading = true
            let requestData = {
                id: this.examInfo.id,
                code: this.examInfo.scope == 'school' ? this.$store.state.user.schoolCode : this.$store.state.userInfo.TEAMModelId,
                subjectId: this.chooseSubject,
                classId: this.chooseClass,
            };
            this.$api.learnActivity.FindAllStudent(requestData).then(
                (res) => {
                    if (res.examClassResults) {
                        this.paperInfo[this.chooseClass]["studentAns"] = res.examClassResults[0];
                        this.setTableData();
                        if (res.examClassResults[0]) {
                            this.calcOverView(res.examClassResults[0])
                        }

                    }
                },
                (err) => {
                    this.$Message.error("API ERROR!");
                }
            ).finally(() => {
                setTimeout(() => {
                    this.dataLoading = false
                    this.tableLoading = false
                }, 500);
            });
        },
        //初始化表单数据
        setTableData() {
            if (this.paperInfo[this.chooseClass] && this.paperInfo[this.chooseClass]["students"] && this.paperInfo[this.chooseClass]["studentAns"]) {
                let studentData = this.paperInfo[this.chooseClass]["students"]
                let studentAns = this.paperInfo[this.chooseClass]["studentAns"]
                this.studentScore = []
                this.tableColumn = [...this.scoreList]
                this.quCount = studentAns.studentScores[0] ? studentAns.studentScores[0].length : 0
                for (let i = 0; i < this.quCount; i++) {
                    let data = {
                        title: "Q" + (i + 1),
                        slot: "qu" + i,
                        align: "center",
                        minWidth: 65,
                    }
                    this.tableColumn.push(data);
                }
                let ans = []
                for (let i = 0; i < studentAns.studentIds.length; i++) {
                    for (let k = 0; k < studentData.students.length; k++) {
                        let score = {}
                        if (studentAns.studentIds[i] == studentData.students[k].id) {
                            score.name = studentData.students[k].name
                            score.id = studentAns.studentIds[i]
                            score.data = studentAns.studentScores[i]
                            score.total = this.getcount(score.data)
                            if (studentAns.studentAnswers[i].length == 0) {//学生未作答
                                score.status = 1
                            } else if (studentAns.studentScores[i].indexOf(-1) >= 0) {//已作答，未评分
                                score.status = 2
                            } else {//已批改
                                score.status = 3
                            }
                            this.studentScore.push(score)
                        }
                    }
                }
                this.originData = this._.cloneDeep(this.studentScore)
                this.students = this._.cloneDeep(this.studentScore)
                this.pageChange(1)
                if (ans.length) {
                    for (let k = 0; k < this.paperInfo.papers.item.length; k++) {
                        this.$set(
                            this.paperInfo.papers.item[k],
                            "answerData",
                            ans[k]
                        );
                        this.$set(
                            this.paperInfo.papers.item[k],
                            "stuScore",
                            score[k]
                        );
                    }
                }
            }

        },
        getBack(data) {
            if (data == "1") {
                this.getClassStudent();
            }
            this.showTest = false;
        },
        //获取单个学生作答数据
        getStudentInfo(data, index) {
            this.dataLoading = true;
            if (this.studentInfo !== undefined) {
                let filData = "";
                filData = this.studentInfo.id;
                let ans = [];
                let score = [];
                for (let i = 0; i < this.classDatas.studentIds.length; i++) {
                    if (this.classDatas.studentIds[i] == filData) {
                        ans = this.classDatas.studentAnswers[i];
                        score = this.classDatas.studentScores[i];
                    }
                }
                if (ans.length) {
                    for (let k = 0; k < this.paperInfo.papers.item.length; k++) {
                        this.$set(this.paperInfo.papers.item[k], "answerData", ans[k]);
                        this.$set(this.paperInfo.papers.item[k], "stuScore", score[k]);
                    }
                }
                this.dataLoading = false;
            } else {
                this.dataLoading = false;
                this.$Message.warning(this.$t('learnActivity.score.stStuWarning'));
            }
            this.selectIndex = index;
        },
        getAnswer(data) {
            //处理学生作答信息
            let listArr = [];
            data.forEach(function (el, index) {
                for (var i = 0; i < listArr.length; i++) {
                    if (listArr[i].group == el.group) {
                        listArr[i].listInfo.push(el);
                        return;
                    }
                }
                listArr.push({
                    group: el.group,
                    listInfo: [el],
                });
            });
            return listArr;
        },
    },
    watch: {
        examInfo: {
            handler(n, o) {
                this.privClassList = undefined
                if (n.subjects && n.subjects.length) {
                    this.chooseSubject = n.subjects[0].id;
                }

                if (n.grades && n.grades.length) {
                    this.chooseGrade = n.grades[0].id;
                }
                if (n.papers && n.papers.length) {
                    if (n.scope == 'school') {
                        let res = n.papers.find((item) => {
                            return item.subjectId == this.chooseSubject;
                        });
                        this.paperInfo = res ? this._.cloneDeep(res) : {};
                    } else {
                        this.paperInfo = n.papers[0]
                    }
                } else {
                    this.paperInfo = {};
                }
            },
            deep: true,
        },
        classList: {
            handler(n, o) {
                if (n && n.length) {
                    this.chooseClass = n[0].id;
                    this.getClassStudent();
                } else {
                    this.chooseClass = undefined
                }
            },
            deep: true,
        },
        chooseStudent: {
            handler(n, o) {
                if (n.id) {
                    let curStu = this.studentScore.find(item => {
                        return item.id == n.id
                    })
                    if (curStu.status == 2) {
                        let flag = n.scores.find(item => {
                            return item == -1
                        })
                        if (!flag) {
                            curStu.status = 3
                            this.overviewInfo.noScore--
                            this.overviewInfo.scored++
                        }
                    }
                }
            },
            deep: true
        }
    },
    computed: {
        classList() {
            if (this.examInfo && this.examInfo.targetClassIds) {
                if (this.examInfo.scope == 'school') {
                    this.showTest = false
                    let classes = this.$store.state.user.schoolProfile.school_classes.filter(
                        (item) => {
                            return (this.examInfo.targetClassIds.indexOf(item.id) >= 0 && item.gradeId == this.chooseGrade);
                        }
                    )
                    return classes;
                } else if (this.examInfo.scope == 'teacher') {
                    this.showTest = false
                    let classes = this.$store.state.user.schoolProfile.school_classes.filter(
                        (item) => {
                            return (this.examInfo.targetClassIds.indexOf(item.id) >= 0);
                        }
                    )
                    return classes;
                } else {
                    //根据targetClassIds查询班级信息
                    if (!this.privClassList) {
                        this.$api.schoolSetting.getClassByIds({
                            code: this.$store.state.userInfo.TEAMModelId,
                            ids: this.examInfo.targetClassIds
                        }).then(
                            res => {
                                if (res.className && res.className.length) this.chooseClass = res.className[0].id
                                this.privClassList = res.className
                            },
                            err => {
                                console.log(err)
                            }
                        )
                    }
                    return this.privClassList
                }
            } else {
                return []
            }
        },
    },
    mounted() {
    },
    created() {
        if (this.$route.name == 'privateEvaluation') {
            this.routerScope = 'private'
        } else {
            this.routerScope = 'school'
        }
    }
};
</script>

<style scoped lang="less">
@import "./Scoring.less";
</style>
<style lang="less">
.scoring-main-wrap .ivu-table-fixed-body {
    background: #353535;
    // background: #2b2b2e;
    max-height: 653px;
}
.scoring-main-wrap .ivu-table-tip {
    position: relative;
    z-index: 9999;
}
.scoring-main-wrap .ivu-table-fixed-right::before,
.scoring-main-wrap .ivu-table-fixed::before {
    display: none;
}
.scoring-main-wrap .ivu-table-fixed-header thead tr th {
    background: #353535;
    // background: #2b2b2e;
    border-color: #606060;
    color: white;
}
.scoring-main-wrap {
    .ivu-table-header thead tr th {
        // background: #353535;
        background: rgba(53, 53, 53, 0.5);
    }
    .ivu-table td {
        // background: #353535;
        background: rgba(53, 53, 53, 0.5);
    }
}
.page-wrap .ivu-page-item {
    background: rgba(40, 40, 40, 0.5);
}

.page-wrap .ivu-page-item:hover {
    border-color: #e4eadb;
}

.page-wrap .ivu-page-item-active {
    background: #bfbfb9;
}

.page-wrap .ivu-page-item a {
    color: #f1f1f1;
}

.page-wrap .ivu-page-next,
.page-wrap .ivu-page-prev {
    background: rgba(0, 0, 0, 0);
}

.page-wrap .ivu-page-next a,
.page-wrap .ivu-page-prev a {
    color: #e4eadb;
}

.page-wrap .ivu-page-next:hover,
.page-wrap .ivu-page-prev:hover {
    border-color: #e4eadb;
}

.page-wrap .ivu-page-item-active,
.page-wrap .ivu-page-item:hover a {
    border-color: #e4eadb;
}

.page-wrap .ivu-page-item-active a {
    color: #595959;
}
.page-wrap
    .ivu-select-small.ivu-select-single
    .ivu-select-selection
    .ivu-select-selected-value {
    height: 27px;
    line-height: 27px;
    font-size: 12px;
}
.page-wrap .ivu-select-single .ivu-select-selection {
    height: 30px;
    background: transparent;
    border: 1px solid #595959;
    box-shadow: none;
    color: #cecece;
}

.page-wrap .ivu-select-single .ivu-select-placeholder {
    height: 30px;
    line-height: 30px;
    font-size: 16px;
}
</style>