<template>
    <!--10.4.1.	直播间组件1开始-->
    <oldVideo v-if="lylLiveStatus==='3'"></oldVideo>
    <div v-else class="live_show_room_mobile_1">
        <!--以下视频部分-->

        <div class="liveshow-video">
            <div class="appbar appbar-transparency liveshow-appicon"><!--头部标题栏-->
                <span class="goback"><a href="javascript:history.go(-1)">返回</a></span>
                <!--<span class="appbar-moreicon">-->
                    <!--<a href=""><img src="../../theme-chalk/src/images/details_icon02.png" alt=""></a>-->
                    <!--<a href=""><img src="../../theme-chalk/src/images/details_icon03.png" alt=""></a>-->
                    <!--<a href=""><img src="../../theme-chalk/src/images/details_icon04.png" alt=""></a>-->
                 <!--</span>-->
            </div>
            <!--直播源-->
            <div id="my_player" style="height: 100%"></div>
            <!--<video id="my-player" poster="../../theme-chalk/src/images/pic04.png" class="video-js vjs-big-play-centered video-diystyle" style="object-fit: fill;"  x5-playsinline="" playsinline="" webkit-playsinline="" controls>-->
            <!--<source src="http://cloud-play.hhalloy.com/live/cf4d66edc142b2f0cc8c71bca56b2268.m3u8" type="application/x-mpegURL">-->
            <!--<p class="vjs-no-js">-->
            <!--not support-->
            <!--</p>-->
            <!--</video>-->
            <!-- <span class="video-xiake-btn">
               <a href="">下课</a>
               <a href="">暂停</a>
            </span> -->
            <!--<span class="video-kecheng-tip">-->
            <!--<a href="">必修课</a>-->
            <!--<a href="">专业课</a>-->
            <!--</span>-->
            <span class="video-kecheng-shangke" v-if="livedetail.lylRealStatus == '0'">
        <span class="sp0">直播未开始</span>
        <!--<span class="sp1"><a href="">开启提醒</a></span>-->
                <!-- <span class="sp2">倒计时：00：30</span> -->
                <!-- <span class="sp3"><a href="">上课</a></span> -->
     </span>
        </div>
        <!--详情简介-->
        <div class="details-list video-details">
            <span class="sp1">{{livedetail.lylName}}</span>
            <span class="sp7">
         <span>
            <i class="i1">{{livedetail.lylStartDate | formatDate}}-{{livedetail.lylEndDate | formatDate}}</i>
            <i class="i2">参加人数：<a>{{livedetail.lylSignupNum}}</a></i>
         </span>
         <i class="i3">{{talkUser.userCount}}人在线</i>
      </span>
        </div>
        <!--课程详情btn-->
        <!--<span class="course-detail-btn"><a href="">课程详情</a></span>-->
        <!--考试规格、考试介绍-->
        <div class="myexam-mainbody">
            <!--以下tab页标题-->
            <div class="myexam-tabtitle">
                <ul>
                    <li :class="livetab==0?'active':''" @click="livetab=0"><a href="javascript:;">聊天</a></li>
                    <li :class="livetab==1?'active':''" @click="livetab=1"><a href="javascript:;">问答</a></li>
                    <li :class="livetab==2?'active':''" @click="livetab=2"><a href="javascript:;">成员</a></li>
                </ul>
            </div>
            <div v-if="livetab==0" class="video-messages-main"><!--聊天-->
                <div class="video-messages">
                    <ul>
                        <li v-for="(item,index) of talk.callBack" :key="index">
                  <span class="video-messages-name">
                     <div class="video-messages-name-jihe">
                        <img src="../../theme-chalk/src/images/header.png" alt="">
                        <span class="sp1">{{item.fromUserName}}</span>
                        <span class="sp2">{{item.createTime}}</span>
                     </div>
                  </span>
                            <span class="video-messages-body">
                     <span class="video-messages-qipao"></span><!--聊天气泡小脚-->
                     <a href="">{{item.msg}}</a>
                  </span>
                        </li>
                    </ul>
                </div>
                <span class="video-messages-kuang">
            <input type="text" class="video-messages-input" v-model="talk.value">
                    <!--<span class="video-messages-checkbox"><input type="checkbox" id="tiwen"><label for="tiwen">提问</label></span>-->
            <span class="video-messages-sub">
               <!--<a href=""><img src="../../theme-chalk/src/images/biaoqing.png" alt=""></a>-->
               <input type="button" class="video-messages-subbtn" @click="subMit" value="发表">
            </span>
         </span>
            </div>
            <div v-if="livetab==1" class="video-wenda-main"><!--问答-->
                <div class="video-messages">
                    <ul>
                        <li class="video-messages-line"  v-for="(item, index) in questionslist.data" :key="index">
                              <span class="video-messages-name">
                                 <div class="video-messages-name-jihe">
                                    <img src="../../theme-chalk/src/images/header.png" alt="">
                                    <span class="sp1">{{item.aswAskCustName}}</span>
                                    <span class="sp2">学员</span>
                                    <span class="sp2">提问于<i>{{item.aswAskDate}}</i></span>
                                 </div>
                                 <span class="sp3" @click="aswclick(item.aswAskCustName,item.aswId)"><img src="../../theme-chalk/src/images/huida.png" alt=""></span>
                              </span>
                            <span class="video-chengyuan-body">	• 	{{item.aswContent}}</span>
                            <!--<span class="video-messages-shouqi"><a href="">收起回答</a></span>-->
                            <ul>
                                <li v-if="item.anserList" v-for="(acsitem, acsindex) in item.anserList" :key="acsindex">
                                    <span class="video-messages-name">
                                       <div class="video-messages-name-jihe">
                                          <img src="../../theme-chalk/src/images/header.png" alt="">
                                          <span class="sp1">{{acsitem.aswdCustName}}</span>
                                          <span class="sp2">学员</span>
                                          <span class="sp2">回答于<i>{{acsitem.aswdDatetime}}</i></span>
                                       </div>
                                    </span>
                                    <span class="video-chengyuan-body">{{acsitem.aswdContent}}</span>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </div>
                <span class="video-messages-kuang" v-if="asworque==0">
                    <input type="text" v-model="question" class="video-messages-input">
                    <!--<span class="video-messages-checkbox"><input type="checkbox"><label for="tiwen">提问</label></span>-->
                    <span class="video-messages-sub">
                       <!--<a href=""><img src="../../theme-chalk/src/images/biaoqing.png" alt=""></a>-->
                       <input type="button" class="video-messages-subbtn" @click="subque()" placeholder="请输入您的问题" value="提问">
                    </span>
                 </span>
                <span class="video-messages-kuang" v-if="asworque==1">
                    <input type="text" v-model="questionasw" class="video-messages-input">
                    <!--<span class="video-messages-checkbox"><input type="checkbox"><label for="tiwen">提问</label></span>-->
                    <span class="video-messages-sub">
                       <!--<a href=""><img src="../../theme-chalk/src/images/biaoqing.png" alt=""></a>-->
                       <input type="button" class="video-messages-subbtn" @click="subasw()" placeholder="请输入您的回答" value="回答">
                    </span>
                 </span>
            </div>
            <div v-if="livetab==2" class="video-chengyuan-main"><!--成员-->
                <div class="video-chengyuan">
                    <ul>
                        <!--<li>-->
                  <!--<span class="video-chengyuan-header">-->
                     <!--<span class="video-chengyuan-header-jiechujinyan">-->
                        <!--<a href="">解除禁言</a>-->
                     <!--</span>&lt;!&ndash;解除禁言&ndash;&gt;-->
                     <!--<img src="../../theme-chalk/src/images/header.png" alt="">-->
                     <!--<span class="video-chengyuan-header-jinyanicon"></span>&lt;!&ndash;禁言小图标&ndash;&gt;-->
                  <!--</span>-->
                            <!--<span class="video-chengyuan-name">-->
                     <!--<span class="sp1"><i class="i1">何超</i><i class="i2">学员</i><i class="i2">【禁言中】</i></span>-->
                     <!--<span class="sp2"><i class="i1">进入直播间：</i>2020-05-27 16:20:21</span>-->
                  <!--</span>-->
                        <!--</li>-->

                        <li v-for="(item,index) in talkUser.getUser" :key="index">
                            <span class="video-chengyuan-header"><img src="../../theme-chalk/src/images/header.png"
                                                                      alt=""></span>
                            <span class="video-chengyuan-name">
                                <span class="sp1"><i class="i1">{{item}}</i></span>
                     <span class="sp2"><i class="i1">进入直播间</i>
                         <!--2020-05-27 16:20:21-->
                     </span>
                  </span>
                        </li>
                        <!--<li>-->
                            <!--<span class="video-chengyuan-header"><img src="../../theme-chalk/src/images/header.png"-->
                                                                      <!--alt=""></span>-->
                            <!--<span class="video-chengyuan-name">-->
                     <!--<span class="sp1"><i class="i1">何超</i><i class="i2">学员</i></span>-->
                     <!--<span class="sp2"><i class="i1">进入直播间：</i>2020-05-27 16:20:21</span>-->
                  <!--</span>-->
                        <!--</li>-->
                    </ul>
                </div>
            </div>
        </div>
    </div>
    <!--10.4.1.	直播间组件1结束-->
</template>

<script>
    // import {httpPost} from '../../../src/utils/utils';
    import formMixin from '../../../src/mixins/formMixin';
    import lenye_base from 'lenye_base';
    // import Player from "xgplayer";
    // import FlvJsPlayer from "xgplayer-flv.js";
    import HlsJsPlayer from 'xgplayer-hls.js';
    import {Toast} from "vant";
    import oldVideo from '../../live_show_oldplay_mobile_1'
    // import $ from "fy-kit";

    export default {
        name: 'ElLiveShowRoomMobile1',
        mixins: [formMixin],
        model: {},
        components:{
            oldVideo
        },
        data() {
            return {
                livetab: 0,
                livedetail: '',
                liveadreess: '',
                isplay: false,
                lylId: '',
                //直播对象
                liveObj: {
                    //直播组件对象
                    livePlayer: {},
                    //    直播地址
                    liveAdress: '',
                    //    直播状态
                    liveStatus: '',
                    //    获取直播状态的函数
                    getLiveStatus: '',
                },
                // websoct对象
                websocket: "",
                // 聊天室的token
                chatToken: "",
                // 聊天室登录名称
                loginName: '',
                // 房间号
                roomId: "",
                // 聊天
                talk: {
                    value: "",
                    callBack: [],
                },
                //聊天室成员对象
                talkUser: {
                    //获取在线人数
                    userCount: 0,
                    //获取直播间用户
                    getUser: 0
                },
                questionslist: [],
                question: '',
                questionasw: '',
                questionaswid: '',
                asworque: 0,
                liveImage: '',
                lylLiveStatus:'3'
            };
        },
        // 过滤
        filters: {
            formatDate: function (value) {
                // var datavalue = value.replace(/\-/g, "/");
                let date = new Date(value);
                // let y = date.getFullYear();
                let MM = date.getMonth() + 1;
                MM = MM < 10 ? ('0' + MM) : MM;
                let d = date.getDate();
                d = d < 10 ? ('0' + d) : d;
                let h = date.getHours();
                h = h < 10 ? ('0' + h) : h;
                let m = date.getMinutes();
                m = m < 10 ? ('0' + m) : m;
                // let s = date.getSeconds();
                // s = s < 10 ? ('0' + s) : s;
                return MM + '月' + d + '日' + h + ':' + m;
            }
        },
        mounted() {
            this.lylLiveStatus = lenye_base.getUrlParam('lylLiveStatus');
            console.log('站点数据', this.siteData);
            this.loginName = lenye_base.user_data.getuserData().custName;
            this.lylId = lenye_base.getUrlParam('id'); //8fbb8997aa65430f801a4c0aac463ada
            if (this.lylLiveStatus==='3'){

            } else {
                this.getlivedetail();
                this.getliveadreess();
            }

        },
        created() {
            this.loginName = lenye_base.user_data.getuserData().custName;

            this.chatLogin();
        },
        watch: {
            'livetab'(newvalue) {
                if (newvalue === 1) {
                    this.questions();
                } else if (newvalue === 2) {
                    this.getRoomInfo();
                }
                ;
            },
            'questionasw'(newvalue) {
                if (!newvalue) {
                    this.asworque = 0;
                }
            }
        },
        methods: {
            getlivedetail() {
                const that = this;
                lenye_base.httpPost(lenye_base.base_data.getapiUrl() + lenye_base.api_url.live.lylLivequeryById, lenye_base.base_data.getformatting({
                    lylId: this.lylId
                }), function (e) {
                    console.log('直播详情', e);
                    that.livedetail = e.data;
                    that.liveImage = e.data.lylPhoto;
                });
            },
            getliveadreess() {
                const that = this;
                lenye_base.httpPost(lenye_base.base_data.getapiUrl() + lenye_base.api_url.live.lylLivequeryStreamAddress, lenye_base.base_data.getformatting({
                    lylId: this.lylId
                }), function (e) {
                    console.log('直播地址', e);
                    that.liveadreess = e.data;
                    that.liveObj.livePlayer = that.playerInit(e.data.length && e.data[2].address);
                    that.liveObj.livePlayer.on('play', function () {
                        this.isplay = true;
                    }).on('pause', function () {
                        this.isplay = false;
                    });
                });
            },
            // 直播视频
            playerInit(url) {
                return new HlsJsPlayer({
                    id: "my_player",
                    autoplay: false,
                    hasVideo: true,
                    hasAudio: true,
                    cors: true,
                    fluid: true,
                    isLive: true,
                    playsinline: true,
                    flvOptionalConfig: {
                        enableWorker: true,
                    },
                    url: url,
                    poster: this.liveImage,
                    lang: "zh-cn",
                    videoInit: false,
                    "x5-video-player-fullscreen": "false",
                    "x5-video-orientation": "landscape",
                    "x5-video-player-type": "h5",
                });
            },
            //直播状态轮询
            getliveStatus() {
                this.liveObj.getLiveStatus = setInterval(() => {
                    const that = this;
                    this.getRoomUserCount();
                    lenye_base.httpPost(lenye_base.base_data.getapiUrl() + lenye_base.api_url.live.lylLivequeryById, lenye_base.base_data.getformatting({
                        lylId: this.lylId
                    }), function (e) {
                        console.log('直播详情', e);
                        that.liveObj.liveStatus = e.data.lylRealStatus;
                    });
                    if (that.liveObj.liveStatus === '2' || that.liveObj.liveStatus === '3') {
                        if (that.isplay) {
                            that.liveObj.livePlayer.pause();
                        }
                    } else if (that.liveObj.liveStatus === '1') {
                        if (that.isplay || that.autoplay) {
                            that.liveObj.livePlayer.play();
                        }
                    }
                }, 5000)
            },
            // 聊天室登录
            chatLogin() {
                const that = this;
                lenye_base.httpPost(lenye_base.base_data.getapiUrl() + lenye_base.api_url.chat.login, JSON.stringify({
                    userName: that.loginName,
                    passWord: '123456'
                }), function (e) {
                    if (e.code === 1) {
                        lenye_base.httpPost(lenye_base.base_data.getapiUrl() + lenye_base.api_url.chat.register, JSON.stringify({
                            userName: that.loginName,
                            passWord: '123456'
                        }), function (e) {
                            if (e.code === 0) {
                                that.chatToken = e.data;
                                that.getRoomId();
                                that.getRoomUserCount();
                            }
                        });
                    } else if (e.code === 0) {
                        that.chatToken = e.data;
                        that.getRoomId();
                        that.getRoomUserCount();
                    }
                });
            },
            //tab切换时触发
            tabChoose(name, title) {
                if (title === '成员') {
                    this.getRoomInfo();
                }
            },
            // 房间号
            getRoomId() {
                var lylId = this.lylId;
                this.roomId = parseInt(lylId.replace(/[^\d]/g, "").slice(0, 5), 10);
                if (this.roomId && this.chatToken) {
                    this.getRoomInfo();
                    this.websocketObj();
                }
            },
            // 发表聊天消息
            subMit() {
                this.pushRoomdata(this.talk.value);
            },
            // 发送聊天
            async pushRoomdata(val) {
                if (this.chatToken) {
                    lenye_base.httpPost(lenye_base.base_data.getapiUrl() + lenye_base.api_url.chat.pushRoom, JSON.stringify({
                        roomId: this.roomId,
                        msg: val,
                        authToken: this.chatToken,
                        op: 3,
                    }), function (e) {
                        return e;
                    });
                }
            },
            //获取成员
            getRoomInfo() {
                if (this.chatToken) {
                    lenye_base.httpPost(lenye_base.base_data.getapiUrl() + lenye_base.api_url.chat.getRoomInfo, JSON.stringify({
                        roomId: this.roomId,
                        authToken: this.chatToken,
                    }), function (e) {
                        // return e;
                    });
                }
            },
            //获取在线用户数量
            getRoomUserCount() {
                setTimeout(function () {
                    if (this.chatToken) {
                        lenye_base.httpPost(lenye_base.base_data.getapiUrl() + lenye_base.api_url.chat.count, JSON.stringify({
                            roomId: this.roomId,
                            authToken: this.chatToken,
                        }), function (e) {
                            // return e;
                        });
                    }
                }, 1000)
            },
            // 实例化websocket对象
            websocketObj() {
                var urlstr = lenye_base.base_data.getapiUrl();
                var url = "wss://"+urlstr.substring(7, urlstr.length)+"/ws";
                this.websocket = new WebSocket(url);
                this.websocket.onopen = this.websocketonopen;
                this.websocket.onmessage = this.websocketonmessage;
            },
            websocketonopen(e) {
                //连接建立之后执行send方法发送数据
                this.websocket.send(
                    JSON.stringify({roomId: this.roomId, authToken: this.chatToken})
                );
            },
            // 监听事件
            websocketonmessage(e) {
                var received_msg = JSON.parse(e.data);
                if (received_msg.op === 3) {
                    received_msg.loginName = this.loginName;
                    this.talk.callBack.push(received_msg);
                    this.messagesContainerTimer = setTimeout(() => {
                        this.$refs.maxScroll.scrollTop = this.$refs.maxScroll.scrollHeight;
                        // 清理定时器
                        clearTimeout(this.messagesContainerTimer);
                    }, 0);
                    this.talk.value = "";
                } else if (received_msg.op === 4) {
                    this.talkUser.userCount = received_msg.count;
                } else if (received_msg.op === 5) {
                    console.log('用户人数', received_msg);
                    this.talkUser.userCount = received_msg.count;
                    this.talkUser.getUser = received_msg.roomUserInfo;
                }
            },
            // 退出事件
            close() {
                lenye_base.httpPost(lenye_base.base_data.getapiUrl() + lenye_base.api_url.chat.logout, lenye_base.base_data.getformatting({
                    authToken: this.chatToken,
                }), function (e) {
                    console.log(e)
                    return false;
                });
            },
            // 问答列表
            questions() {
                const that = this;
                let aswIds = '';
                let listobj = [];
                lenye_base.httpPost(lenye_base.base_data.getapiUrl() + lenye_base.api_url.interact.qAaList, lenye_base.base_data.getformatting({
                    aswServiceType: 'live',
                    aswObjId: this.lylId,
                    rows: ''
                }), function (e) {
                    for (let i = 0; i < e.data.length; i++) {
                        aswIds += e.data[i].aswId + ',';
                        listobj.push({
                            objId: e.data[i].aswId,
                            type: 'asw',
                        });
                        lenye_base.httpPost(lenye_base.base_data.getapiUrl() + lenye_base.api_url.interact.answerList, lenye_base.base_data.getformatting({
                            aswId: e.data[i].aswId
                        }), function (res) {
                            e.data[i].anserList = res.data;
                        });
                        // lenye_base.httpPost(lenye_base.base_data.getapiUrl() + lenye_base.api_url.interact.addReadTimes, lenye_base.base_data.getformatting({
                        //     objId: e.data[i].aswId,
                        //     type: 'asw'
                        // }), function(res) {
                        //     e.data[i].anserList = res.data;
                        // });
                    }
                    setTimeout(function () {
                        that.questionslist = e;
                    }, 1000);
                    console.log(aswIds);
                });
            },
            subque() {
                const that = this;
                if (!this.question) {
                    Toast.fail('提问内容不能为空');
                    return false;
                }
                lenye_base.httpPost(lenye_base.base_data.getapiUrl() + lenye_base.api_url.interact.addQues, lenye_base.base_data.getformatting({
                    aswTitle: this.livedetail.lylName,
                    aswContent: this.question,
                    aswIsOpen: '1',
                    aswObjId: this.lylId,
                    aswServiceType: 'live',
                }), function (e) {
                    if (e.success === '1') {
                        Toast.success('已提问');
                        that.question = '';
                        // 重新渲染一次列表
                        that.questions();
                    } else {
                        Toast.fail(e.message);
                    }
                });
            },
            //回答切换
            aswclick(name, sawid) {
                this.asworque = 1;
                this.questionasw = '@' + name + ':';
                this.questionaswid = sawid;
            },
            subasw() {
                const that = this;
                if (!this.questionasw) {
                    Toast.fail('内容不能为空');
                    return false;
                }
                lenye_base.httpPost(lenye_base.base_data.getapiUrl() + lenye_base.api_url.interact.answerListAdd, lenye_base.base_data.getformatting({
                    aswId: this.questionaswid,
                    aswdContent: this.questionasw,
                }), function (e) {
                    if (e.success === '1') {
                        Toast.success('已回复');
                        that.question = '';
                        that.questionasw = '';
                        that.asworque = 0;
                        // 重新渲染一次列表
                        that.questions();
                    } else {
                        Toast.fail(e.message);
                    }
                });
            },
        }
    };
</script>
