<template>
    <div class="activity-info-container dark-iview-split">
        <Split v-model="split1">
            <div slot="left" class="activity-target-list">
                <div class="activity-target-header">
                    <span>
                        授课班级
                    </span>
                    <div class="tools-box" v-if="classList.length > 0">
                        <Icon v-show="classList[curClassIndex][learnContent.id]" type="ios-undo" class="action-btn-icon" title="撤回" @click="revokeStatus = true" />
                        <Icon v-if="!classList[curClassIndex][learnContent.id]" type="ios-share-alt" class="action-btn-icon" title="分享" @click="publishStatus = true" />
                        <Icon v-else type="md-create" class="action-btn-icon" title="编辑" @click="publishStatus = true" />
                    </div>
                </div>
                <div style="height:calc(100% - 50px)">
                    <vuescroll>
                        <div @click="selectActivity(index)" v-for="(item,index) in classList" :key="index" :class="index == curClassIndex ? 'activity-target-item block-bg block-bg-active':'block-bg activity-target-item'">
                            <p class="target-name">
                                {{item.name}}
                                <span class="class-type-label" :style="{background: item.scope == 'school' ? '#1cc0f3':'#ff9900'}">{{item.scope == 'school' ? '系统班级':'动态名单'}}</span>
                                <span class="activity-status" :style="{background: item[learnContent.id] ? '#19be6b':'#ed4014'}">{{item[learnContent.id] ? '进行中':'未分享'}}</span>
                            </p>
                            <p style="margin-top:6px;">
                                <span class="info-label">活动类型：</span>
                                <span class="info-value">{{ !item[learnContent.id] ? '-- --' : item[learnContent.id].type == 1 ? '自主学习':'课前预习'}}</span>
                            </p>
                            <p style="margin-top:6px;" v-if="item[learnContent.id]">
                                <span class="info-label">{{ item[learnContent.id].type == 1 ? '开始时间：' : '结束时间：' }}</span>
                                <span class="info-value">{{item[learnContent.id].type == 1 ? $tools.formatTime(item[learnContent.id].createTime,'yyyy-MM-dd') : $tools.formatTime(item[learnContent.id].endTime)}}</span>
                            </p>
                            <p style="margin-top:6px;" v-else>
                                <span class="info-label">结束时间：</span>
                                <span class="info-value">{{item.endTime ? item.endTime:'-- --'}}</span>
                            </p>
                        </div>
                        <EmptyData v-if="classList.length == 0" textContent="暂无授课班级"></EmptyData>
                    </vuescroll>
                </div>
            </div>
            <div slot="right" class="activity-detail-info">
                <vuescroll style="height:100%;">
                    <div v-if="classList[curClassIndex] && classList[curClassIndex][learnContent.id]" style="height:100%;">
                        <div class="learn-progress-container" v-if="!showAnswer">
                            <div class="learn-progress-main dark-iview-table">
                                <vuescroll>
                                    <Loading v-show="isLoading" bgColor="rgba(103, 103, 103, 0.27)"></Loading>
                                    <p class="chart-name" style="margin-top:15px;">活动进度概览</p>
                                    <div class="whole-progress-wrap">
                                        <div class="progress-histogram-wrap" style="margin:auto;">
                                            <ProgressBar v-if="learnContent.pk == 'LearnProcess' && learnContent.steps.length > 1" :countData="countData" @clickStep="clickStep"></ProgressBar>
                                            <ProgressPie v-else :pieData="pieData"></ProgressPie>
                                        </div>
                                    </div>
                                    <p  class="chart-name">通过率统计</p>
                                    <div class="pass-bar-wrap">
                                        <PassBar :passData="passData"></PassBar>
                                    </div>
                                    <p  class="chart-name">
                                        学生进度概览
                                    </p>
                                    <Table :columns="studentColumns" :data="showRecord" :show-header="true" style="margin:0px 25px;" no-data-text="此班暂无学生" @on-sort-change="sortByPercent">
                                        <template slot-scope="{ row, index }" slot="isComplete">
                                            <Icon size="20" type="md-checkmark" color="aqua" v-if="row.isComplete == 1" />
                                            <span v-else>--</span>
                                        </template>
                                        <template slot-scope="{ row, index }" slot="progress">
                                            <Progress :percent="row.percent" status="normal" style="width:80%; max-width:300px;"/>
                                        </template>
                                        <template slot-scope="{ row, index }" slot="question">
                                            <div style="cursor:pointer;font-size:20px;">
                                                <span title="提问/留言" v-if="index % 3 == 0">- -</span>
                                                <Icon @click="goToAnswer" v-else type="ios-chatbubbles-outline" title="查看留言/提问" />
                                            </div>
                                        </template>
                                        <template slot-scope="{ row, index }" slot="max">
                                            <span>{{getMaxStep(row)}}</span>
                                        </template>
                                    </Table>
                                    <div v-if="classList[curClassIndex][learnContent.id] && classList[curClassIndex][learnContent.id].record" style="width:100%;text-align:center;margin-top:20px;" class="dark-iview-page">
                                        <Page :total="classList[curClassIndex][learnContent.id].record.length" size="small" :current.sync="currentPage" :page-size="pageSize" show-sizer show-total @on-change="getPageData" @on-page-size-change="getPageData($event,'size')" />
                                    </div>
                                </vuescroll>
                            </div>
                        </div>
                        <QuestionInfo v-if="showAnswer" @closeAnswerDetail="showAnswer = false"></QuestionInfo>
                    </div>
                    <EmptyData v-else textContent="此班未分享，暂无学习数据"></EmptyData>
                </vuescroll>
            </div>
        </Split>
        <Modal v-model="publishStatus"
               title="发布学习活动"
               class-name="dark-iview-modal dark-iview-form publish-modal"
               @on-ok="confirmPublish">
            <Form ref="activityInfo" :model="activityInfo" label-colon label-position="left" :label-width="90" :rules="ruleValidate">
                <FormItem label="分享班级">
                    <span style="color:white;" v-if="classList[curClassIndex]">{{classList[curClassIndex].name}}</span>
                </FormItem>
                <FormItem label="闯关模式" prop="stage">
                    <RadioGroup v-model="activityInfo.stage" style="color:white;">
                        <Radio :label="1" style="width:82px;">
                            <span>是</span>
                        </Radio>
                        <Radio :label="0">
                            <span>否</span>
                        </Radio>
                    </RadioGroup>

                </FormItem>
                <transition name="fade">
                    <FormItem label="过关分数" prop="stage" v-if="activityInfo.stage == 1">
                        <InputNumber size="small" :max="100" :min="60" v-model="activityInfo.passScore" style="width:170px;"></InputNumber>
                    </FormItem>
                </transition>
                <FormItem label="活动类型" prop="type">
                    <RadioGroup v-model="activityInfo.type" style="color:white;">
                        <Radio :label="item.value" v-for="(item,index) in activityTypeList" :key="index">
                            <span>{{ item.label }}</span>
                        </Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="截止时间" v-if="activityInfo.type == 2" prop="endTime">
                    <DatePicker type="datetime" placeholder="设置截止时间" style="width: 100%;" @on-change="setEndTime"></DatePicker>
                </FormItem>
            </Form>
        </Modal>
        <Modal v-model="revokeStatus"
               title="撤回学习活动"
               class-name="dark-iview-modal dark-iview-form publish-modal"
               @on-ok="confirmRevoke">
            <p style="color:white;font-size:15px;">撤回活动将同时删除学生学习数据，确定撤回<span style="color:#ff9900;font-weight:600;" v-if="classList[curClassIndex]">{{classList[curClassIndex].name}}</span>的学习活动吗？</p>
        </Modal>
    </div>
</template>
<script>
    import ProgressBar from './ProgressBar.vue'
    import ProgressPie from './ProgressPie.vue'
    import PassBar from './PassBar.vue'
    import Loading from '@/common/Loading.vue'
    import StudyDetail from './StudyDetail.vue'
    import AnswerRecord from './AnswerRecord.vue'
    import QuestionInfo from './QuestionInfo.vue'

    export default {
        components: {
            StudyDetail,AnswerRecord,Loading,ProgressBar,ProgressPie,PassBar,QuestionInfo
        },
        props: {
            learnContent: {
                default: () => {
                    return {
                        id: '',
                        pk:''
                    }
                },
                type: Object
            },
            classList: {
                default: () => {
                    return []
                },
                type: Array
            }
        },
        data() {
            return {
                isLoading: false,
                activityTypeList: [
                    {
                        value: 1,
                        label:'自主学习'
                    },
                    {
                        value: 2,
                        label:'课前预习'
                    },
                ],
                ruleValidate: {
                    type: [
                        { required: true, type:'number', message: '请选择活动类型', trigger: 'change' }
                    ],
                    stage: [
                        { required: true, type:'number',message: '请选择活动模式', trigger: 'change' }
                    ],
                    endTime: [
                        { required: true, type:'number',message: '请设置结束时间', trigger: 'change' }
                    ]
                },
                activityInfo: {
                    type: 1,
                    endTime: undefined,
                    stage: 1,
                    passScore:100
                },
                revokeStatus: false,
                publishStatus: false,
                showAnswer: false,
                curClassIndex:0,
                split1: 0.25,
                pageSize: 10,
                currentPage:1,
                dataIndex: 1,
                curStudent: '',
                studentData: [],
                showRecord:[],
                studentPageData:[],
                studentColumns: [
                    {
                        type: 'expand',
                        width: 80,
                        render: (h, params) => {
                            return h(StudyDetail, {
                                props: {
                                    studyData: params.row,
                                    learnContent: this.learnContent
                                }
                            })
                        }
                    },
                    {
                        title: '姓名',
                        key: 'name',
                        width:180
                    },
                    {
                        title: '学习进度',
                        slot: 'progress',
                        key:'percent',
                        align: 'center',
                        sortable: 'custom'
                    },
                    {
                        title: '作答次数最多',
                        slot: 'max',
                        align: 'center',
                        sortable: true
                    },
                    {
                        title: '提问/留言',
                        slot: 'question',
                        align: 'center',
                        width: 200
                    }
                ],
            }
        },
        methods: {
            //设置结束时间格式
            setEndTime() {

            },
            //根据完成进度排序
            sortByPercent(column) {
                if (column.key == 'percent') {
                    this.classList[this.curClassIndex][this.learnContent.id].record.sort((a, b) => {
                        if (column.order == 'asc') {
                            return a.percent - b.percent
                        } else {
                            return b.percent - a.percent
                        }
                    })
                    this.getPageData()
                }
            },
            //计算作答次数最多的阶段
            getMaxStep(row) {
                let max = 1
                let step = []
                for (let item of row.steps) {
                    if (item.count > max) {
                        max = item.count
                        step.length = 0
                        step.push(item.index + 1)
                    } else if (item.count == max && max !== 1) {
                        step.push(item.index + 1)
                    }
                }
                if (step.length > 0) {
                    return step.join(',')
                } else {
                    return '--'
                }
            },
            clickStep(data) {
                this.dataIndex = data.dataIndex
            },
            //学生表格分页
            getPageData(number, type) {
                if (type == 'size') {
                    this.pageSize = number
                }
                if (this.classList[this.curClassIndex][this.learnContent.id]) {
                    let starIndex = this.pageSize * (this.currentPage - 1)
                    let endIndex = this.pageSize * this.currentPage > this.classList[this.curClassIndex][this.learnContent.id].record.length ? this.classList[this.curClassIndex][this.learnContent.id].record.length : this.pageSize * this.currentPage
                    this.showRecord = this.classList[this.curClassIndex][this.learnContent.id].record.slice(starIndex, endIndex)
                } else {
                    this.showRecord = []
                }
            },
            /**
             * 确认撤回学习活动
             * */
            confirmRevoke() {
                let requestData = {
                    id: this.learnContent.id,
                    pk: this.classList[this.curClassIndex].id
                }
                this.$api.learnActivity.deleteTask(requestData).then(
                    (res) => {
                        if (!res.error) {
                            this.$Message.success('撤销成功!')
                            this.classList[this.curClassIndex][this.learnContent.id] = undefined
                        } else {
                            this.$Message.error('API error!')
                        }
                    },
                    (err) => {
                        this.$Message.error('API error!')
                    }
                )
            },
            /**
             * 确认分享学习内容
             * */
            confirmPublish() {
                this.$Message.warning('暂未对接API')
                return
                this.$refs.activityInfo.validate((valid) => {
                    if (valid) {
                        let requestData = {
                            id: this.learnContent.id,
                            code: this.classList[this.curClassIndex].id,
                            endTime: this.activityInfo.endTime ? this.activityInfo.endTime: 0,
                            status: 200,
                            type: this.activityInfo.type,
                            stage: this.activityInfo.stage,
                            passScore: this.activityInfo.passScore
                        }
                        this.$api.learnActivity.UpsertTask(requestData).then(
                            (res) => {
                                if (res.error == null) {
                                    this.$set(this.classList[this.curClassIndex], [res.result.data.id], res.result.data)
                                    this.$Message.success('分享成功！')
                                } else {
                                    this.$Message.error('分享失败！')
                                }
                            },
                            (err) => {
                                this.$Message.error('分享失败！')
                            }
                        )
                    } else {
                        this.$Message.error('请完善信息再发布!')
                    }
                })
            },
            selectActivity(index) {
                this.curClassIndex = index
                if (this.classList.length > 0 && this.classList[this.curClassIndex]) {
                    console.log('......')
                    this.getClassroomStudent()
                }
            },
            goToAnswer() {
                this.showAnswer = true
            },
            /**
             *检测是否首次访问学生数据 
             * */
            checkFindRecord() {
                if (this.classList[this.curClassIndex][this.learnContent.id] && !this.classList[this.curClassIndex][this.learnContent.id].record) {
                    this.findRecord()
                } else {
                    this.getPageData()
                }
            },
            /**
             * 获取学生学习数据
             * */
            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.getPageData()
                                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)
                        this.getPageData()
                    } else {
                        this.showRecord = []
                    }
                    
                    this.isLoading = false
                }
                
            },
            //获取系统班级关联的学生（暂未对接动态班级名单）
            getClassroomStudent() {
                this.isLoading = true
                console.log(this.classList)
                if (!this.classList[this.curClassIndex].students) {
                    this.$api.schoolSetting.getClassroomStudent(
                        {
                            'school_code': this.$store.state.userInfo.schoolCode,
                            'teacher.id': this.$store.state.userInfo.TEAMModelId,
                            'scope':'school'
                        }
                    ).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)
                }
            },
        },
        mounted() {
            if (this.classList.length > 0 && this.classList[this.curClassIndex]) {
                this.getClassroomStudent()
            }
        },
        computed: {
            //多个阶段的学习进度统计
            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
                    }
                }
            },
            //单个阶段的学习进度统计
            pieData() {
                if (this.learnContent.pk == 'LearnUnit' || this.learnContent.steps.length < 2 ) {
                    if (this.classList.length > 0) {
                        if (this.classList[this.curClassIndex].students && this.classList[this.curClassIndex][this.learnContent.id].record) {
                            let studentCount = this.classList[this.curClassIndex].students.length
                            let completed = 0
                            for (let item of this.classList[this.curClassIndex][this.learnContent.id].record) {
                                if (item.steps.length > 0) {
                                    completed++
                                }
                            }
                            return [completed == 0 ? undefined : completed, studentCount - completed == 0 ? undefined : studentCount - completed]
                        }
                    } 
                }
                return [0,0]
            },
            //作答通过率统计
            passData() {
                if (this.learnContent.pk == 'LearnProcess') {
                    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) {
                        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) {
                                //let once = 0
                                //let twice = 0
                                //let third = 0
                                //let zero = 0

                                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') {

                }
            }
        },
        created() {
          
        }
    }
</script>
<style lang="less" scoped>
    @import "ActivityInfo.less";
</style>
<style>
    .learn-progress-filter .ivu-select-input {
        color:white;
    }
    .learn-progress-main td.ivu-table-expanded-cell {
        padding:0px;
    }
    .activity-detail-info .__view {
        height:100%;
    }
</style>