<template>
    <div class="index_box">
        <div class="banner"><img src="../assets/mobile/index_icon.jpg"></div>
        <div class="connect">
            <!--<Button type="success" long style="background:#2d8cf0;border:1px solid #2d8cf0;line-height: 2.1;font-size: 13px" @click="callCamera()">扫码加入教室</Button>-->
            <Input v-model="ClassNumber" placeholder="输入教室编号" style="width: 100%;margin-top:10%;font-size:0.35rem" />
            <div class="submit_btn"><Button type="primary" @click="JoinClass()">连接教室</Button></div>
        </div>
        <q-dialog v-model="alert">
            <q-card>
                <q-card-section>
                    <div><q-input v-model="name" label="姓名或昵称" /></div>
                </q-card-section>
                <q-card-actions align="right">
                    <q-btn flat label="跳过" color="primary" @click="skip" />
                    <q-btn flat label="OK" color="primary" @click="close" />
                </q-card-actions>
            </q-card>
        </q-dialog>
        <!--<van-popup v-model="show">
            <div class="reconnection-box">
                <div class="reconnection-title">当前有加入的教室哦，接下来的操作？</div>
                <div class="reconnection-handle">
                    <div class="comeback"><van-button color="linear-gradient(to right, #4bb0ff, #6149f6)" round="true" @click="comebackirs">回到互动页面</van-button></div>
                    <div class="quitclass"><van-button color="linear-gradient(to right,#FF8888,#FF0000)" round="true">不，我要退出重新加入</van-button></div>
                </div>
            </div>
        </van-popup>-->
    </div>
</template>
<script>
    import Vue from 'vue'
    import cookie  from 'vue-cookies'
    Vue.prototype.$cookie = cookie;
    export default {
        data() {
            return {
                ClassNumber: '',
                mobiledeviceId:'',
                mobiletoken: '',
                accepterId: '',
                MqttInformation: '',
                Sendmsg: '',
                client: '',
                alert: false,
                address: '',
                name: '',
                isPwd: true,
                seatnum: '',
                nowtime: '',
                show:false,
            }
        },
        created() {
            //this.reconnection();
            this.StudentuserInit()
            this.QRcodeJoinclass()
            this.registerId();
            this.uiinit1();
        },
         mounted() {
             this.information()
              window.onbeforeunload = function (e) {
                var storage = window.localStorage;
                  //storage.removeItem('mobiledeviceId') 
                  //storage.removeItem('mobiletoken')
                  //storage.removeItem('mobileclassnum')
                  //storage.removeItem('seatnum')
            }
        },
        methods: {
            /*进入页面检测 误操作或重连*/
            //reconnection() {
            //    let username = localStorage.getItem('username')
            //    let vaildtime = localStorage.getItem('timeefficiency')
            //    let time = Math.round(new Date().getTime())
            //    let seatnum = localStorage.getItem('seatnum')
            //    let mobileclassnum = localStorage.getItem('mobileclassnum')
            //    let mobiledeviceId = localStorage.getItem('mobiledeviceId')
            //    let mobiletoken = localStorage.getItem('mobiletoken')
            //    if (username && seatnum && mobileclassnum && mobiledeviceId && mobiletoken) {
            //        this.show = true;
            //    }
            //},
            /*学生用户装置ID有效期判断*/
            StudentuserInit() {
                //当前时间戳
                let correcttime = Math.round(new Date().getTime())
                let cachetime = localStorage.getItem('timeefficiency')
                let devicesId = localStorage.getItem('mobiledeviceId')
                let CookieDeviceId = this.$cookie.get('mobiledeviceId');
                let CookieToken = this.$cookie.get('token');
                let CookieUsername = this.$cookie.get('username');
                let CookieSeatnum = this.$cookie.get('seatnum');
                let CookieClassnum = this.$cookie.get('classnum');
                let CookieTime= this.$cookie.get('timeefficiency');
                console.log(correcttime, '当前时间戳')
                if (cachetime === '' || cachetime === null || devicesId === '' || devicesId === null) {
                    this.registerId()
                } else if (correcttime > cachetime) {
                    console.log('时间过期！执行方法')
                    let MobileDeviceId = this.common.guid()
                    localStorage.setItem('mobiledeviceId',MobileDeviceId)
                    this.registerId()
                }
                if (CookieDeviceId && CookieToken && CookieUsername && CookieSeatnum && CookieClassnum && CookieTime) {
                    localStorage.setItem('mobiledeviceId', CookieDeviceId)
                    localStorage.setItem('mobiletoken', CookieToken)
                    localStorage.setItem('username', CookieUsername)
                    localStorage.setItem('seatnum', CookieSeatnum)
                    localStorage.setItem('mobileclassnum', CookieClassnum)
                    localStorage.setItem('timeefficiency', CookieTime)
                }
            },
            /*扫码加入教室*/
            QRcodeJoinclass() {
                var url = window.location.href
                console.log(url)
                let decide = url.indexOf('classnum')
                console.log(decide)
                if (decide === -1) {
                    this.$router.push({ path: '/mobileindex' })
                    console.log('没有，正常进入首页')
                } else {
                    let classnums = url.substr(decide + 9, 6);
                    this.ClassNumber=classnums
                    console.log(classnums, '教师号')
                    let MobileDeviceIds = localStorage.getItem('mobiledeviceId')
                    let MobileToken = localStorage.getItem('mobiletoken')
                    if (MobileDeviceIds && MobileToken) {
                        this.JoinClass()
                    } else {
                        console.log('缺少数据')
                    }
                }
                
            },
            /*防止掉线 获取以前的用户名*/
            information() {
                if (localStorage.getItem('username')) {
                    this.name = localStorage.getItem('username');
                }
            },
            /*获取装置ID*/
            registerId() {
                let MobileDeviceId = localStorage.getItem('mobiledeviceId') ? localStorage.getItem('mobiledeviceId') : '' + this.common.guid()
                console.log(MobileDeviceId,'进入方法后的装置ID')
                 this.$api.getLoginInfo(
                    {
                        'jsonrpc': '2.0',
                        'method': 'Regist',
                        'params': {
                            'deviceId': MobileDeviceId,
                            'clientId': 'c89edcfd-3830-4238-b8a8-0bd4b43c20ca',
                            'verificationCode': 'cc13f9c6-54a1-4ce9-a3d9-8952c335983e',
                            'verificationCodeVer': '46662dcbd6a6421f9d45d1857ebdec95',
                            'productCode': 'LZLL6ZEI',
                            'extraInfo': {}
                        },
                        'id': 1
                    }
                 ).then(res => {
                     console.log(res.result,'fanhui')
                     localStorage.setItem('mobiledeviceId', MobileDeviceId)
                     this.mobiledeviceId = MobileDeviceId
                     this.mobiletoken = res.result.token
                     if (this.mobiletoken) {
                         localStorage.setItem('mobiletoken', this.mobiletoken)
                         //localStorage.setItem('serviceUrl', JSON.stringify(res.result.serviceUrl))
                         /*执行扫码加入教室*/
                         var url = window.location.href
                         let decide = url.indexOf('classnum')
                         if (decide === -1) {

                         } else {
                             this.QRcodeJoinclass()
                         }
                     }
                     let time = localStorage.getItem('timeefficiency')
                     if (time === '' || time === null) {
                         console.log('缓存时间为空 执行生成时间戳')
                         let nowtimes = Math.round((new Date().getTime()) + (3600000 * 3))
                         //let nowtimes = Math.round(new Date().getTime())
                         localStorage.setItem('timeefficiency',nowtimes)
                     }
                     console.log(this.mobiletoken,'移动端token值')
                 }).catch(res => {
                      console.log(res,'失败原因')
                 })
            },
            /*移动端获取教室编号加入教室获取MQTT信息以及sendmsg*/
            JoinClass() {
                let getclass = this.ClassNumber;
                 if (getclass !== '') {
                     localStorage.setItem('mobileclassnum', getclass)
                }
                let JoinMobiledeviceId = localStorage.getItem('mobiledeviceId');
                console.log(JoinMobiledeviceId,'数据信息')
                if (JoinMobiledeviceId !== '') {
                    this.$api.getLoginInfo(
                        {
                            'jsonrpc': '2.0',
                            'method': 'JoinGroup',
                            'params': {
                                'deviceId': JoinMobiledeviceId,
                                'groupNum': getclass
                            },
                            'id': 1
                        }
                    ).then(res => {
                        console.log('加入教室成功')
                        console.log(res,33333)
                        this.alert = true;
                        /*接收人设备ID*/
                        console.log(res,'返回数据')
                        this.accepterId = res.result.groupManager
                        /*MQTT相应资讯*/
                        this.MqttInformation = res.result.mqtt
                        /*Sendmsg内容*/
                        this.Sendmsg = res.result.mqtt.publishTopic.sendMsg
                       
                    })
                }
            },
            /*MQTT连接教室*/
            ConnectMqtt() {
                console.log('开始执行mqtt')
                let that = this;
                let mobileuserdeviceId = that.mobiledeviceId;
                console.log(mobileuserdeviceId, '装置ID')
                let recipient = that.accepterId  
                let recipients = {
                     "directMethod": that.accepterId
                }
                console.log(recipient,'其他ID')
                let mobilemqtt = that.MqttInformation
                let sendmsginfo = that.Sendmsg
                let seatnumber = that.seatnum
                let willtopmsg = that.Sendmsg
                /*拼接内容和接收者*/
                let willtopic = willtopmsg + "&$.to=" + JSON.stringify(recipients)
                console.log(willtopic,'遗嘱拼接')
                /*遗嘱内容*/
                let willcontent = {
                    "Answer": '已意外离线:' + mobileuserdeviceId,
                    "GroupAPI-Version": 0.0,
                    "GroupMemberNum": 0,
                    "Host-Software-Version": 0,
                    "MemberID": 0,
                    "Pincode": 0,
                    "TypeId": 5,
                    "id": mobileuserdeviceId,
                }
                let willpayload = JSON.stringify(willcontent);
                console.log(willpayload,'遗嘱内容')
                let client = that.$mqttconnects(mobilemqtt.connectInfo.clientID, mobilemqtt.connectInfo.username, mobilemqtt.connectInfo.password,willtopic,willpayload)
                Vue.prototype.$connect = client
                /*连接以及订阅*/
                client.on('connect', function () {
                    console.log('连接成功')
                    client.subscribe('$iothub/methods/POST/directMethod/#', function (err) {
                        if (!err) {
                            //console.log('主题订阅成功');
                            that.MobileMsg({ "id": mobileuserdeviceId }, 0, recipient,'JoinClass');
                            //this.$Message.success('通讯信息连接成功！')
                        } else {
                            console.log('主题订阅失败')
                            //this.$Message.success('通讯信息连接失败，请重试！')
                        }
                    });
                    /*接收消息*/
                    client.on('message', function (topic, message) {
                        // message is Buffer
                        console.log('收到消息 主题：' + topic + '  消息：' + message.toString() + '内容是：' + message)
                        if (topic.indexOf('$iothub/methods/POST/directMethod/') != -1) {
                            // TODO
                            let seatnums = JSON.parse(message.toString());
                            that.seatnum =seatnums.Payload.seatnum
                            localStorage.setItem('seatnum', seatnums.Payload.seatnum)
                              that.$router.push({ path: '/mobileirs', query: { seatnum:seatnumber,accepterid:recipient,sendmsginfos:sendmsginfo,deviceid:mobileuserdeviceId,mobilemqtts:mobilemqtt}});
                            //console.log(JSON.parse(message.toString()), '内容1111')
                           
                            console.log('主题符合')
                        } else {
                            return
                        }
                        // 收到特定主题要回复一个空消息
                        let pubTopic = '$iothub/methods/res/200/?$rid=' + topic.split('=')[1]
                        client.publish(pubTopic, '', {}, (error) => {
                            if (!error) {
                                console.log('回复成功')
                            }
                        })
                    })
                    /*连接失败*/
                    client.on('error', (error) => {
                        console.log('连接失败:', error)
                    })
                    })
            },
            /*发送消息*/
            MobileMsg(msgs,typeid,accepter,operationname) {
                let msg = msgs
                let directMethod = accepter
                let name=this.name
                //let MobileMqttinfo = this.MqttInformation;
                //let userdeviceId = MobileMqttinfo.connectInfo.clientID;
                let sendMsg =this.Sendmsg
                const timestamp = Math.floor(Date.now() / 1000)
                var msgconfig = {
                    'Action': operationname,
                    'Sender': name,
                    'TypeId':typeid,
                    'Timestamp': timestamp,
                    'Payload': { 'StudentId': msg }
                }
                let payload = JSON.stringify(msgconfig)
                let receiveId = {
                    'directMethod': directMethod
                }
                let pubTopic = sendMsg + '&$.to=' + JSON.stringify(receiveId)
                console.log('发送内容：' + payload)
                console.log('发送主题：' + pubTopic)
                let client = this.$connect
                client.publish(pubTopic, payload, { qos: 0 }, (error) => {
                    if (!error) {
                        console.log('发布成功')
                    } else {
                        console.log('发布失败')
                    }
                })
            },
            /*用户初始化*/
            close() {
               console.log(this.name,'用户名')
                this.alert = false;
                //if (this.name === '') {
                //    let codenum = this.randomnum(3);
                //    this.name = 'user' + codenum;
                //    localStorage.setItem('username', this.name)
                //} else {
                //    localStorage.setItem('username', this.name)
                //}
                let usernames = localStorage.setItem('username', this.name)
                if (usernames === '' && this.name === '') {
                    let codenum = this.randomnum(3);
                    this.name = 'user' + codenum;
                    localStorage.setItem('username', this.name)
                }
                this.ConnectMqtt();
            },
           /*跳过*/
            skip() {
                this.alert = false;
                let codenum = this.randomnum(3);
                this.name = 'user' + codenum;
                localStorage.setItem('username', this.name)
                this.ConnectMqtt();
            },
           /*随机数方法*/
            randomnum(num) {
                var codeLength = num;//验证码的长度   
                var random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);//随机数 
                let code = '';
                for (var i = 0; i < codeLength; i++) {
                    //循环操作   
                    var index = Math.floor(Math.random() * 10);//取得随机数的索引（0~35）   
                    code += random[index];//根据索引取得随机数加到code上  
                }
                return code;
            },
            uiinit1() {
                function setRem() {
                    var whdef = 100 / 750;// 表示1920的设计图,使用100PX的默认值
                    var bodyWidth = document.body.clientWidth;// 当前窗口的宽度
                    var rem = bodyWidth * whdef;// 以默认比例值乘以当前窗口宽度,得到该宽度下的相应FONT-SIZE值
                    document.getElementsByTagName('html')[0].style.fontSize = rem + 'px';
                }
                window.addEventListener('load', setRem);
                window.addEventListener('resize', setRem);
            },
        /*回到IRS页面*/
            //comebackirs() {
            //    console.log('触发方法')
            //    this.$router.go(-1);
            //}
        },
    }
</script>
<style>
    .ivu-btn {
        padding: 7px 5px !important;
    }

    .ivu-input {
        height: 40px !important;
        font-size: 13px;
    }
</style>
<style scoped>
    .index_box {
        max-width: 750px;
        margin: 0 auto;
        background: #fff;
        padding: 0.2rem;
        min-height: 100vh;
    }

    .banner {
        width: 80%;
        height: auto;
        margin: 0 auto;
    }

        .banner img {
            width: 100%;
            margin: 0 auto;
        }

    .connect {
        width: 100%;
        padding: 0% 2%;
        margin-top: 5%;
    }
        .connect button {
         font-size: 0.4rem;
        }

    .submit_btn {
        width: 50%;
        margin: 0 auto;
    }
        .submit_btn button {
            width: 100% !important;
            margin-top: 15%;
            font-size: 0.35rem;
        }
   
</style>
