<script>
    import siteinfo from './siteinfo.js';
    import http from './static/js/http.js'
    export default {
        onLaunch: function() {
            // console.log('App Launch')
        },
        onShow: function(options) {
            // console.log(options, 'App Show')
            // 判断是否开启语音播报
            if (this.globalData.openYuyin && this.globalData.yuyinStoreId) {
                this.initSocket(this.globalData.yuyinStoreId)
            }
            if (options.query.scene) {
                uni.setStorageSync("is_login", 2);
                uni.setStorageSync("admin_id", options.query.scene);
            }

            if (options.referrerInfo.extraData) {
                uni.setStorageSync("token", options.referrerInfo.extraData.token);
            }

            const updateManager = uni.getUpdateManager(); // 获取更新管理器对象
            updateManager.onCheckForUpdate(function(res) {
                if (res.hasUpdate) {
                    updateManager.onUpdateReady(function() {
                        uni.showModal({
                            title: '更新提示',
                            content: '新版本已经准备好，是否重启应用?',
                            showCancel: false,
                            success: res => {
                                if (res.confirm) {
                                    updateManager.applyUpdate();
                                }
                            }
                        })
                    })
                    updateManager.onUpdateFailed(function() {
                        uni.showModal({
                            title: '提示',
                            content: '检查到有新版本，但是下载失败，请检查网络设置',
                            showCancel: false
                        })
                    })
                }
            })
        },

        onHide: function() {
            // console.log('App Hide')
            this.closeSocket()
        },

        globalData: {
            URL: siteinfo.siteroot,
            token: null,
            playList: [],
            isPlay: false,
            yuyinSocket: null,
            openYuyin: false,
            yuyinStoreId: ''
        },
        methods: {
            closeSocket(msg = '', exit = false) {
                uni.closeSocket({
                    code: 100,
                    reason: msg || "退出小程序 关闭链接",
                    complete: (r) => {

                        // console.log("退出时 关闭websocket")
                    }
                })
                if (exit) {
                    this.globalData.openYuyin = false
                }
            },
            connectSocket(urlNoProtocol) {
                uni.connectSocket({
                    url: `wss://${urlNoProtocol}/wss:8282`,
                    // url:'ws://121.40.165.18:8800',//测试链接
                    complete: e => {
                        // console.warn("connect socket complete", e);
                    }
                })
            },
            initSocket(store_id = '') {
                this.globalData.openYuyin = true
                this.globalData.yuyinStoreId = store_id
                console.log(store_id, '链接websocket')
                let that = this,
                    url = siteinfo.siteroot;
                var urlNoProtocol = url.replace(/^https?\:\/\//i, "");
               
                this.connectSocket(urlNoProtocol)
                this.globalData.yuyinSocket = uni.onSocketOpen(res => {
                    uni.onSocketMessage(res => {
                        console.warn("socket message", res)
                        let data = JSON.parse(res.data)
                        if (data.type == 'init') {
                            http({
                                url: 'yy/bindSocket',
                                data: {
                                    store_id,
                                    client_id: data.client_id
                                },
                                showLoading:true
                            }).then(res => {
                                console.log(res)
                            })

                        } else if (data.type == 'yuyin') {
                          
                            this.play(`${url}${data.route}`)
                        }

                    })
                    uni.onSocketClose(res => {
                        console.error("socket close", res)
                        if (res.code != 100) {
                            // console.warn("重新链接websocket")
                            this.connectSocket(urlNoProtocol)
                        }

                    })
                })
                uni.onSocketError(res => {
                    // console.warn("socket error", res)
                    // this.connectSocket(urlNoProtocol)
                })

            },
            // 播放语音
            play(src = '', isNext = false) {
                // console.log(this.globalData.isPlay, !isNext, 'isPlay')
                if (this.globalData.isPlay && !isNext) {
                    // console.log("加入队列");
                    this.globalData.playList.push(src)
                    // console.log(this.globalData.playList);
                    return false
                }
                this.globalData.isPlay = true
                // console.log("播放来单提醒", src)
                const innerAudioContext = uni.createInnerAudioContext();
                innerAudioContext.autoplay = true;
                innerAudioContext.src = src;
                innerAudioContext.onPlay(() => {
                    // console.log('开始播放');
                });
                innerAudioContext.onError((res) => {
                    // console.log(res.errMsg);
                    // console.log(res.errCode);
                });
                innerAudioContext.onEnded((res) => {
                    //播放完成，播放下一条
                    // console.log("播放完成", res);
                    this.execPlayList()
                })
            },
            //播放队列
            execPlayList() {
                // console.log("播放队列");
                let list = this.globalData.playList
                if (list.length > 0) {
                    let src = list.splice(0, 1)[0]
                    this.globalData.play = list
                    this.play(src, true)
                } else {
                    this.globalData.isPlay = false

                }
            },


        }

    }
</script>

<style>
    /*每个页面公共css */
    @import url("/static/css/iconfont.css");
    @import url("/static/css/flex.css");
    @import url("/static/css/common.css");
    @import url("/static/css/public.css");

    page {
        font-family: PingFang SC, PingFang SC-Regular;
    }

    swiper.square-dot .wx-swiper-dot,
    swiper.square-dot .a-swiper-dot,
    swiper.square-dot .uni-swiper-dot {
        background-color: #ffffff;
        opacity: 0.4;
        width: 10upx;
        height: 10upx;
        border-radius: 20upx;
        margin: 0 8upx !important;
    }

    swiper.square-dot .wx-swiper-dot.wx-swiper-dot-active,
    swiper.square-dot .a-swiper-dot.a-swiper-dot-active,
    swiper.square-dot .uni-swiper-dot.uni-swiper-dot-active {
        opacity: 1;
        width: 30upx;
    }

    /*  */
    .text-1 {
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .text-2 {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
    }

    /* 粘性布局 */
    .sticky {
        position: sticky;
        top: 0;
        z-index: 100;
    }

    /* 空列表 */
    .list-have-no {
        padding: 50rpx 0;
    }

    .list-have-no-img {
        display: block;
        width: 598rpx;
        height: 222rpx;
        margin: 0 auto;
    }

    /* 页面底部按钮 */
    .public-btm-btn-block {
        height: 200rpx;
        width: 100%;
    }

    .public-btm-btn-block .btn {
        width: 600rpx;
        height: 80rpx;
        padding: 0;
        margin: 0;
        border-radius: 16rpx;
        background: #C79A4E;
        box-shadow: 0 0 20rpx #DDC59D;
        position: absolute;
        left: 50%;
        bottom: 60rpx;
        margin-left: -300rpx;
        text-align: center;
        line-height: 80rpx;
        font-size: 32rpx;
        font-weight: 500;
        color: #fff;
    }

    /*  */
    .input-placeholder {
        font-size: 28rpx;
        color: #969696;
    }

    /* flex */
    .flex-row {
        display: flex;
        flex-flow: row nowrap;
        justify-content: flex-start;
        align-items: center;
    }

    .flex-row-between {
        display: flex;
        flex-flow: row nowrap;
        justify-content: space-between;
        align-items: center;
    }

    .flex-row-center {
        display: flex;
        flex-flow: row nowrap;
        justify-content: center;
        align-items: center;
    }

    .flex-row-start {
        display: flex;
        flex-flow: row nowrap;
        justify-content: flex-start;
        align-items: flex-start;
    }

    .flex-column {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
        align-items: center;
    }

    .flex-column-center {
        display: flex;
        flex-flow: column nowrap;
        justify-content: center;
        align-items: center;
    }

    .flex-column-between {
        display: flex;
        flex-flow: column nowrap;
        justify-content: space-between;
        align-items: center;
    }

    .flex-column-between-start {
        display: flex;
        flex-flow: column nowrap;
        justify-content: space-between;
        align-items: start;
    }

    .flex-y-bottom {
        display: -webkit-box;
        display: -webkit-flex;
        display: flex;
        -webkit-box-align: end;
        -webkit-align-items: flex-end;
        -ms-flex-align: end;
        -ms-grid-row-align: flex-end;
        align-items: flex-end;
    }
</style>
