<template>
    <div class="container" @click="_closeAll">
        <template v-if="status == 200 && channelInfo.id">
            <skin :layoutColor="channelInfo.layoutColor"></skin>
            <mobile v-if="isMobile"></mobile> 
            <pc v-else></pc>
        </template>
        <template v-else-if="status == 401">
            <!-- 拉黑 -->
            <status401></status401>
        </template>
        <template v-else-if="status == 404">
            <!-- 资源不存在 -->
            <status404></status404>
        </template>
        <template v-else-if="status == 408">
            <!-- 等待 -->
            <status408></status408>
        </template>
        <template v-else>
            <div class="loading"></div>
        </template>
    </div>
</template>
<script>
    import {getclientip} from '@/plugins/API/apiAll'
    import { mapGetters, mapMutations, mapActions } from 'vuex'
    import UserAgent from '@/plugins/UserAgent/index'

    import skin from '@/assets/skin/index';
    const viewPc = resolve => require(['@/components/view/pc'],resolve)
    const viewMobile = resolve => require(['@/components/view/mobile'],resolve)
    const status401 = resolve => require(['@/components/view/401'],resolve)
    const status404 = resolve => require(['@/components/view/404'],resolve)
    const status408 = resolve => require(['@/components/view/408'],resolve)
    export default {
        head() {
            return {
                title: this.domTitle,
            }
        },
        components: {
            'skin': skin,
            'pc':viewPc,
            'mobile':viewMobile,
            'status401': status401,
            'status404': status404,
            'status408': status408
        },
        data(){
            return {
                id: this.$route.params.id,
                refererId: this.$route.query.refererId,
                dmsTimer: null,
                isMobile: true,
                IP: '',
            }
        },
        computed: {
            ...mapGetters({
                'status': 'status',
                'type': 'type',
                'corpId': 'corpId',
                'channelInfo': 'channelInfo',
                'userInfo': 'userInfo',
                'menuList': 'menuList',
            }),
            domTitle(){
                if(this.status == 200){
                    return this.channelInfo.channelName || '';
                }else if(this.status == 404){
                    return '抱歉，您的页面迷路了';
                }else if(this.status == 408){
                    return '直播间人数较多，请耐心等待';
                }else{
                    return this.channelInfo.channelName || '';
                }
            },
            reportDms(){
                let dms = '';
                for(let i = 0; i < this.menuList.length; i++){
                    let item = this.menuList[i];
                    if(item.menuType == 'report' && item.menuInfo){
                        dms = `pic_text_${item.menuInfo}`;
                    }
                }
                return dms;
            },
            otherTopic(){
                return {
                    audience: `dms_${this.channelInfo.uin}_audience`
                }
            },
            
        },
        async asyncData({store, query, params, userAgent}){
            let isMobile = /Android|webOS|iPhone|iPod|BlackBerry/i.test(userAgent) ? true : false;
            await store.dispatch('get_control', {id: params.id})
            return {
                isMobile: isMobile,
            }
        },
        async mounted(){
            if(this.status != 200){
                return false;
            }
            setTimeout(() => {
                this.isMobile = UserAgent.isMobile();
            },1000)

            this.set_corpId(this.$route.query.corpId);
            
            this._DMSInit();
            this.get_userInfo({refererId: this.refererId});
            this.getclientip();
        },
        methods: {
            ...mapMutations({
                'set_corpId': 'set_corpId',
                'set_channelInfo': 'set_channelInfo',
                'set_userInfo': 'set_userInfo',
            }),
            ...mapActions({
                'get_control': 'get_control',
                'get_userInfo': 'get_userInfo',
            }),
            _closeAll(){
                this.$Bus.$emit('bus-remEnclosure')
                this.$Bus.$emit('bus-showReward', false)
            },
            async getclientip(){
                const res = await getclientip()
                if(res.code === 0){
                    let ipArr = res.data.ip.replace(/\s+/g,"").split(',');
                    this.IP = ipArr[0]
                }
                this.enterDms();
            },
            enterDms(){
                clearTimeout(this.dmsTimer);
                this.dmsTimer = null;
                this.dmsTimer = setTimeout(() => {
                    this._makeClientId();   
                    this.dmsTimer = null;
                },500)
            },
            _makeClientId(){
                ROP.Leave();
                let uin = this.channelInfo.uin || '';
                let navigatorType = !UserAgent.isMobile() ? 1 : UserAgent.isWx() ? 3 : 4;
                let isSafe = this.userInfo.isSafe ? 1 : 2;
                let timeStr = String(new Date().getTime()+Math.floor(Math.random()*100000));
                let userTimeKey = this.userInfo.userTimeKey || timeStr;
                let IP = this.IP || '127.0.0.1';
      
                let clientId = `${uin}_${navigatorType}_${isSafe}_${userTimeKey}_${IP}`;
                console.log(clientId)
                ROP.Enter('', this.channelInfo.sub_key, clientId, true);
            },
            _DMSInit(){
                let _this = this;
                //chat连接成功后的消息
                ROP.On("enter_suc",function(){
                    console.log('服务器连接成功')
                    ROP.Subscribe(_this.channelInfo.dmsTopic);
                    ROP.Subscribe(_this.channelInfo.dmsDataTopic);
                    ROP.Subscribe(_this.channelInfo.dmsRewardTopic);
                    ROP.Subscribe(_this.channelInfo.dmsImageTextTopic);
                    ROP.Subscribe(_this.channelInfo.dmsRedpacketTopic);
                    ROP.Subscribe(_this.otherTopic.audience);


                    if(_this.channelInfo.dmsActivityManage){
                        ROP.Subscribe(_this.channelInfo.dmsActivityManage);
                    }
                    if(_this.channelInfo.dmsActivityDraw){
                        ROP.Subscribe(_this.channelInfo.dmsActivityDraw);
                    }
                    if(!UserAgent.isMobile()){
                        // ROP.Subscribe(_this.channelInfo.dmsLoginBackTopic);
                        ROP.Subscribe(_this.channelInfo.dmsPayWatchBackTopic);
                    }
                    if(_this.reportDms){
                        ROP.Subscribe(_this.reportDms);
                    }
                })
                ROP.On("reconnect",function(err){
                    console.log('重连',err);
                })
                //chat连接失败后的消息
                ROP.On("enter_fail",function(err){
                    console.log('服务器连接失败',err);
                })
                //chat接收到的消息
                ROP.On("publish_data",function(data, topic){
                    data = JSON.parse(data);
                    switch (topic)
                    {
                        case _this.channelInfo.dmsTopic:
                        case _this.channelInfo.dmsRewardTopic:
                        case _this.channelInfo.dmsRedpacketTopic:
                            if(data.msgType == 1){
                                _this.$Bus.$emit('bus-sendBarrage', data.filterContent)
                            }
                            if(data.msgType == 6){
                                if(data.redpacketId){
                                    _this.$Bus.$emit('bus-addShareList', {redpacketId: data.redpacketId})
                                }
                            }else if(data.msgType == 10){
                                if(data.redpacketId){
                                    _this.$Bus.$emit('bus-addAnswerList', {redpacketId: data.redpacketId})
                                }
                            }else if(data.msgType == 12){
                                if(data.redpacketId){
                                    _this.$Bus.$emit('bus-addBusinessList', { redpacketId: data.redpacketId,isRob: 2,})
                                }
                            }else{
                                if(data.isTop){
                                    _this.$Bus.$emit('bus-addTopChat', data)
                                }
                                _this.$Bus.$emit('bus-addChat', data)
                                _this.$Bus.$emit('bus-chatNum',1);
                            }
                            break;
                        case _this.channelInfo.dmsDataTopic:
                            if(data.cmd == 'praise') {   //点赞
                                _this.$Bus.$emit('bus-praiseNum', parseInt(data.num));
                            }else if (data.cmd == 'watchNum') {  //自定义观看量
                                _this.$Bus.$emit('bus-customWatchNum', parseInt(data.watchNum));
                            }else if(data.cmd == 'realWatchNum'){ //真实观看量
                                _this.$Bus.$emit('bus-realWatchNum', parseInt(data.realWatchNum));
                            }else if(data.cmd == 'chatDisable'){ //是否全员禁言
                                let info = JSON.parse(JSON.stringify(_this.channelInfo));
                                info.chatDisable = data.status;
                                _this.set_channelInfo(info)
                            }else if(data.cmd == 'chatLogin'){ //是否禁止游客聊天
                                let info = JSON.parse(JSON.stringify(_this.channelInfo));
                                info.chatLogin = data.status;
                                _this.set_channelInfo(info)
                            }else if(data.cmd == 'chatSee'){ //聊天是否自己可见
                                let info = JSON.parse(JSON.stringify(_this.channelInfo));
                                info.chatSee = data.status;
                                _this.set_channelInfo(info)
                            }else if(data.cmd == 'chatCountStatus'){ //是否显示聊天数
                                let info = JSON.parse(JSON.stringify(_this.channelInfo));
                                info.chatCountStatus = data.status;
                                _this.set_channelInfo(info)
                            }else if(data.cmd == 'living'){ //开启结束直播
                                let info = JSON.parse(JSON.stringify(_this.channelInfo));
                                info.liveStatus = data.status;
                                _this.set_channelInfo(info)
                            }else if(data.cmd == 'isTop'){ //是否置顶
                                if(data.status==0){
                                    _this.$Bus.$emit('bus-delTopChat', data.chatInfo.id)
                                }
                            }else if(data.id){  //删除聊天
                                _this.$Bus.$emit('bus-delTopChat', data.id)
                                _this.$Bus.$emit('bus-delChat', data.id)
                                _this.$Bus.$emit('bus-chatNum', -1)
                            } 
                            break;
                        // case _this.channelInfo.dmsLoginBackTopic:
                        //     _this.$Bus.$emit('bus-pcLogin', data)
                        //     break;
                        case _this.channelInfo.dmsPayWatchBackTopic:
                            if(_this.userInfo.id && data.userId == _this.userInfo.id && !UserAgent.isMobile()){
                                _this.$layer.msg('支付成功');
                                setTimeout(function(){
                                    window.location.reload();
                                },1000)
                            }
                            break;
                        case _this.channelInfo.dmsActivityManage:
                            if(data.cmd == 'vote_set_include'){
                                _this.$Bus.$emit('bus-voteList',data);
                            }
                            if(data.cmd == 'vote_edit'){
                                _this.$Bus.$emit('bus-voteEdit',data);
                            }
                            if(data.cmd == 'vote_service'){
                                _this.$Bus.$emit('bus-voteStatus',data);
                            }
                            if(data.cmd == 'draw_bind'){
                                if(data.status == 1){
                                    _this.$Bus.$emit('bus-drawInfo',data.drawInfo);
                                }else{
                                    _this.$Bus.$emit('bus-drawInfo',{});
                                }
                            }
                            if(data.cmd == 'vote_set_source'){
                                if(data.status == 1){
                                    _this.$Bus.$emit('bus-voteInfo',data.voteInfo);
                                }else{
                                    _this.$Bus.$emit('bus-voteInfo',{});
                                }
                            }
                            break;
                        case _this.channelInfo.dmsActivityDraw:
                            _this.$Bus.$emit('bus-drawStatus',data);
                            break;
                        case _this.reportDms:
                            _this.$Bus.$emit('bus-reportAdd',data);
                            break;
                        case _this.otherTopic.audience:
                            let ids = data.ids.map(x => parseInt(x))
                            if(!~ids.indexOf(parseInt(_this.userInfo.id))){
                                return false;
                            }
                            if(data.cmd == 'disableChat'){
                                let info = JSON.parse(JSON.stringify(_this.userInfo));
                                info.isDisableChat = parseInt(data.isDisable);
                                _this.set_userInfo(info)
                            }
                            if(data.cmd == 'setStatus'){
                                let info = JSON.parse(JSON.stringify(_this.userInfo));
                                info.status = parseInt(data.status);
                                _this.set_userInfo(info)
                            }
                            break;
                    }
                })
                //chat断开连接后的消息
                ROP.On("losed",function(){
                    console.log('服务器断开连接');
                })
            },
        },
        watch: {
            'userInfo.id'(){
                this.enterDms();
            },
            IP(){
                this.enterDms();
            },
            reportDms(){
                this.enterDms();
            }
        },
    }
</script>

<style lang="less" scoped>
.container {
    background-color: #fff;
    .loading{
        position: fixed;
        top: 0;
        left: 0;
        z-index: 99999;
        width: 100%;
        height: 100vh;
        background-color: #fbfbfb;
        background-image: url("~@/assets/img/loading.gif");
        background-repeat: no-repeat;
        background-size: 270px auto;
        background-position: center center;
    }
}
</style>
