<template>
    <div class="offline">
        <Loading v-if="isLoading" hideMask></Loading>
        <div class="offline-content">
            <div class="offline-left">
                <div class="offline-content-header">{{ $t('jyzx.offline.activity') }}</div>
                <vuescroll>
                    <EmptyData :top="100" v-if="!activity.length"></EmptyData>
                    <div class="volume-list">
                        <div v-for="(item, index) in activity" :key="index" :class="[
                                'volume-item',
                                activeIndex === index ? 'volume-active' : '',
                            ]" @click="getActivityInfo(item, index)">
                            <p class="volume-item-name">
                                <span style="display: inline-block; background: #a2b02e;" v-show="item.owner == 'area'">{{ $t('jyzx.common.area') }}</span>
                                <span style="display: inline-block; background: #FF9900;" v-show="item.owner == 'school'">{{ $t('jyzx.common.school') }}</span>
                                {{ item.name }}
                            </p>
                            <p class="status-time" style="padding-left:25px">
                                {{ item.startTime }} - {{ item.endTime }}
                            </p>
                        </div>
                    </div>
                </vuescroll>
            </div>
            <div class="offline-right">
                <div class="offline-content-header">{{ $t('jyzx.offline.info') }}</div>
                <div class="offline-tree-box">
                    <div class="detailbox" v-if="Object.keys(resource).length">
                        <div style="margin-bottom: 40px">
                            <div class="detailheader">
                                <div class="activitytitle">
                                    <p class="detailstitle">
                                        <span class="school-gade" style="background: #a2b02e" v-show="resource.owner == 'area'">{{ $t('jyzx.common.typeArea') }}</span>
                                        <span class="school-gade" style="background: #ff9900" v-show="resource.owner == 'school'">{{ $t('jyzx.common.typeSch') }}</span>
                                        {{ resource.name }}
                                    </p>
                                    <div class="site">
                                        <span class="info-label">{{ $t('jyzx.offline.creator') }}：</span>
                                        <span v-if="resource.createdName">{{resource.createdName}}</span>
                                        <span v-else>{{ $t('jyzx.offline.noPeople') }}</span>
                                    </div>
                                    <div class="site">
                                        <span class="info-label">{{ $t('jyzx.offline.joinNum') }}：</span><span>{{ resource.joinNum}}</span>
                                    </div>
                                    <div class="site">
                                        <span class="info-label">{{ $t('jyzx.offline.actTime') }}：</span>
                                        <span>
                                            {{ resource.startTime }} -
                                            {{ resource.endTime }}
                                        </span>
                                    </div>
                                    <div class="site" v-if="targets.length">
                                        <span class="info-label">{{ $t('jyzx.offline.target') }}：</span>
                                        <span v-for="(item, index) in targets" :key="index" style="margin-right: 10px">{{ item }}</span>
                                    </div>
                                </div>
                                <div class="img-box" :style="{backgroundImage: `url(${resource.img || defImg})`}"></div>
                            </div>
                            <div class="basics">
                                <dt class="headeicon"><span class="headeicontitle">{{ $t('jyzx.offline.basicInfo') }}</span></dt>
                                <div class="target">
                                    <span class="info-label">{{ $t('jyzx.offline.studyTar') }}：</span>
                                    <span>{{ resource.desc }}</span>
                                </div>
                                <div class="site">
                                    <span class="info-label">{{ $t('jyzx.offline.address') }}：</span><span>{{ resource.address }}</span>
                                </div>
                                <div class="keynote">
                                    <span class="info-label">{{ $t('jyzx.offline.speaker') }}：</span><span>{{ resource.presenter }}</span>
                                </div>
                                <div class="type">
                                    <span class="info-label">{{ $t('jyzx.offline.type') }}：</span><span>{{ resource.typeName }}</span>
                                </div>
                                <div class="totalperiod">
                                    <span class="info-label">{{ $t('jyzx.offline.studyTime') }}：</span>
                                    <span class="hour-tag">{{ resource.hour }}{{ $t('jyzx.offline.studyTime') }}</span>
                                </div>
                                <div class="content">
                                    <span class="info-label">{{ $t('jyzx.common.content') }}：</span><span>{{ resource.topic }}</span>
                                </div>
                            </div>
                            <!-- <Divider dashed /> -->
                            <!-- 作业 -->
                            <div class="submitarea"  v-if="resource.settings.includes('hw') && workInfo">
                                <dt class="headeicon"><span class="headeicontitle">{{ $t('jyzx.offline.homework') }}</span></dt>
                                <div class="target">
                                    <span class="info-label">{{ $t('jyzx.offline.hwName') }}：</span><span>{{ workInfo.name }}</span>
                                </div>
                                <div class="target">
                                    <span class="info-label">{{ $t('jyzx.offline.hwDes') }}：</span><span>{{ workInfo.description }}</span>
                                </div>
                                <div class="target hw-style">
                                    <Upload
                                        type="drag"
                                        action=""
                                        :before-upload="customUpload"
                                    >
                                        <div style="padding: 20px 0">
                                            <Icon type="ios-cloud-upload" size="52" :style="{color: homeWork ? '#b4b4b4' : '#2d8cf0' }"></Icon>
                                            <p>
                                                <span>
                                                    {{ homeWork ? $t('jyzx.offline.againLoad') : $t('jyzx.offline.hwUpload')}}
                                                </span>
                                            </p>
                                        </div>
                                    </Upload>
                                    <!-- <Upload action="" :before-upload="customUpload">
                                        <div class="hw-area" :style="{background: homeWork ? '#19be6b' : '#2d8cf0' }">
                                            <Icon type="ios-cloud-upload" color="#fff" />
                                            <span>
                                                {{homeWork ? '重新上传' : '上传作业'}}
                                            </span>
                                        </div>
                                    </Upload> -->
                                    <span v-show="homeWork">
                                        <Icon type="ios-document" />{{
                                            homeWork
                                        }}
                                    </span>
                                </div>
                            </div>
                            <!-- 问卷 -->
                            <div class="submitarea" v-if="resource.settings.includes('survey') && surveyInfo">
                                <dt class="headeicon"><span class="headeicontitle">{{ $t('jyzx.offline.question') }}</span></dt>
                                <div class="target">
                                    <span class="info-label">{{ $t('jyzx.offline.queName') }}：</span><span>{{ surveyInfo.name }}</span>
                                </div>
                                <div class="target">
                                    <span class="info-label">{{ $t('jyzx.offline.queDes') }}：</span><span>{{ surveyInfo.description }}</span>
                                </div>
                                <div class="target hw-style">
                                    <Button type="primary" @click="doSurvey" v-if="!isSurvey">
                                        <Icon type="ios-create" />
                                        {{ $t('jyzx.offline.queAnswer') }}
                                    </Button>
                                    <Button type="success" @click="doSurvey" v-else>
                                        <Icon type="md-checkmark-circle-outline" />
                                        {{ $t('jyzx.offline.answered') }}
                                    </Button>
                                </div>
                            </div>
                            <!-- 评测 -->
                            <div class="submitarea" v-if="resource.settings.includes('exam') && examInfo">
                                <dt class="headeicon"><span class="headeicontitle">{{ $t('jyzx.offline.exam') }}</span></dt>
                                <div class="target">
                                    <span class="info-label">{{ $t('jyzx.offline.examName') }}：</span><span>{{ examInfo.name }}</span>
                                </div>
                                <div class="target">
                                    <span class="info-label">{{ $t('jyzx.offline.examDes') }}：</span><span>{{ examInfo.description }}</span>
                                </div>
                                <!-- <div v-if="resource.detail.hwTime">
                                    <span class="info-label">结束时间：</span><span>{{ resource.detail.hwTime }}</span>
                                </div> -->
                                <div class="target hw-style">
                                    <Button type="primary" @click="doExam" v-if="!isExam">
                                        <Icon type="ios-create" />
                                        {{ $t('jyzx.offline.examAnswer') }}
                                    </Button>
                                    <Button type="success" @click="doExam" v-else>
                                        <Icon type="md-checkmark-circle-outline" />
                                        {{ $t('jyzx.offline.answered') }}
                                    </Button>
                                    <span class="ansShow" v-show="isExam">
                                        {{ $t('jyzx.offline.right') }}：{{ rightNum }} {{ $t('jyzx.offline.topic') }}，
                                        {{ $t('jyzx.offline.error') }}：{{ wrongNum }}{{ $t('jyzx.offline.topic') }}
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <Modal v-model="surveyStatus" :title="$t('jyzx.offline.feedback')" width="800" @on-ok="saveSurvey">
            <DoSurvey v-if="surveyInfo" :survey="surveyInfo" @answer-change="getSurveyData" />
        </Modal>
        <Modal v-model="examStatus" :title="$t('jyzx.offline.answerExam')" width="800" @on-ok="saveExam">
            <DoExam v-if="examInfo" :exam="examInfo" @answer-change="getExamData" @have-answer="haveAns" />
        </Modal>
    </div>
</template>

<script>
import DoSurvey from './DoSurvey.vue'
import DoExam from './DoExam.vue'
import BlobTool from "@/utils/blobTool.js"
import { mapGetters } from 'vuex'
export default {
    components: {
        DoSurvey,
        DoExam
    },
    data() {
        return {
            myAnswer: [],
            itemCount: 0,
            isSurvey: false, //问卷是否作答
            surveyStatus: false, //问卷弹框
            surveyInfo: undefined, //问卷信息
            isExam: false,
            examStatus: false,
            examInfo: undefined,
            rightNum: 0,
            wrongNum: 0,
            rightAns: [],
            defImg: 'https://www.habook.com.cn/data/editor/images/img/20210429%2001/001.png',
            isLoading: false,
            activity: [],
            resource: {},
            actType: [],
            activeIndex: 0,
            fileDownload: false,
            successicon: false,
            homeWork: "", //上传的作业
            workInfo: undefined, //作业信息
            allteach:[],//所有老师
            ansShow: false, //是否合格：2:不合格  1:合格
            targets: [], //学习对象
        }
    },
    created() {
        this.actType = this.$GLOBAL.TRAIN_TYPE()
        this.$store.dispatch('user/getSchoolTeacher').then(
            res=>{ 
                this.allteach=this.teachers
            },
            error=>{
                this.$Message.error('获取所有教师API异常')
            }
        )
    },
     mounted() {
        this.getAllAct()
     },
    methods: {
        // 作答问卷
        getSurveyData(data) {
            // 获取作答数据：data
            this.myAnswer = data.answer
            this.itemCount = data.count
        },
        saveSurvey() {
            if(this.myAnswer.length && this.myAnswer.length == this.itemCount && !this.myAnswer.includes(undefined)) {
                let params = {
                    "userid": this.$store.state.userInfo.TEAMModelId,
                    "code": this.surveyInfo.code,
                    "id": this.surveyInfo.id,
                    record: this.myAnswer.map(i => Array.isArray(i) ? i : [i])
                }
                this.$api.jyzx.answerSurvey(params).then(res => {
                    if(res.code == 200) {
                        this.isSurvey = true
                        this.$Message.success(this.$t("jyzx.offline.success1"))
                    } else {
                        this.$Message.warning(this.$t("jyzx.offline.error1"))
                    }
                })
            } else if(this.myAnswer.length) {
                this.$Message.warning(this.$t("jyzx.offline.message1"))
            }
            
        },
        // 作答评测
        getExamData(data) {
            // 获取作答数据：data
            this.myAnswer = data.answer
            this.itemCount = data.count
            this.rightAns = data.rightAns
        },
        // 已有答案
        haveAns(data) {
            this.judgeSub(data.answer, data.rightAns)
        },
        // 判断作对几题
        judgeSub(ans, rightAns) {
            var rNum = rightAns.length;
            var hNum = 0;
            ans.forEach((ha, hi) => {
                let ii = 0
                if(rightAns[hi].length == ha.length) {
                    ha.forEach(hChild => {
                        rightAns[hi].forEach(rChild => {
                            if(hChild == rChild) {
                                ii++
                            }
                        })
                    })
                    if(ii == rightAns[hi].length) {
                        hNum++
                    }
                }
            })
            this.rightNum = hNum
            this.wrongNum = rNum - hNum
        },
        saveExam() {
            if(this.myAnswer.length && this.myAnswer.length == this.itemCount && !this.myAnswer.includes(undefined)) {
                this.myAnswer = this.myAnswer.map(i => Array.isArray(i) ? i : [i])
                this.judgeSub(this.myAnswer, this.rightAns)
                let params = {
                    id: this.examInfo.id,
                    code: this.$store.state.userInfo.schoolCode,
                    tId: this.$store.state.userInfo.TEAMModelId,
                    ans: this.myAnswer
                }
                this.$api.jyzx.submitExam(params).then(res => {
                    if(res.code == 200) {
                        this.$Message.success(this.$t("jyzx.offline.success1"))
                        this.isExam = true
                    }
                })
            }
            else if(this.myAnswer.length) {
                this.$Message.warning(this.$t("jyzx.offline.message2"))
            }
        },
        doSurvey() {
            this.surveyStatus = true
        },
        doExam() {
            this.examStatus = true
        },
        // 活动列表
        getAllAct() {
            let req = {type: "Study"}
            this.$api.jyzx.getAllActivity(req).then((res) => {
                if (res.datas.length) {
                    res.datas.map((item) => {
                        item.startTime = this.dateFormat(item.startTime)
                        item.endTime = this.dateFormat(item.endTime)
                    })
                    this.activity = res.datas.reverse()
                    this.getApiAct()
                }
            })
        },
        getActivityInfo(activity, index) {
            this.activeIndex = index
            this.getApiAct()
        },
        // 查询活动的信息
        getApiAct() {
            this.targets.length = 0
            this.resource={}
            this.homeWork = ""
            let req = {
                code: this.$store.state.userInfo.schoolCode,
                id: this.activity[this.activeIndex].id,
            }
            this.$api.train.findSummaryTrain(req).then((res) => {
                if(res.status == 404) {
                    this.$Modal.confirm({
                        title: this.$t("studentWeb.vote.delTitle"),
                        okText: this.$t("studentWeb.vote.delOk"),
                        cancelText: this.$t("studentWeb.vote.delCancel"),
                        onOk: () => {
                            this.delActivity(this.activity[this.activeIndex])
                        }
                    })
                } else if(res.status == 200) {
                    if (res.study) {
                        this.getTarget(res.study.tchLists)

                        res.study.startTime = this.dateFormat(
                            res.study.startTime
                        )
                        res.study.endTime = this.dateFormat(
                            res.study.endTime
                        )
                        /* if (res.study.detail.hwTime) {
                            res.study.detail.hwTime = this.dateFormat(
                                res.study.detail.hwTime
                            )
                        } */

                        this.actType.map((item) => {
                            if (item.value == res.study.type) {
                                res.study.typeName = item.label
                            }
                        })
                        if (!res.study.desc) {
                            res.study.desc = "暂无"
                        }

                        res.study.joinNum = res.teachers.length
                        /* let hWork = res.study.teachers.filter((item) => {
                            return item.id == this.$store.state.userInfo.TEAMModelId
                        })
                        if (hWork[0].hw) {
                            this.homeWork = hWork[0].hw.substring(hWork[0].hw.lastIndexOf("/") + 1)
                        } */
                        
                        this.resource = res.study
                        if (this.resource.settings.includes('survey')) {
                            this.getSurveyInfo(this.resource.surveyId)
                        }
                        if (this.resource.settings.includes('exam')) {
                            this.myAnswer = []
                            this.getExam(this.resource.examId)
                        }
                        if (this.resource.settings.includes('hw')) {
                            this.getWork(this.resource.workId)
                        }
                        this.getcreatd()
                    }
                }
            })
        },
        // 删除不存在的投票
        delActivity(item) {
            let param = {
                code: item.code,
                id: item.id,
                role: "teacher"
            }
            this.$api.jyzx.delActivity(param).then(res => {
                if(res) {
                    if(res.status == 200) {
                        this.$Message.success(this.$t("studentWeb.vote.delSuccess"))
                        this.activity.splice(this.activeIndex, 1)
                        if(this.activeIndex == this.activity.length) {
                            this.activeIndex = 0
                        }
                        this.getApiAct()
                    }
                }
            }).finally(()=>{
            })
        },
        //处理创建者name和参与人name
        getcreatd() {
            var createdId = this.resource.creatorId
            var detailsDatas = this.resource
            var allteachs = this.allteach
            for(let i in allteachs) {
                if(allteachs[i].id === createdId) {
                    detailsDatas.createdName = allteachs[i].name
                }
            }
            var teachArr = this.resource.teachers
            var teachnameArr = []
            for(var i = 0; i < teachArr.length; i++) {
                var teachId = teachArr[i].id
                let crew = allteachs.find((n) => n.id === teachId)
                if(crew) {
                    teachnameArr.push(crew)
                }
                //console.log(allteachs.find((n)=>n.id===teachId),'添加到数据的人')   
            }
            /* for(var r = 0; r < allteachs.length; r++) {
                if(allteachs[r].id === '1528783259') {
                    console.log(allteachs[r],'找到了')
                } else {
                    console.log('没有找到这个人')
                }
            } */
            detailsDatas.teachers = teachnameArr
            this.resource = detailsDatas
        },
        getTarget(targets) {
            let params = {
                school_code: this.$store.state.userInfo.schoolCode,
                ids: targets
            }
            this.$api.learnActivity.findResearchList(params).then(res => {
                if(!res.error) {
                    let list = []
                    res.list.map(item => {
                        list.push(item.class.name)
                    })
                    this.targets = list
                }
            })
        },
        getSurveyInfo(surveyId) {
            let params = {
                id: surveyId,
                code: 'Survey-' + this.$store.state.userInfo.schoolCode
            }
            this.$api.questionnaire.FindSurveysSummary(params).then(
                res => {
                    if (res.survey) {
                        this.surveyInfo = res.survey
                        /* res.survey.teachers.forEach(item => {
                            item.answer = item.answer || []
                        }) */

                        /* let tea = res.survey.teachers.find(item => {
                            return item.id == this.$store.state.userInfo.TEAMModelId
                        })
                        if (tea) {
                            this.isSurvey = !!tea.time
                        } */
                    }
                }
            )
        },
        getExam(examId) {
            let params = {
                id: examId,
                code: this.$store.state.userInfo.schoolCode
            }
            this.$api.ability.getExamSummary(params).then(
                res => {
                    if (res.examLite) {
                        res.examLite.teachers.forEach(item => {
                            item.answer = item.answer || []
                        })
                        this.examInfo = res.examLite

                        let tea = res.examLite.teachers.find(item => {
                            return item.id == this.$store.state.userInfo.TEAMModelId
                        })
                        if (tea) {
                            this.isExam = !!tea.time
                        }
                    }
                }
            )
        },
        getWork(workId) {
            let params = {
                id: workId,
                code: this.$store.state.userInfo.schoolCode
            }
            this.$api.ability.getWorkSummary(params).then(
                res => {
                    if (res.works.length) {
                        this.workInfo = res.works[0]
                        if(res.works[0].teachers.length) {
                            console.log(111111);
                            res.works[0].teachers.forEach(item => {
                                if(item.id == this.$store.state.userInfo.TEAMModelId) {
                                    this.homeWork = item.hw.substring(item.hw.lastIndexOf("/") + 1)
                                }
                            })
                        }
                    }
                }
            )
        },
        // 上传作业
        customUpload(file) {
            let sas = this.$store.state.user.schoolProfile.blob_sas
            let blobUrl = JSON.parse(
                decodeURIComponent(localStorage.school_profile, "utf-8")
            ).blob_uri
            let host = blobUrl.substring(0, blobUrl.lastIndexOf("/"))
            let cont = blobUrl.substring(blobUrl.lastIndexOf("/") + 1)
            // 创建一个blob盒子，装文件
            let blobTool = new BlobTool(host, cont, "?" + sas, "school")
            let path = `train/${this.activity[this.activeIndex].id}`
            blobTool.upload(file, path).then(
                (res) => {
                    let req = {
                        id: this.workInfo.id,
                        code: this.$store.state.userInfo.schoolCode,
                        tId: this.$store.state.userInfo.TEAMModelId,
                        ans: res.blob, //文件地址
                    }
                    this.$api.train.uploadHw(req).then((resHW) => {
                        if (resHW.code === 200) {
                            this.homeWork = res.name
                            this.$Message.success(this.$t("jyzx.offline.success2"))
                        } else {
                            this.$Message.warning(this.$t("jyzx.offline.error1"))
                        }
                    })
                }
            )
            return false
        },
        dateFormat(timestamp) {
            let date = new Date(timestamp)
            let Y = date.getFullYear()
            let M = date.getMonth()
            let D = date.getDate()
            let H = date.getHours()
            let MIN = date.getMinutes()
            return `${Y}-${M < 9 ? "0" + (M + 1) : M + 1}-${D} ${H < 10 ? "0" + H : H
                }:${MIN < 10 ? "00" : MIN}`
        },
    },

    computed: {
        ...mapGetters({
            teachers: 'user/getSchoolUserJoined', // 取得已加入此學校的使用者
        })
    }
}
</script>

<style lang="less" scoped>
@import "./offline.less";
</style>
<style lang="less">
.offline {
    .ivu-form .ivu-form-item-label,
    .ivu-input {
        font-weight: bold;
    }
    /* .ivu-upload {
    display: inline-block;
} */
}
</style>