<template>
    <div class="layout">
        <div class="top-box">
            <div class="top-select dark-iview-select">
            <Select v-model="model1" size="small" style="width:120px;margin-left:5px" placeholder="学年">
                <Option v-for="item in timeList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
            <Select v-model="model2" size="small" style="width:120px;margin-left:5px" placeholder="学期">
                <Option v-for="item in cityList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
            <Select v-model="model3" size="small" style="width:120px;margin-left:5px" placeholder="教学班级">
                <Option v-for="(item,index) in classList" :key="index" :value="item.classroomCode">{{ item.classroomName }}</Option>
            </Select>
        </div>
        <div class="box-show">
            <record-chart></record-chart>
        </div>
        </div>
        <div class="buttom-box">
            <Tabs @on-click="getType" :animated="false">
                <TabPane v-for="(item,index) in dataInfo" :key="index" :label="item.type">
                    <div class="list-show">
                        <div class="list-box">
                            <vuescroll>
                                <Loading :top="200" bgColor="rgba(103, 103, 103, 0.27)" type="1" v-show="isLoading"></Loading>
                                <ul v-for="(data,indexs) in item.data" :key="indexs" @click="getList(indexs)">
                                    <li :class="indexs == listIndex ? 'active-list' : ''">
                                        <div class="box">
                                            <span :class="indexs == listIndex ? 'list-color' : ''">{{data.name}}</span>
                                            <br />
                                            <div class="box-info">
                                                <h3>活动开始时间：</h3><p>{{dateFormat(data.createTime == undefined ? data.startTime : data.createTime)}}</p>
                                            </div>
                                        </div>
                                    </li>
                                </ul>
                            </vuescroll>
                        </div>
                        <div class="chart-box">
                            <vuescroll>
                                <div v-if="item.code == 1" style="margin-left:5px">
                                    <Loading :top="200" bgColor="rgba(103, 103, 103, 0.27)" type="1" v-show="isLoading"></Loading>
                                    <span style="text-align: right; margin-top: 5px; width: 100%; display: block; padding-right: 20px; cursor: pointer;" @click="getTestData"><Icon :type="testStatus ? 'md-list-box':'md-stats'" style="margin-right:5px;" />{{testStatus ? '成绩列表':'成绩分析'}}</span>
                                    <div v-if="!testStatus" class="chart" style="margin:auto">
                                        <Grade v-if="studentList.length !== 0" :studentData="studentList"></Grade>
                                    </div>
                                    <div v-if="testStatus" class="chart">
                                        <Analyse></Analyse>
                                    </div>
                                    <Table v-if="studentList.length !== 0" :studentData="studentList"></Table>
                                </div>
                                <div v-if="item.code == 2">
                                    <div style="height:400px">
                                        <PassBar :passData="passData"></PassBar>
                                        <ProgressBar :countData="countData"></ProgressBar>

                                    </div>
                                </div>
                                <div v-if="item.code == 3">
                                    <div>
                                        <BaseHwTable :studentsList="HwstudentsList" :hwId="currentHw.id"></BaseHwTable>
                                    </div>
                                </div>
                                <div v-if="item.code == 4">
                                    <BaseVoteTable :tableDatas="tableData"></BaseVoteTable>
                                    <!--<div style="display:flex">
                                        <BaseVotePie pieId="votePie" :pieData="tableData" v-show="tableData.length"></BaseVotePie>
                                        <BaseVoteBar pieId="votePie2" v-show="tableData.length" :pieData="tableData"></BaseVoteBar>
                                    </div>-->
                                    <!--<BaseVoteSsTable :tableDatas="studentsTable"></BaseVoteSsTable>-->
                                </div>      
                                <div v-if="item.code == 5">
                                    <BaseQuestionnaire :editItem="currentQn" :isEdit="editable" ref="qnPaper" ></BaseQuestionnaire>
                                </div>
                            </vuescroll>
                        </div>
                    </div>
                </TabPane>
            </Tabs>
        </div>
    </div>
</template>
<script>
    import RecordChart from '../../components/learnactivity/RecordChart.vue'
    import Grade from '@/components/learnactivity/GradeChart.vue'
    import Analyse from '@/components/learnactivity/AnalyseChart.vue'
    import PassBar from '../selflearn/PassBar.vue'
    import ProgressBar from '../selflearn/ProgressBar.vue'
    import BaseVoteTable from '@/components/vote/BaseVoteTable'
    import BaseVoteSsTable from '@/components/vote/BaseVoteSsTable'
    import BaseHwTable from '@/components/homework/BaseHwTable'
    import BaseQuestionnaire from '@/components/questionnaire/BaseQuestionnaire'
    import Table from '@/components/learnactivity/GradeTable'
    export default {
        data() {
            return {
                isLoading: false,
                testStatus: false,
                listIndex: 0,
                isCollapsed: false,
                editable:true,
                dataInfo: [],
                cityList: [
                    {
                        value: '上学期',
                        label: '上学期'
                    },
                    {
                        value: '下学期',
                        label: '下学期'
                    }
                ],
                timeList: [
                    {
                        value: '2016',
                        label: '2016'
                    },
                    {
                        value: '2017',
                        label: '2017'
                    },
                    {
                        value: '2018',
                        label: '2018'
                    },
                    {
                        value: '2019',
                        label: '2019'
                    },
                    {
                        value: '2020',
                        label: '2020'
                    },

                ],
                model2:'',
                model1: '',
                model3: '',
                studentList: [],
                classList: [],
                orderLearnList: [],
                voteList: [], //投票数据
                studentsTable: [],
                tableData: [],
                hwList: [], //作业活动数据
                HwstudentsList: [],//作业活动学生列表
                currentHw:[],
                selectClass: {},
                curClassIndex: 0,
                learnContent: {},
                qnList: [],
                currentQn: {
                    status: 300
                },
            }
        },
        methods: {
            /*
             * 获取班级信息
             */
            getClassData(data) {
                if (data !== '' || data !== undefined) {
                    for (let i = 0; i < this.classList.length; i++) {
                        if (this.classList[i].classroomCode == data) {
                            this.selectClass = this.classList[i]
                            this.curClassIndex = i
                        }
                    }
                } else {
                    this.$Message.warning('班级信息错误！')
                }
            },
            getType(data) {
            },
            collapsedSider() {
                this.$refs.side1.toggleCollapse();
            },
            getData() {
                let data = this.$Mock.data.classData
                this.dataInfo = data
                this.studentList = this.$Mock.data.studentList[0].studentScore
            },
            getList(data) {
                this.listIndex = data
            },
            getTestData() {
                this.testStatus = !this.testStatus
            },
            /*
             * 获取评测列表数据
             */
            findEvaluation() {
                let requestData = {
                    code: this.$store.state.userInfo.TEAMModelId
                }
                this.$api.learnActivity.FindExamInfo(requestData).then(
                    res => {
                        if (res.error == null) {
                            this.dataInfo[0].data = res.result.data
                            for (let i = 0; i < this.dataInfo[0].data.length; i++) {
                                this.dataInfo[0].data[i].createTime = this.dataInfo[0].data[i].startTime
                            }
                            
                        } else {
                            this$Message.error('API ERROR!')
                        }
                    },
                    res => {

                    }
                )
            },
            /*
             * 获取自主学习数据
             */
            getClassroomStudent() {
                if (!this.classList[this.curClassIndex].students) {
                    this.$api.courseMgmt.getClassroomStudent(
                        {
                            classroomCode: [this.classList[this.curClassIndex].classroomCode],
                            schoolCode: this.classList[this.curClassIndex].code
                        }
                    ).then(
                        (res) => {
                            if (res.error == null) {
                                let students = res.result.extend.students
                                this.$set(this.classList[this.curClassIndex], 'students', students)
                                this.findRecord()
                            } else {
                                this.$Message.error('API error!')
                                this.isLoading = false
                            }
                        },
                        (err) => {
                            this.$Message.error('API error!')
                            this.isLoading = false
                        }
                    )
                } else {
                    this.checkFindRecord()

                    //setTimeout(() => {
                    //    this.isLoading = false
                    //}, 800)
                }
            },
            //查询学习任务
            findTask() {
                if (this.learnContent.id) {
                    this.$api.learnActivity.findTask({
                        id: this.learnContent.id
                    }).then(
                        (res) => {
                            if (res.error == null) {
                                let resData = res.result.data
                                for (let index in resData) {
                                    for (let i in this.classList) {
                                        if (this.classList[i].classroomCode == resData[index].code) {
                                            this.$set(this.classList[i], [resData[index].id], resData[index])
                                            break
                                        }
                                    }
                                }
                            } else {
                                this.$Message.error('API error!')
                            }
                        },
                        (err) => {
                            this.$Message.error('API error!')
                        }
                    )
                }
            },
            /**
           * 获取学生学习数据
           * */
            findRecord() {
                let requestData = {
                    id: this.learnContent.id,
                    'code': this.classList[this.curClassIndex].students.map((item) => {
                        return item.studentId
                    })
                }
                if (requestData.code.length > 0) {
                    this.$api.learnActivity.findRecord(requestData).then(
                        (res) => {
                            if (!res.error && res.result.data) {
                                let resData = res.result.data
                                let type = this.learnContent.pk
                                let count = 0
                                if (type == 'LearnProcess') {
                                    count = this.learnContent.steps.length
                                }
                                let zeroStu = []
                                for (let item of this.classList[this.curClassIndex].students) {
                                    let flag = false
                                    for (let index in resData) {
                                        if (item.studentId == resData[index].code) {
                                            resData[index].name = item.name
                                            resData[index].percent = type == 'LearnProcess' ? parseInt(resData[index].steps.length / count * 100) : 100
                                            flag = true
                                            break
                                        }
                                    }
                                    if (!flag) {
                                        zeroStu.push({
                                            code: item.studentId,
                                            name: item.name,
                                            percent: 0,
                                            steps: []
                                        })
                                    }
                                }
                                resData.push(...zeroStu)
                                this.$set(this.classList[this.curClassIndex][this.learnContent.id], 'record', resData)
                                this.isLoading = false
                            } else {
                                this.$Message.error("API error!")
                                this.isLoading = false
                            }
                        },
                        (err) => {
                            this.$Message.error("API error!")
                            this.isLoading = false
                        }
                    )
                } else {
                    let record = []
                    for (let item of this.classList[this.curClassIndex].students) {
                        record.push({
                            code: item.studentId,
                            name: item.name,
                            percent: 0,
                            steps: []
                        })
                    }
                    if (this.classList[this.curClassIndex][this.learnContent.id]) {
                        this.$set(this.classList[this.curClassIndex][this.learnContent.id], 'record', record)
                    } else {
                        this.showRecord = []
                    }

                    this.isLoading = false
                }
            },
            /**
             * 查询编序式教材列表
             * */
            findOrderLearn() {
                if (this.orderLearnList.length == 0) {
                    let requestData = {
                        code: this.$store.state.userInfo.TEAMModelId
                    }
                    this.$api.learnActivity.FindOrderLearn(requestData).then(
                        res => {
                            if (res.error == null) {
                                this.orderLearnList = res.result.data
                                this.dataInfo[1].data = res.result.data
                                this.learnContent = this.orderLearnList[this.curClassIndex]
                                this.findTask()
                                this.getClassroomStudent()
                            } else {
                                this.$Message.error('API ERROR!')
                            }
                        },
                        err => {

                        }
                    )
                }
            },
            checkFindRecord() {
                if (this.classList[this.curClassIndex][this.learnContent.id] && !this.classList[this.curClassIndex][this.learnContent.id].record) {
                    this.findRecord()
                } else {
                    this.getPageData()
                }
            },
            /** 获取作业列表 */
            getHomeWorkList() {
                this.isLoadList = true
                let params = {
                    code: this.$store.state.userInfo.TEAMModelId
                }
                this.$api.learnActivity.FindHomeWork(params).then(res => {
                    if (!res.error && res.result.data) {
                        this.hwList = res.result.data.sort((a, b) => {
                            return b.createTime - a.createTime
                        })
                        this.dataInfo[2].data = res.result.data
                        for (let i = 0; i < this.dataInfo[2].data.length; i++) {
                            this.dataInfo[2].data[i].createTime = this.dataInfo[2].data[i].startTime
                        }
                        this.onHwClick(res.result.data[0], 0)
                        this.isLoadList = false
                    } else {
                        this.$Message.error('获取数据失败')
                    }
                })
            },
            onHwClick(item, index) {
                this.currentHw = item
                this.HwstudentsList = []
                this.getHwStudents(item.id, item.target)
            },
            async getHwStudents(hwId, target) {
                let records = await this.getHwRecord(hwId)
                this.isLoading = true
                //  先查找 作业发布对象关联的学生清单 然后再去判断学生的作答情况
                this.$api.courseMgmt.getClassroomStudent({
                    classroomCode: target.map(i => i.classroomCode),
                    schoolCode: this.$store.state.userInfo.schoolCode
                }).then(res => {
                    if (!res.error && res.result.data) {
                        let list = res.result.data
                        let infoList = res.result.extend.students
                        list.forEach(i => {
                            i.name = infoList.filter(j => j.studentId === i.code)[0].name
                            i.classroomName = target.filter(k => k.classroomCode === i.id)[0].classroomName
                        })
                        // 要根据作答情况 结合两张表 处理表格显示的数据 
                        if (records.length) {
                            list.forEach(i => {
                                for (let a = 0; a < records.length; a++) {
                                    // 如果学生已提交 则添加提交信息 如果未提交则跳过
                                    let item = records[a]
                                    if (i.code === item.code) {
                                        i.submissionBool = true
                                        i.submissionTime = item.submitTime
                                        i.teacherComments = item.tchCmt
                                        i.studentComments = item.stuCmt
                                        i.score = item.score
                                        i.content = item.content
                                        return false
                                    } else {
                                        i.submissionBool = false
                                        i.submissionTime = null
                                        i.teacherComments = null
                                        i.studentComments = []
                                        i.score = 0
                                        i.content = []
                                    }
                                }
                            })
                        }
                        this.HwstudentsList = list
                        this.isLoading = false
                    } else {
                        this.$Message.error('获取数据失败')
                    }
                })
            },
            getHwRecord(hwId) {
                return new Promise((r, j) => {
                    this.$api.learnActivity.FindRecordByHwId({
                        id: hwId
                    }).then(res => {
                        if (!res.error && res.result.data) {
                            r(res.result.data)
                        } else {
                            j(500)
                        }
                    })
                })
            },
            /** 获取投票活动列表 */
            getVoteList(type) {
                let params = {
                    code: this.$store.state.userInfo.schoolCode
                }
                this.$api.learnActivity.FindVote(params).then(async res => {
                    if (!res.error && res.result.data) {
                        let that = this
                        let privateSas = await this.$tools.getPrivateSas()
                        let schoolSas = await this.$tools.getSchoolSas()
                        let list = res.result.data
                        /* 遍历替换成BLOB里面的JSON完整数据 */
                        let transBlob2Json = async function () {
                            for (let j = 0; j < list.length; j++) {
                                let i = list[j]
                                if (i.url) {
                                    try {
                                        let sasString = i.code === that.$store.state.userInfo.TEAMModelId ? privateSas : schoolSas
                                        let jsonInfo = await that.$tools.getFile(i.url + sasString.sas)
                                        let jsonData = JSON.parse(jsonInfo)
                                        jsonData.id = i.id
                                        jsonData.status = i.status
                                        jsonData.startTime = i.startTime
                                        jsonData.fileName = i.url.split('/')[i.url.split('/').length - 1].split('.json')[0]
                                        that.$set(list, j, jsonData)
                                    } catch (e) {
                                        that.$Message.warning('存在试题读取异常！')
                                    }
                                }
                            }
                            that.voteList = list.reverse()
                            that.dataInfo[3].data = that.voteList
                            that.onVoteClick(list[0], 0)
                        }
                        transBlob2Json()
                    } else {
                        this.$Message.error('获取数据失败')
                    }
                })
            },
            /**获取问卷调查数据 */
            getVoteSearch() {
                let params = {
                    code: this.$store.state.userInfo.TEAMModelId
                }
                this.$api.questionnaire.FindSurveysSummary(params).then(async res => {
                    if (!res.error && res.result.data) {
                        let list = res.result.data
                        this.qnList = list
                        this.dataInfo[4].data = this.qnList
                        if (list.length) {
                            this.onQnClick(list[0], 0)
                        }
                    } else {
                        this.$Message.error('获取数据失败')
                    }
                })
            },
            async onQnClick(item, index) {
                /* 判断是否有新增但是无效的ITEM  如果有 则清空 需要重新添加 */
                let hasNewQn = this.qnList.filter(i => !i.id).length
                if (hasNewQn) {
                    this.qnList.filter(i => !i.id).forEach(item => {
                        this.qnList.splice(this.qnList.indexOf(item), 1)
                    })
                }
                // 如果当前点击活动是已结束 则获取问卷的作答数据
                
                this.currentQn = item.id ? await this.getQnDetails(item.id) : this.currentQn
                this.currentQn.status = item.status
            },
            async getQnDetails(qnId) {
                return new Promise(async (r, j) => {
                    let privateSas = await this.$tools.getPrivateSas()
                    let schoolSas = await this.$tools.getSchoolSas()
                    this.$api.questionnaire.FindSurveys({
                        id: qnId
                    }).then(async res => {
                        if (!res.error && res.result.data) {
                            let i = res.result.data[0]
                            if (i.url) {
                                let sasString = i.code === this.$store.state.userInfo.TEAMModelId ? privateSas : schoolSas
                                let jsonInfo = await this.$tools.getFile(i.url + sasString.sas)
                                let jsonData = JSON.parse(jsonInfo)
                                jsonData.id = i.id
                                jsonData.fileName = i.url.split('/')[i.url.split('/').length - 1].split('.json')[0]
                                r(jsonData)
                            } else {
                                r(i)
                            }
                        } else {
                            this.$Message.error('获取数据失败')
                        }
                    })
                })

            },

            onVoteClick(item, index) {
                this.getVoteStudents(item.id, item.target)
            },
            /**
			 * 获取投票关联的学生清单
			 * @param voteId 投票ID
			 */
            async getVoteStudents(voteId, target) {
                this.isLoading = true
                let records = await this.getVoteRecord(voteId)
                //  先查找 投票发布对象关联的学生清单 然后再去判断学生的作答情况
                this.$api.courseMgmt.getClassroomStudent({
                    classroomCode: target.map(i => i.classroomCode),
                    schoolCode: this.$store.state.userInfo.schoolCode
                }).then(res => {
                    if (!res.error && res.result.data) {
                        let list = res.result.data
                        let infoList = res.result.extend.students
                        list.forEach(i => {
                            i.name = infoList.filter(j => j.studentId === i.code)[0].name
                            i.classroomName = target.filter(k => k.classroomCode === i.id)[0].classroomName
                        })
                        // 要根据作答情况 结合两张表 处理表格显示的数据 
                        if (records.length) {
                            let arr = []
                            this.studentsTable = []
                            records.forEach((item, index) => {
                                arr.push({
                                    // option: this.getSimpleText(item.optionValue),
                                    option: item.optionKey ? '选项' + (index + 1) : '未投票',
                                    key: item.optionKey || '',
                                    result: item.students
                                })
                                this.studentsTable = this.studentsTable.concat(item.students)
                            })
                            this.studentsTable.forEach(i => {
                                let matchList = list.filter(j => j.code === i.code)
                                i.name = matchList.length ? matchList[0].name : '暂无数据'
                            })
                            this.tableData = arr
                        } else {
                            this.tableData = []
                        }
                        this.isLoading = false
                    } else {
                        this.$Message.error('获取数据失败')
                        this.isLoading = false
                    }
                })
            },
            /* 获取投票结果数据 */
            getVoteRecord(voteId) {
                return new Promise((r, j) => {
                    this.$api.learnActivity.FindRecordByVoteId({
                        id: voteId
                    }).then(res => {
                        if (!res.error && res.result.data) {
                            r(res.result.data)
                        } else {
                            j(500)
                        }
                    })
                })
            },
            /*
             * 查询班级信息
             */
            findClassroom() {
                if (this.classList.length == 0) {
                    let requestData = this.$store.state.userInfo.TEAMModelId
                    this.$api.learnActivity.FindClassroomByTeacherId({
                        code: requestData
                    }).then(
                        res => {
                            if (res.error == null) {
                                this.classList = res.result.data
                                if (this.classList.length > 0) {
                                    setTimeout(() => {
                                        this.findOrderLearn()
                                    }, 1000)
                                }
                            } else {
                                this.$Message.error('API ERROR!')
                            }
                        },
                        err => {

                        }
                    )
                }
            },

            dateFormat(timestamp) {
                var date = new Date(timestamp)
                var Y = date.getFullYear() + '-'
                var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
                var D = date.getDate() + ' '
                return Y + M + D;
            },
        },
        components: {
            RecordChart, Grade, Analyse, PassBar, BaseVoteTable, BaseVoteSsTable, BaseHwTable, BaseQuestionnaire, Table,ProgressBar
        },
        mounted() {
            this.findClassroom()
            this.getData()
            this.getVoteList()
            this.getVoteSearch()
            this.findEvaluation()
            this.getHomeWorkList()
            window.addEventListener('resize', () => {
                //clearTimeout(this.timer)  //清零
                //this.timer = setTimeout(() => {
                //    //this.table.resize()
                //    //this.pie.resize()
                //    //this.chart.resize()
                //}, 500)
            })
        },
        computed: {
            menuitemClasses: function () {
                return [
                    'menu-item',this.isCollapsed ? 'collapsed-menu' : ''
                ]
            },
            countData() {
                if (this.learnContent.pk == 'LearnProcess') {
                    let labels = this.learnContent.steps.map((item) => {
                        return item.name
                    })
                    let studentCount = 0
                    let seriesData = []
                    for (let index in labels) {
                        seriesData.push(0)
                    }
                    if (this.classList.length > 0) {
                        if (this.classList[this.curClassIndex].students && this.classList[this.curClassIndex][this.learnContent.id].record) {
                            studentCount = this.classList[this.curClassIndex].students.length
                            for (let item of this.classList[this.curClassIndex][this.learnContent.id].record) {
                                for (let step of item.steps) {
                                    seriesData[step.index]++
                                }
                            }
                        }
                    }
                    return {
                        xAxisData: labels,
                        seriesData: seriesData,
                        studentCount: studentCount
                    }
                }
            },
            passData() {
                if (this.learnContent.pk == 'LearnProcess' && this.classList[this.curClassIndex][this.learnContent.id] !== undefined) {
                    let labels = this.learnContent.steps.map((item) => {
                        return item.name
                    })
                    let studentCount = 0
                    let result = []
                    for (let item of labels) {
                        result.push({
                            name: item,
                            zero: 0,
                            once: 0,
                            twice: 0,
                            third: 0
                        })
                    }
                    if (this.classList.length > 0 && this.classList[this.curClassIndex][this.learnContent.id].record !== undefined) {
                        if (this.classList[this.curClassIndex].students ) {
                            studentCount = this.classList[this.curClassIndex].students.length
                            for (let item of this.classList[this.curClassIndex][this.learnContent.id].record) {
                                for (let stepIndex in item.steps) {
                                    if (item.steps[stepIndex].count == 1) {
                                        result[stepIndex].once++
                                        //once++
                                    } else if (item.steps[stepIndex].count == 2) {
                                        result[stepIndex].twice++
                                        //twice++
                                    } else if (item.steps[stepIndex].count >= 3) {
                                        result[stepIndex].third++
                                        //third++
                                    }
                                }
                            }
                            for (let item of result) {
                                item.zero = studentCount - item.once - item.twice - item.third
                            }
                        }
                    }
                    return result
                } else if (this.learnContent.pk == 'LearnUnit') {

                }
            }
        }
    }
</script>
<style scoped lang="less">
@import"./ManageRecord.less";
</style>