<template>
    <div class="train-detail-container">
        <vuescroll>
            <div class="detail-wrap">
                <div class="detail-left">
                    <div class="back-item" @click="toTrainMgt">
                        <Icon type="md-arrow-round-back" size="20" />
                        <span style="margin-left:10px">返回研修总览</span>
                    </div>
                    <div class="train-top-info">
                        <div class="img-box" :style="{backgroundImage: `url(${trainInfo.img || defImg})`}"></div>
                        <div class="infos">
                            <p class="title">
                                <span>{{trainInfo.topic}}</span>
                                <span class="hour">{{trainInfo.hour}}学时</span>
                            </p>
                            <div class="info-item">
                                <span class="info-label">
                                    主讲老师：
                                </span>
                                <span>
                                    {{trainInfo.presenter}}
                                </span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">
                                    培训主题：
                                </span>
                                <span>
                                    {{trainInfo.topic}}
                                </span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">
                                    培训地点：
                                </span>
                                <span>
                                    {{trainInfo.address}}
                                </span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">
                                    培训时间：
                                </span>
                                <span>
                                    <span>{{dateFormat(trainInfo.startTime) + ' 至 ' + dateFormat(trainInfo.endTime)}}</span>
                                    <!-- {{trainInfo.time.join(' 至 ')}} -->
                                </span>
                            </div>
                        </div>
                        <p class="train-detail-text" @click.prevent="delAreaTrain">
                            删除
                        </p>
                    </div>
                    <div class="select-school-wrap">
                        <span>学校：</span>
                        <Select v-model="curSchool" style="width:300px" @on-change="getTableData">
                            <Option v-for="item in schoolList" :value="item.id" :key="item.id">{{ item.sname }}</Option>
                        </Select>
                    </div>
                    <div class="train-data-wrap">
                        <Tabs v-model="tabName">
                            <TabPane label="学时审核" name="name" class="tab-pane-wrap" style="height:600px">
                                <Table :columns="columns" :data="tableData" class="table-box" :height="580">
                                    <template slot-scope="{ row,index }" slot="action">
                                        <Button type="success" size="small" @click="audit(index,1)">通过</Button>
                                        <Button type="error" size="small" @click="audit(index,2)" style="margin-left:5px">不通过</Button>
                                    </template>
                                    <template slot-scope="{ row,index }" slot="signTime">
                                        <span>{{dateFormat(row.signTime)}}</span>
                                    </template>
                                    <template slot-scope="{ row,index }" slot="hwTime">
                                        <span>{{dateFormat(row.hwTime)}}</span>
                                    </template>
                                    <template slot-scope="{ row,index }" slot="surveyTime">
                                        <span>{{dateFormat(row.surveyTime)}}</span>
                                    </template>
                                    <template slot-scope="{ row,index }" slot="examTime">
                                        <span>{{dateFormat(row.examTime)}}</span>
                                    </template>
                                    <template slot-scope="{ row,index }" slot="status">
                                        <span :style="{color:row.status == 0 ? '#ff9900' : row.status == 1 ? '#19be6b' : '#ed4014'}">
                                            {{row.status == 0 ? '未审核' : row.status == 1 ? '已通过' : '未通过'}}
                                        </span>
                                    </template>
                                </Table>
                            </TabPane>
                            <TabPane label="签到详情" name="name1" class="tab-pane-wrap" v-if="trainInfo.settings.includes('sign')">
                                <Table :columns="signColumns" :data="tableData" class="table-box" :height="580">
                                    <template slot-scope="{ row,index }" slot="signTime">
                                        <span>{{dateFormat(row.signTime)}}</span>
                                    </template>
                                    <template slot-scope="{ row,index }" slot="signStatus">
                                        <span :style="{color:row.sign ? row.sign == 1 ? '#19be6b' : '#ff9900' : '#ed4014'}">
                                            {{row.sign ? row.sign == 1 ? '已签到' : '迟到' : '未签到'}}
                                        </span>
                                    </template>
                                </Table>
                            </TabPane>
                            <TabPane label="作业详情" name="name2" class="tab-pane-wrap" v-if="trainInfo.settings.includes('hw')">
                                <Table :columns="hwColumns" :data="tableData" class="table-box" :height="580">
                                    <template slot-scope="{ row,index }" slot="hwTime">
                                        <span>{{dateFormat(row.hwTime)}}</span>
                                    </template>
                                    <template slot-scope="{ row,index }" slot="action">
                                        <Button type="primary" size="small" :disabled="!row.hwTime" @click="viewHw(index)">查看</Button>
                                        <Button style="margin-left:8px" type="success" size="small" :disabled="!row.hwTime" @click="downloadFile(row.url, row.hw)">下载</Button>
                                    </template>
                                </Table>
                            </TabPane>
                            <TabPane label="问卷反馈" name="name3" class="tab-pane-wrap" v-if="trainInfo.settings.includes('survey')" style="height:600px">
                                <Table :columns="surveyColumns" :data="tableData" class="table-box" :height="580">
                                    <template slot-scope="{ row }" slot="surveytTime">
                                        <span>{{dateFormat(row.time)}}</span>
                                    </template>
                                    <template slot-scope="{ row,index }" slot="action">
                                        <Button type="primary" size="small" :disabled="!row.time" @click="toViewSurvey(index)">
                                            {{row.time ? '查看详情' : '暂未作答'}}
                                        </Button>
                                    </template>
                                </Table>
                            </TabPane>
                            <TabPane label="评测反馈" name="name4" class="tab-pane-wrap" v-if="trainInfo.settings.includes('exam')" style="height:600px">
                                <Table :columns="examColumns" :data="tableData" class="table-box" :height="580">
                                    <template slot-scope="{ row }" slot="examTime">
                                        <span>{{dateFormat(row.examTime)}}</span>
                                    </template>
                                    <template slot-scope="{ row,index }" slot="action">
                                        <Button type="primary" size="small" :disabled="!row.examTime" @click="toViewExam(index)">
                                            {{row.examTime ? '查看详情' : '暂未作答'}}
                                        </Button>
                                    </template>
                                </Table>
                            </TabPane>
                        </Tabs>
                    </div>
                </div>
                <div class="detail-right">
                    <Card style="width:100%" :bordered="false" v-if="trainInfo.settings.includes('sign')">
                        <p slot="title">
                            <Icon type="ios-film-outline"></Icon>
                            签到码
                        </p>
                        <div class="my-card-content">
                            <div id="sign-qr-code"></div>
                            <div class="qr-code-setting">
                                <div class="qr-code-item">
                                    <span class="qr-code-label">是否开始签到：</span>
                                    <i-switch v-model="isOpen" @on-change="toggleOpen" />
                                </div>
                                <div class="qr-code-item">
                                    <span class="qr-code-label">定时刷新(10s)：</span>
                                    <i-switch v-model="isFresh" @on-change="freshQRcode" />
                                </div>
                                <div class="qr-code-item">
                                    <Button type="primary" size='small' style="width:100%" @click="showFull">全屏显示</Button>
                                </div>
                            </div>
                        </div>
                    </Card>
                    <Card style="width:100%;margin-top:30px" :bordered="false" v-if="trainInfo.settings.includes('sign')">
                        <p slot="title">
                            <Icon type="ios-film-outline"></Icon>
                            签到统计
                        </p>
                        <div class="my-card-content">
                            <div>
                                <p>
                                    <span class="num-info success-color">
                                        {{signData.signed}}
                                        <span style="font-size:14px">人</span>
                                    </span>
                                    <span>
                                        签到成功
                                    </span>
                                </p>
                                <p>
                                    <span class="num-info warning-color">
                                        {{signData.late}}
                                        <span style="font-size:14px">人</span>
                                    </span>
                                    <span>
                                        迟到
                                    </span>
                                </p>
                                <p>
                                    <span class="num-info error-color">
                                        {{signData.unsign}}
                                        <span style="font-size:14px">人</span>
                                    </span>
                                    <span>
                                        未签到
                                    </span>
                                </p>
                            </div>
                            <i-circle :percent="80" stroke-color="#19be6b" :size="100">
                                <p style="font-size:30px;">{{signData.rate}}%</p>
                                <p style="font-size:12px;margin-top:10px">签到率</p>
                            </i-circle>
                        </div>
                    </Card>
                    <Card style="width:100%;margin-top:30px" :bordered="false" v-if="trainInfo.settings.includes('hw')">
                        <p slot="title">
                            <Icon type="ios-film-outline"></Icon>
                            作业统计
                        </p>
                        <div class="my-card-content">
                            <div>
                                <p>
                                    <span class="num-info success-color">
                                        {{hwData.uploaded}}
                                        <span style="font-size:14px">人</span>
                                    </span>
                                    <span>
                                        已提交
                                    </span>
                                </p>
                                <p>
                                    <span class="num-info error-color">
                                        {{hwData.unupload}}
                                        <span style="font-size:14px">人</span>
                                    </span>
                                    <span>
                                        未提交
                                    </span>
                                </p>
                            </div>
                            <i-circle :percent="80" stroke-color="#ff9900" :size="100">
                                <p style="font-size:30px;">{{hwData.rate}}%</p>
                                <p style="font-size:12px;margin-top:10px">提交率</p>
                            </i-circle>
                        </div>
                    </Card>
                    <Card style="width:100%;margin-top:30px" :bordered="false" v-if="trainInfo.settings.includes('survey')">
                        <p slot="title">
                            <Icon type="ios-film-outline"></Icon>
                            问卷统计
                        </p>
                        <div class="my-card-content">
                            <div>
                                <p>
                                    <span class="num-info success-color">
                                        {{surveyData.uploaded}}
                                        <span style="font-size:14px">人</span>
                                    </span>
                                    <span>
                                        已提交
                                    </span>
                                </p>
                                <p>
                                    <span class="num-info error-color">
                                        {{surveyData.unupload}}
                                        <span style="font-size:14px">人</span>
                                    </span>
                                    <span>
                                        未提交
                                    </span>
                                </p>
                            </div>
                            <i-circle :percent="80" stroke-color="#ff9900" :size="100">
                                <p style="font-size:30px;">{{surveyData.rate}}%</p>
                                <p style="font-size:12px;margin-top:10px">提交率</p>
                            </i-circle>
                        </div>
                    </Card>
                    <Card style="width:100%;margin-top:30px" :bordered="false" v-if="trainInfo.settings.includes('exam')">
                        <p slot="title">
                            <Icon type="ios-film-outline"></Icon>
                            评测统计
                        </p>
                        <div class="my-card-content">
                            <div>
                                <p>
                                    <span class="num-info success-color">
                                        {{examData.uploaded}}
                                        <span style="font-size:14px">人</span>
                                    </span>
                                    <span>
                                        已作答
                                    </span>
                                </p>
                                <p>
                                    <span class="num-info error-color">
                                        {{examData.unupload}}
                                        <span style="font-size:14px">人</span>
                                    </span>
                                    <span>
                                        未作答
                                    </span>
                                </p>
                            </div>
                            <i-circle :percent="80" stroke-color="#ff9900" :size="100">
                                <p style="font-size:30px;">{{examData.rate}}%</p>
                                <p style="font-size:12px;margin-top:10px">提交率</p>
                            </i-circle>
                        </div>
                    </Card>
                    <Card style="width:100%;margin-top:30px" :bordered="false">
                        <p slot="title">
                            <Icon type="ios-film-outline"></Icon>
                            学时审核
                        </p>
                        <div class="my-card-content">
                            <div>
                                <p>
                                    <span class="num-info warning-color">
                                        {{hourData.uncheck}}
                                        <span style="font-size:14px">人</span>
                                    </span>
                                    <span>
                                        未审核
                                    </span>
                                </p>
                                <p>
                                    <span class="num-info success-color">
                                        {{hourData.pass}}
                                        <span style="font-size:14px">人</span>
                                    </span>
                                    <span>
                                        通过
                                    </span>
                                </p>
                                <p>
                                    <span class="num-info error-color">
                                        {{hourData.fail}}
                                        <span style="font-size:14px">人</span>
                                    </span>
                                    <span>
                                        不通过
                                    </span>
                                </p>
                            </div>
                            <i-circle :percent="80" :size="100">
                                <p style="font-size:30px;">{{hourData.rate}}%</p>
                                <p style="font-size:12px;margin-top:10px">通过率</p>
                            </i-circle>
                        </div>
                    </Card>
                </div>
            </div>
        </vuescroll>
        <div class="qr-code-wrap" v-show="showQrStatus" @click="showQrStatus = false">
            <div class="qr-code-info" @click.stop>
                <div id="fullqrcode" :class="showQrStatus ? 'animated fadeIn':'animated fadeOut'" ref="qrcode" style="padding:20px 50px 40px 50px;background-color:white;margin:auto;">
                    <p class="qr-code-title">
                        扫码签到
                    </p>
                </div>
            </div>
        </div>
        <Modal v-model="hwViewStatus" title="查看作业" width="900">
            <p v-if="tableData[viewIndex]" class="tea-info-item">
                <span class="tea-info-label">教师姓名：</span>
                <span>{{tableData[viewIndex].name}}</span>
            </p>
            <p v-if="tableData[viewIndex]" class="tea-info-item">
                <span class="tea-info-label">上传时间：</span>
                <span>{{dateFormat(tableData[viewIndex].hwTime)}}</span>
            </p>
            <p v-if="tableData[viewIndex]" class="tea-info-item">
                <span class="tea-info-label">作业附件：</span>
                <span>{{getFileName(tableData[viewIndex].hw)}}</span>
            </p>

            <div v-if="tableData[viewIndex]">
                <video v-if="tableData[viewIndex].fileType == 'video'" id="previewVideo" :src="tableData[viewIndex].url" width="870" controls="controls" style="max-height: 800px;">
                    {{$t('teachContent.tips8')}}
                </video>
                <audio v-else-if="tableData[viewIndex].fileType == 'audio'" controls>
                    <source :src="tableData[viewIndex].url">
                    {{$t('teachContent.notAudio')}}
                </audio>
                <img v-else-if="tableData[viewIndex].fileType == 'image'" :src="tableData[viewIndex].url" style="border-radius: 5px;max-height: 800px;max-width:870px;" />
                <iframe v-else-if="tableData[viewIndex].extension == 'PDF'" :src="'/web/viewer.html?file=' + escapeBlobUrl(tableData[viewIndex].url)" width='870' height='700' frameborder='1'></iframe>
                <iframe v-else-if="tableData[viewIndex].fileType == 'doc'" :src="'https://view.officeapps.live.com/op/view.aspx?src=' + escapeBlobUrl(tableData[viewIndex].url)" width='870' height='700' frameborder='1'></iframe>
                <div v-else>
                    <p>文件类型不支持线上预览，请下载文件</p>
                    <Button @click="downloadFile(tableData[viewIndex].url, tableData[viewIndex].hw)">
                        <Icon type="md-cloud-download" />下载文件
                    </Button>
                </div>
            </div>
        </Modal>
        <Modal v-model="surveyStatus" title="作答详情" width="800">
            <SurveyDetail v-if="surveyInfo && tableData[surveyIndex]" :survey="surveyInfo" :answer="tableData[surveyIndex].surveyAnswer" :schoolInfo="schoolInfo"></SurveyDetail>
        </Modal>
        <Modal v-model="examStatus" title="作答详情" width="800">
            <SurveyDetail v-if="examInfo && tableData[examIndex]" :survey="examInfo" :answer="tableData[examIndex].examAnswer || []" :schoolInfo="schoolInfo"></SurveyDetail>
        </Modal>
    </div>
</template>
<script>
import QRCode from 'qrcodejs2'
import jwtDecode from 'jwt-decode'
import SurveyDetail from './SurveyDetail.vue'
export default {
    components: {
        SurveyDetail
    },
    data() {
        return {
            curSchool: '',
            schoolList: [],
            trainList: [],
            allTeacherList: [],
            examAllData: [],
            workAllData: [],
            surveyAllData: [],
            hwAndSignData: [],
            examStatus: false,
            examIndex: 0,
            areaId: sessionStorage.getItem('areaId'),
            examInfo: undefined,
            surveyIndex: 0,
            surveyStatus: false,
            surveyInfo: undefined,
            viewIndex: 0,
            hwViewStatus: false,
            fullQR: undefined,
            showQrStatus: false,
            isOpen: false,
            isFresh: false,
            signQRcode: undefined,
            timer: undefined, //定时任务
            defImg: 'https://www.habook.com.cn/data/editor/images/img/20210429%2001/001.png',
            tabName: 'name',
            trainInfo: {
                settings: []
            },
            columns: [
                {
                    title: '姓名',
                    key: 'name',
                    align: 'center'
                }
            ],
            signColumns: [
                {
                    title: '姓名',
                    key: 'name',
                    align: 'center'
                },
                {
                    title: '签到时间',
                    slot: 'signTime',
                    align: 'center',
                    sortable: true
                },
                {
                    title: '状态',
                    slot: 'signStatus',
                    align: 'center'
                }
            ],
            hwColumns: [
                {
                    title: '姓名',
                    key: 'name',
                    align: 'center'
                },
                {
                    title: '提交时间',
                    slot: 'hwTime',
                    align: 'center',
                    sortable: true
                },
                {
                    title: '操作',
                    slot: 'action',
                    align: 'center'
                }
            ],
            surveyTableData: [],
            surveyColumns: [
                {
                    title: '姓名',
                    key: 'name',
                    align: 'center'
                },
                {
                    title: '作答时间',
                    slot: 'surveytTime',
                    align: 'center',
                    sortable: true
                },
                {
                    title: '操作',
                    slot: 'action',
                    align: 'center'
                }
            ],
            examColumns: [
                {
                    title: '姓名',
                    key: 'name',
                    align: 'center'
                },
                {
                    title: '作答时间',
                    slot: 'examTime',
                    align: 'center',
                    sortable: true
                },
                {
                    title: '操作',
                    slot: 'action',
                    align: 'center'
                }
            ],
            examTableData: [],
            tableData: []
        }
    },
    computed: {
        schoolInfo() {
            let d = this.schoolList.find(item => {
                return item.id == this.curSchool
            })
            if (d) {
                return d
            } else {
                return {}
            }
        },
        signData() {
            let data = {
                all: 0,
                signed: 0,
                unsign: 0,
                late: 0,
                rate: 0
            }
            if (this.hwAndSignData) {
                this.hwAndSignData.forEach(item => {
                    data.all += item.count
                    data.signed += item.signCount
                })
                data.unsign = data.all - data.signed
                data.rate = (data.signed * 100 / data.all).toFixed(1)
            }
            return data
        },
        hwData() {
            let data = {
                all: this.tableData.length,
                uploaded: 0,
                unupload: 0,
                rate: 0
            }
            if (this.workAllData) {
                this.workAllData.forEach(item => {
                    data.all += item.count
                    data.uploaded += item.ansCount
                })
                data.unupload = data.all - data.uploaded
                data.rate = (data.uploaded * 100 / data.all).toFixed(1)
            }
            return data
        },
        hourData() {
            let data = {
                all: this.tableData.length,
                fail: 0,
                pass: 0,
                uncheck: 0,
                rate: 0
            }
            data.uncheck = this.tableData.filter(item => {
                return item.status == 0
            }).length
            data.pass = this.tableData.filter(item => {
                return item.status == 1
            }).length
            data.fail = this.tableData.filter(item => {
                return item.status == 2
            }).length
            data.rate = (data.pass * 100 / data.all).toFixed(1)
            return data
        },
        surveyData() {
            let data = {
                all: 0,
                uploaded: 0,
                unupload: 0,
                rate: 0
            }
            if (this.surveyAllData) {
                this.surveyAllData.forEach(item => {
                    data.all += item.count
                    data.uploaded += item.ansCount
                })
                data.unupload = data.all - data.uploaded
                data.rate = (data.uploaded * 100 / data.all).toFixed(1)
            }

            return data
        },
        examData() {
            let data = {
                all: 0,
                uploaded: 0,
                unupload: 0,
                rate: 0
            }
            if (this.examAllData) {
                this.examAllData.forEach(item => {
                    data.all += item.count
                    data.uploaded += item.ansCount
                })
                data.unupload = data.all - data.uploaded
                data.rate = (data.uploaded * 100 / data.all).toFixed(1)
            }
            return data
        }
    },
    methods: {
        delAreaTrain() {
            this.$Modal.confirm({
                title: '删除研修活动',
                content: '删除区级活动后，相关学校将无法参与此活动，确认删除活动吗？',
                onOk: () => {
                    let params = {
                        id: this.trainList[0].pId,
                        areaId: this.areaId,
                        pk: 'Study'
                    }
                    this.$api.train.delAreaTrain(params).then(
                        res => {
                            this.$Message.success('删除成功')
                            this.toTrainMgt()
                        },
                        err => {
                            this.$Message.error('删除失败')
                        }
                    )
                }
            })
        },
        downloadFile(url, hw) {
            const downloadRes = async () => {
                let response = await fetch(url); // 内容转变成blob地址
                let blob = await response.blob();  // 创建隐藏的可下载链接
                let objectUrl = window.URL.createObjectURL(blob);
                let a = document.createElement('a');
                a.href = objectUrl;
                a.download = this.getFileName(hw);
                a.click()
                a.remove()
            }
            downloadRes()
        },
        escapeBlobUrl(url) {
            return encodeURIComponent(url)
        },
        audit(index, status) {
            let params = {
                id: this.trainInfo.id,
                tId: this.tableData[index].id,
                code: this.$store.state.userInfo.schoolCode,
                type: status
            }
            this.$api.ability.AuditStudy(params).then(
                res => {
                    this.$Message.success('保存成功')
                    this.tableData[index].status = status
                },
                err => {
                    this.$Message.error('保存失败')
                }
            )
        },
        toViewSurvey(index) {
            this.surveyIndex = index
            this.surveyStatus = true
        },
        toViewExam(index) {
            this.examIndex = index
            this.examStatus = true
        },
        getSurveyInfo() {
            let tInfo = this.trainList.find(item => {
                return item.school == this.curSchool
            })
            if (tInfo) {
                let params = {
                    id: tInfo.surveyId,
                    code: tInfo.school
                }
                this.$api.ability.getSurveySummary(params).then(
                    res => {
                        if (res.trSurveys && res.trSurveys[0]) {
                            res.trSurveys[0].teachers.forEach(item => {
                                item.answer = item.answer || []
                            })
                            this.surveyInfo = res.trSurveys[0]
                            this.surveyTableData = this.surveyInfo.teachers
                            this.tableData.forEach(item => {
                                let t = this.surveyTableData.find(s => {
                                    return item.id == s.id
                                })
                                if (t) {
                                    item.surveyTime = t.time
                                    item.answer = t.answer
                                }
                            })
                            let data = JSON.parse(JSON.stringify(this.tableData))
                            console.log('后面的数据', data)
                            this.tableData = []
                            this.tableData = data
                        }
                    },
                    err => {

                    }
                )
            }
        },
        getExamInfo() {
            let tInfo = this.trainList.find(item => {
                return item.school == this.curSchool
            })
            if (tInfo) {
                let params = {
                    id: tInfo.examId,
                    code: tInfo.school
                }
                this.$api.ability.getExamSummary(params).then(
                    res => {
                        if (res.examLite) {
                            // let schoolTeacher = this.allTeacherList.find(item => { item.school == this.curSchool })
                            if (this.tableData) {
                                console.log('表格数据', this.tableData)
                                res.examLite.teachers.forEach(item => {
                                    let curT = this.tableData.find(t => {
                                        return t.id == item.id
                                    })
                                    console.log('123', curT)
                                    if (curT) {
                                        curT.examTime = item.time
                                        curT.examAnswer = item.answer
                                    }
                                })
                                this.examInfo = res.examLite
                                let data = JSON.parse(JSON.stringify(this.tableData))
                                this.tableData = []
                                this.tableData = data
                            }
                        }
                    },
                    err => {

                    }
                )
            }
        },
        getWorkInfo() {
            let tInfo = this.trainList.find(item => {
                return item.school == this.curSchool
            })
            if (tInfo) {
                let params = {
                    id: tInfo.workId,
                    code: tInfo.school
                }
                this.$api.ability.getWorkSummary(params).then(
                    async res => {
                        let sasData = await this.$tools.getSchoolSas()
                        if (res.works && res.works.length) {
                            if (this.tableData) {
                                res.works[0].teachers.forEach(item => {
                                    let curT = this.tableData.find(t => {
                                        return t.id == item.id
                                    })
                                    if (curT) {
                                        let info = this.getExAndType(item.hw)
                                        curT.fileType = info.type
                                        curT.extension = info.ex
                                        curT.hwTime = item.hwTime
                                        curT.hw = item.hw
                                        curT.url = `${sasData.url}/${sasData.name}${item.hw}${sasData.sas}`
                                    }
                                })
                                this.workInfo = res.works[0]
                                let data = JSON.parse(JSON.stringify(this.tableData))
                                this.tableData = []
                                this.tableData = data
                            }
                        }
                    },
                    err => {

                    }
                )
            }
        },
        getFileName(blob) {
            if (blob) {
                return blob.substring(blob.lastIndexOf('/') + 1)
            }
        },
        viewHw(index) {
            this.viewIndex = index
            this.hwViewStatus = true
        },
        toggleOpen() {
            this.createQRCode()
            this.fullQRcode()
        },
        freshQRcode() {
            if (this.isFresh) {
                this.timer = setInterval(() => {
                    this.createQRCode()
                    this.fullQRcode()
                }, 10 * 1000)
            } else {
                clearInterval(this.timer)
            }
        },
        showFull() {
            this.fullQRcode()
            this.showQrStatus = true
        },
        handleUrl() {
            let random = this.$jsFn.getBtwRandom(1000, 9999)
            let link = window.location.origin + '/phonesign'
            let id = this.trainInfo.id
            let school = this.$store.state.userInfo.schoolCode
            let topic = this.trainInfo.topic
            let address = this.trainInfo.address
            let presenter = this.trainInfo.presenter
            let time = `${this.dateFormat(this.trainInfo.startTime)} 至 ${this.dateFormat(this.trainInfo.endTime)}`
            let url = `${link}?isOpen=${this.isOpen}&id=${id}&school=${school}&topic=${topic}&address=${address}&presenter=${presenter}&time=${time}&random=${random}`
            //这里需要根据站点动态拼接域名
            let addr = this.$store.state.config.srvAdr
            let type = this.$store.state.config.srvAdrType
            let clientId, nonce, state
            state = this.$jsFn.getBtwRandom(1000, 9999)
            let idToken = localStorage.getItem('id_token')
            let tokenData = jwtDecode(idToken)
            nonce = tokenData ? tokenData.nonce : ''
            //国际站
            if (addr == 'Global') {
                clientId = this.$store.state.config.Global.clientID
            }
            // 大陆站
            else {
                clientId = this.$store.state.config.China.clientID
            }
            url = encodeURIComponent(url)
            let loginUrl = `https://account.teammodel.cn?response_type=code&client_id=${clientId}&state=${state}&nonce=${nonce}&redirect_uri=${url}`
            return loginUrl
        },
        fullQRcode() {
            this.$nextTick(() => {
                // 此时已经渲染完成
                let url = this.handleUrl()
                console.log(url)
                if (!this.fullQR) {
                    let qrcode = new QRCode('fullqrcode', {
                        width: 320, // 设置宽度，单位像素
                        height: 320, // 设置高度，单位像素
                        text: url // 设置二维码内容或跳转地址
                    })
                    this.fullQR = qrcode
                } else {
                    this.fullQR.clear()
                    this.fullQR.makeCode(url)
                }
                let dom = document.getElementById('fullqrcode')
                if (dom) dom.title = ''
            })
        },
        //创建二维码
        createQRCode() {
            this.$nextTick(() => {
                // 此时已经渲染完成
                let url = this.handleUrl()
                console.log(url)
                if (!this.signQRcode) {
                    let qrcode = new QRCode('sign-qr-code', {
                        width: 150, // 设置宽度，单位像素
                        height: 150, // 设置高度，单位像素
                        text: url // 设置二维码内容或跳转地址
                    })
                    this.signQRcode = qrcode
                } else {
                    this.signQRcode.clear()
                    this.signQRcode.makeCode(url)
                }
                let dom = document.getElementById('qrcode')
                if (dom) dom.title = ''
            })
        },
        dateFormat(timestamp) {
            if (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}`
            } else {
                return '—'
            }

        },
        toTrainMgt() {
            this.$router.push({
                name: 'TrainAreaMgt'
            })
        },
        getTableData() {
            let tInfo = this.trainList.find(item => {
                return item.school == this.curSchool
            })
            let teacherInfo = this.allTeacherList.find(item => {
                return item.school == this.curSchool
            })
            if (tInfo && teacherInfo) {
                this.tableData = this._.cloneDeep(teacherInfo.teachers)
                tInfo.teachers.forEach(item => {
                    let curTea = this.tableData.find(tea => { return tea.id == item.id })
                    if (curTea) {
                        item.name = curTea.name
                        Object.assign(curTea, item)
                    }
                })
                if (this.trainInfo.settings.includes('survey')) {
                    this.getSurveyInfo()
                }
                if (this.trainInfo.settings.includes('exam')) {
                    this.getExamInfo()
                }
                if (this.trainInfo.settings.includes('hw')) {
                    this.getWorkInfo()
                }
            }

        },
        getAllTrainInfo(id) {
            if (id) {
                let params = {
                    id: id,
                    areaId: this.areaId
                }
                this.$api.train.findAreaAllTrain(params).then(
                    res => {
                        if (res && res.studies && res.studies.length) {
                            this.trainList = res.studies.map(item => { return item.stu })
                            this.allTeacherList = res.studies.map(item => {
                                return {
                                    school: item.stu.school,
                                    teachers: item.teac
                                }
                            })
                            this.trainInfo = this.trainList[0]
                            if (this.trainInfo.settings.includes('sign')) {
                                this.columns.push({
                                    title: '签到时间',
                                    slot: 'signTime',
                                    align: 'center'
                                })
                                this.createQRCode()
                            }
                            if (this.trainInfo.settings.includes('hw')) {
                                this.columns.push({
                                    title: '作业提交时间',
                                    slot: 'hwTime',
                                    align: 'center'
                                })
                            }
                            if (this.trainInfo.settings.includes('survey')) {
                                this.columns.push({
                                    title: '完成问卷时间',
                                    slot: 'surveyTime',
                                    align: 'center'
                                })
                            }
                            if (this.trainInfo.settings.includes('exam')) {
                                this.columns.push({
                                    title: '完成评测时间',
                                    slot: 'examTime',
                                    align: 'center'
                                })
                            }
                            this.columns.push({
                                title: '状态',
                                slot: 'status',
                                align: 'center'
                            })
                            this.columns.push({
                                title: '操作',
                                slot: 'action',
                                align: 'center'
                            })

                            let schoolIds = this.trainList.map(item => {
                                return item.school
                            })

                            this.examAllData = res.exam
                            this.workAllData = res.work
                            this.surveyAllData = res.survey
                            this.hwAndSignData = res.info
                            this.getSchoolList(schoolIds)
                        }
                    },
                    err => {

                    }
                )
            }
        },
        getSchoolList(ids) {
            this.$api.ability.findAreaGroup({
                id: this.areaId
            }).then(
                res => {
                    console.log(res)
                    this.schoolList = res.gr.filter(item => {
                        return ids.includes(item.id)
                    })
                    if (this.schoolList.length) {
                        this.curSchool = this.schoolList[0].id
                        this.getTableData()
                    }
                },
                err => {
                    console.log(err)
                }
            )
        },
        //获取文件后缀和类型
        getExAndType(fileName) {
            let ex = fileName.substring(fileName.lastIndexOf('.') + 1)
            let type = 'other'
            ex = ex.toUpperCase()
            for (let key in this.$GLOBAL.CONTENT_TYPES) {
                if (this.$GLOBAL.CONTENT_TYPES[key].indexOf(ex) != -1) {
                    type = key
                    break
                }
            }
            return {
                ex, type
            }
        }
    },
    created() {
        let routerData = this.$route
        this.getAllTrainInfo(routerData.query.id)
    },
    beforeRouteLeave(to, from, next) {
        if (this.timer) {
            clearInterval(this.timer)
        } else {
            clearInterval()
        }
        next()
    }
}
</script>
<style lang="less" scoped>
@import "./TrainDetail.less";
</style>
<style scoped lang="less">
.detail-right .ivu-card:first-child {
    margin-top: 0px !important;
}
</style>