<template>
    <view>
        <view
            :class="'nav-wrap ' + (navbarDataClone.background ? '' : 'border-bottom-after')"
            :style="
                'height: ' +
                navHeight +
                'px; background: ' +
                (navbarDataClone.background ? navbarDataClone.background : '#fff') +
                ' no-repeat; background-size: 100% 274rpx; display: ' +
                (navbarDataClone.title === 'none' ? 'none' : 'block')
            "
        >
            <!-- 导航栏 中间的标题 -->
            <view class="nav-title" v-if="navbarDataClone.title" :style="'color: ' + (navbarDataClone.background ? '#fff' : '#333') + '; padding-top: ' + statusBarHeight + 'px;'">
                <text>{{ navbarDataClone.title }}</text>
            </view>
            <!-- 主页导航栏 样式 -->
            <div
                class="nav-capsule nav-index"
                v-if="navbarDataClone.isIndex"
                @tap.native="handleChangeHosp"
                :style="'color: ' + (navbarDataClone.background ? '#fff' : '#333') + '; padding-top: ' + statusBarHeight + 'px;'"
            >
                <image class="nav-index-img-new" :src="imgHost + '/images/icon/logo-words.png'" />
                <!-- <image class="nav-index-img" src="{{ imgHost + '/images/icon/nv_hospital@2x.png'}}" />
    <view class="nav-index-title-box">
      <text class="nav-index-title">{{userData && userData.hospDesc ? userData.hospDesc : ""}}</text>
    </view> -->
            </div>
            <!-- 导航栏  左上角的返回按钮 和home按钮 -->
            <view class="nav-capsule" :style="'padding-top: ' + statusBarHeight + 'px;'" v-if="navbarDataClone.isGoHome || navbarDataClone.isGoBack">
                <!-- 左上角的返回按钮，wx:if='{{!share}}'空制返回按钮显示
    从分享进入小程序时 返回上一级按钮不应该存在 -->
                <i @tap="navbackFun" v-if="!share && navbarDataClone.isGoBack" class="iconfont icon-fanhui" :style="'color: ' + (navbarDataClone.background ? '#fff' : '#999')"></i>
                <i
                    v-if="!share && navbarDataClone.isGoHome && navbarDataClone.isGoBack"
                    class="iconfont icon-shuxian"
                    :style="'color: ' + (navbarDataClone.background ? '#fff' : '#999')"
                ></i>
                <i @tap="backhomeFun" v-if="navbarDataClone.isGoHome" class="iconfont icon-index" :style="'color: ' + (navbarDataClone.background ? '#fff' : '#999')"></i>
            </view>
        </view>
        <van-popup
            class="nav-wrap-modal"
            :show="visible"
            closeable
            :close-on-click-overlay="false"
            @close="handleClose"
            close-icon-position="top-right"
            custom-style="width: 80%; background: transparent;"
        >
            <view :style="'background: url(' + messagePopupBg + ') no-repeat;background-size: cover'" class="nav-wrap-modal-main">
                <view class="nav-wrap-modal-content">
                    <view class="nav-wrap-modal-head">
                        {{
                            videoCallsData && videoCallsData.type === 'V'
                                ? videoCallsData && videoCallsData.userName + '医生邀请您视频看诊'
                                : videoCallsData && videoCallsData.type === 'D'
                                ? '提示'
                                : ''
                        }}
                    </view>
                    <view v-if="videoCallsData && videoCallsData.type === 'V' && !(scopeCamera && scopeRecord)" class="nav-wrap-modal-text">
                        检测到您未开启 {{ !scopeCamera && !scopeRecord ? '摄像头/麦克风权限' : !scopeCamera ? '摄像头权限' : '麦克风权限' }}
                    </view>
                    <view v-if="videoCallsData && videoCallsData.type === 'V' && scopeCamera && scopeRecord" class="nav-wrap-modal-text">
                        {{ navbarDataClone && navbarDataClone.patName ? navbarDataClone.patName : userData.patDesc }}您好
                    </view>
                    <view v-if="videoCallsData && videoCallsData.type === 'V' && scopeCamera && scopeRecord" class="nav-wrap-modal-text">请进入在线诊室进行视频看诊</view>
                    <view v-if="videoCallsData && videoCallsData.type === 'V' && !(scopeCamera && scopeRecord)" class="nav-wrap-modal-text">
                        让医生更好的进行诊疗，请先开启权限。
                    </view>
                    <view v-if="videoCallsData && videoCallsData.type === 'D'" class="nav-wrap-modal-text">医生已为您开具处方</view>
                    <view v-if="videoCallsData && videoCallsData.type === 'D'" class="nav-wrap-modal-text">请尽快支付相关费用</view>
                </view>
                <view class="nav-wrap-modal-btn">
                    <text @tap.stop.prevent="queryPermissionStatus">
                        {{
                            videoCallsData && videoCallsData.type === 'V'
                                ? !(scopeCamera && scopeRecord)
                                    ? '开启权限'
                                    : '立即看诊'
                                : videoCallsData && videoCallsData.type === 'D'
                                ? '现在去支付'
                                : ''
                        }}
                    </text>
                </view>
            </view>
        </van-popup>
        <van-dialog id="van-dialog" />
        <view
            class="new-message"
            @tap="goMyConsultation"
            :style="'display: ' + (overlayVisible && !navbarDataClone.isMonitorNewMessage ? 'flex' : 'none') + '; top: ' + statusBarHeight + 'px'"
        >
            <view class="new-message-text">
                <i class="iconfont icon-xiaoxi"></i>
                {{ videoCallsData.newMsg }}
            </view>
            <text @tap.stop.prevent="handleOverlayHide" class="text-delete">X</text>
        </view>
        <view class="new-message new-message-login" v-if="isLogin">
            <view class="new-message-text">
                <i class="iconfont icon-yichang"></i>
                离线状态下不能接收与发送消息，是否重新登录？？？
            </view>
            <view class="new-message-btn">
                <text @tap.stop.prevent="logInAgain">重新登录</text>
            </view>
            <text @tap.stop.prevent="handleLoginHide" class="text-delete">X</text>
        </view>
        <!-- <van-popup class="wc-permission-modal" show="{{ !(scopeCamera&&scopeRecord) }}" close-icon-position="top-right" custom-style="width: 80%;" overlay-style="background: rgba(0,0,0,.4)">
  <view class="wc-permission-modal-context">
    <view class="wc-permission-modal-head border-bottom-after">视频问诊需要以下权限</view>
    <view class="wc-permission-modal-content">
      <view class="wc-permission-modal-title"><text class="dian"></text>{{(!scopeCamera&&!scopeRecord) ? "摄像头/麦克风" : (!scopeCamera ? "摄像头" : "麦克风")}}</view>
      <view class="wc-permission-modal-desc">让医生更好的进行诊疗，满足政策监管要求。</view>
    </view>
    <view class="wc-permission-modal-btn border-top-before">
      <text bindtap="handleGoBack">取消</text>
      <text class="border-left-before" bindtap="handleOpenPermission">确认</text>
    </view>
  </view>
</van-popup> -->
        <van-toast id="van-toast" />
        <view v-if="announcementKey !== null && navbarDataClone && navbarDataClone.announcementData && navbarDataClone.announcementData.length > 0" class="announcement">
            <view>
                <image :src="imgHost + '/images/icon/notice.png'" alt="" class="image"></image>
            </view>
            <view class="title-A">
                <text>{{ navbarDataClone.announcementData[announcementKey].Title }}</text>
            </view>
            <view class="SecondTitle-A">
                <text>{{ navbarDataClone.announcementData[announcementKey].SecondTitle }}</text>
            </view>
            <view class="NoticeContent-A">
                {{ navbarDataClone.announcementData[announcementKey].NoticeContent }}
            </view>
            <view class="time-A">
                <text>{{ navbarDataClone.announcementData[announcementKey].ReleaseDate }}</text>
                <view>
                    <text>{{ navbarDataClone.announcementData[announcementKey].Signature }}</text>
                </view>
            </view>
            <view class="cancel-All">
                <text @tap="cancelAnnoun" class="cancel-A cancel" v-if="navbarDataClone.announcementData.length > 1">关闭</text>
                <text @tap="announcementNext" :class="navbarDataClone.announcementData.length > 1 ? 'cancel-A color' : 'cancel-B color'">
                    {{ announcementKey === navbarDataClone.announcementData.length - 1 ? '确定' : '下一条' }}
                </text>
            </view>
        </view>
        <van-overlay :show="announcementKey !== null && navbarDataClone && navbarDataClone.announcementData && navbarDataClone.announcementData.length > 0" @click="cancelAnnoun" />
    </view>
</template>

<script>
// 自定义导航栏
import { $http } from '../../utils/https';
import { Util } from '../../utils/util';
import { httpConfig } from '../../utils/httpConfig';
import TIM from 'tim-wx-sdk';
import GenerateTestUserSig from '../../debug/GenerateTestUserSig.js';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const app = getApp();
let timer = null;
export default {
    data() {
        return {
            imgHost: httpConfig.imgHost,

            userData: {
                patDesc: ''
            },

            navHeight: app.globalData.navHeight,
            spaceHeight: app.globalData.spaceHeight,
            navTitleHeight: app.globalData.navTitleHeight,
            statusBarHeight: app.globalData.statusBarHeight,
            visible: false,
            messagePopupBg: httpConfig.imgHost + '/images/icon/message-popup.png',

            videoCallsData: {
                type: '',
                userName: ''
            },

            overlayVisible: false,
            isLogin: false,
            scopeRecord: true,
            scopeCamera: true,
            hospList: [],
            curHosp: '',

            option1: [
                {
                    text: '全部商品',
                    value: 0
                },
                {
                    text: '新款商品',
                    value: 1
                },
                {
                    text: '活动商品',
                    value: 2
                }
            ],

            announcementKey: 0,
            share: '',

            navbarDataClone: {
                background: false,
                title: '',
                isIndex: '',
                isGoHome: '',
                isGoBack: '',
                patName: '',
                isMonitorNewMessage: '',
                announcementData: ''
            },

            Title: '',
            SecondTitle: '',
            NoticeContent: '',
            ReleaseDate: '',
            Signature: ''
        };
    },
    options: {
        styleIsolation: 'shared'
    },
    // 组件的对外属性，是属性名到属性设置的映射表
    props: {
        /*
    navbarData所包含的参数
      isGoHome 是否显示返回首页的图标
      isGoBack 是否显示返回上一页的图标
      title 当前界面的标题
      isMonitorCalls 是否需要监听医生来电提醒 默认不传则监听，传 noMonitor 则不监听
      isMonitorNewMessage 是否需要提醒有新消息  默认不传，传true则不提醒
  */
        navbarData: {
            //navbarData   由父页面传递的数据，变量名字自命名
            type: Object,

            default: () => ({})
        }
    },
    mounted() {
        // 处理小程序 attached 生命周期
        this.attached();
    },
    // 组件的方法，包括事件响应函数和任意的自定义方法，关于事件响应函数的使用
    methods: {
        handlePageShow: function () {
            // 监听呼叫
            if (!(this.navbarData && this.navbarData.isMonitorCalls && this.navbarData.isMonitorCalls === 'noMonitor')) {
            }
            app.globalData.context = this;
            this.autoUpdate();
        },

        handlePageHide: function () {
            this.setData(
                {
                    visible: false
                },
                () => {
                    clearInterval(timer); // 清除定时器
                }
            );
        },

        //  组件生命周期函数-在组件实例进入页面节点树时执行)
        attached: function () {
            // 获取是否是通过分享进入的小程序
            // 定义导航栏的高度   方便对齐
            this.setData({
                share: app.globalData.share,
                visible: false,
                userData: uni.getStorageSync('userData')
            });
            // 设置window头部颜色
            if (this.navbarData && this.navbarData.background) {
                uni.setNavigationBarColor({
                    frontColor: '#ffffff',
                    backgroundColor: '#ffffff'
                });
            }
        },

        // 更新userData
        upDateUserData: function () {
            console.log('更新userData');
            this.setData({
                userData: uni.getStorageSync('userData')
            });
        },

        autoUpdate: function () {
            console.log('autoUpdate更新提示');
            var that = this;
            // 获取小程序更新机制兼容
            if (uni.canIUse('getUpdateManager')) {
                const updateManager = uni.getUpdateManager();
                //1. 检查小程序是否有新版本发布
                updateManager.onCheckForUpdate(function (res) {
                    // 请求完新版本信息的回调
                    if (res.hasUpdate) {
                        //检测到新版本，需要更新，给出提示
                        uni.showModal({
                            title: '更新提示',
                            content: '检测到新版本，是否下载新版本并重启小程序？',
                            success: function (res) {
                                if (res.confirm) {
                                    //2. 用户确定下载更新小程序，小程序下载及更新静默进行
                                    that.downLoadAndUpdate(updateManager);
                                } else if (res.cancel) {
                                    //用户点击取消按钮的处理，如果需要强制更新，则给出二次弹窗，如果不需要，则这里的代码都可以删掉了
                                    uni.showModal({
                                        title: '温馨提示~',
                                        content: '本次版本更新涉及到新的功能添加，旧版本无法正常访问的哦~',
                                        showCancel: false,
                                        //隐藏取消按钮
                                        confirmText: '确定更新',
                                        //只保留确定更新按钮
                                        success: function (res) {
                                            if (res.confirm) {
                                                //下载新版本，并重新应用
                                                that.downLoadAndUpdate(updateManager);
                                            }
                                        }
                                    });
                                }
                            }
                        });
                    }
                });
            } else {
                // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
                uni.showModal({
                    title: '提示',
                    content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
                });
            }
        },

        /**
         * 下载小程序新版本并重启应用
         */
        downLoadAndUpdate: function (updateManager) {
            uni.showLoading();
            //静默下载更新小程序新版本
            updateManager.onUpdateReady(function () {
                uni.hideLoading();
                //新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                updateManager.applyUpdate();
            });
            updateManager.onUpdateFailed(function () {
                // 新的版本下载失败
                uni.showModal({
                    title: '已经有新版本了哟~',
                    content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~'
                });
            });
        },

        // 返回上一页面
        navbackFun() {
            let { navbarData } = app.globalData.context.data;
            if (navbarData && navbarData.isGoBack === 'home') {
                uni.switchTab({
                    url: '/pages/tabBar/index/index'
                });
            } else {
                uni.navigateBack();
            }
        },

        //返回到首页
        backhomeFun() {
            uni.switchTab({
                url: '/pages/tabBar/index/index'
            });
        },

        /**
         * 监听组件属性变更，外部变更组件属性时触发该监听
         * @param {Object} data newVal，oldVal
         */
        propertyObserverFun(data) {
            if (data.name === 'navbarData') {
                console.log(data.newVal);
            }
        },

        // 监听消息变化
        monitorMessageChanges() {
            if (app.globalData && app.globalData.tim) {
                console.log('触发了监听');
                app.globalData.tim.on(TIM.EVENT.MESSAGE_RECEIVED, this.handleMessageReceived);
                app.globalData.tim.on(TIM.EVENT.KICKED_OUT, this.monitorKickedOut);
            }
        },

        // 登录
        login: Util.debounce(function (userID) {
            let userData = GenerateTestUserSig.genTestUserSig(userID || '');
            if (app.globalData.tim) {
                let promise = app.globalData.tim.login({
                    userID: userID || '',
                    userSig: userData && userData.userSig ? userData.userSig : ''
                });
                promise
                    .then((imResponse) => {
                        app.globalData.isLogOut = true;
                        console.log('tim登录成功：', userID);
                    })
                    .catch((imError) => {
                        // this.signOut('signOut', userID)
                        console.log('tim登录失败：', userID, imError); // 登录失败的相关信息
                    });
            }
        }),

        // 重新登录
        logInAgain: Util.debounce(function () {
            let userData = uni.getStorageSync('userData');
            app.globalData.context.login(userData.imUserID);
            app.globalData.context.handleLoginHide('repeat');
        }),

        handleLoginShow() {
            app.globalData.context.setData({
                isLogin: true
            });
        },

        handleLoginHide(isRepeat) {
            app.globalData.context.setData(
                {
                    isLogin: false
                },
                () => {
                    if (isRepeat === 'repeat') {
                        setTimeout(() => {
                            app.globalData.context.$emit('handleSend'); // 首页弹出消息列
                        }, 500);
                    }
                }
            );
        },

        // 根据传入的type获取对应的数据
        interceptTheValueOfTheStr(str, type) {
            if (str && str.indexOf('$') !== -1) {
                let arr = str.split('$');
                let res = '';
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i].split('^')[0] === type) {
                        res = arr[i].split('^')[1];
                        break;
                    }
                }
                return res;
            }
        },

        vibrateLong: function () {
            if (timer) {
                clearInterval(timer);
            }
            timer = setInterval(() => {
                uni.vibrateLong({
                    success: (res) => {
                        console.log(res);
                    }
                });
                this.playBGM();
            }, 1500);
        },

        /**
         * 播放背景音
         * @param {Object} params url
         * @returns {Promise}
         */
        playBGM(params) {
            uni.playBackgroundAudio({
                dataUrl: httpConfig.imgHost + '/images/Voice/startvideo.mp3',
                title: '',
                coverImgUrl: ''
            });
            // return new Promise((resolve, reject) => {
            //   this.data.pusher.getPusherContext().playBGM({
            //     // url: httpconfig.imgDomain + '/images/Voice/startvideo.mp3',
            //     url: httpConfig.imgHost + '/images/Voice/startvideo.mp3',
            //     // 已经有相关事件不需要在这里监听,目前用于测试
            //     success: () => {
            //       // this._emitter.emit(EVENT.BGM_PLAY_START)
            //       resolve()
            //     },
            //     fail: () => {
            //       this._emitter.emit(EVENT.BGM_PLAY_FAIL)
            //       reject(new Error('播放背景音失败'))
            //     },
            //     // complete: () => {
            //     //   this._emitter.emit(EVENT.BGM_PLAY_COMPLETE)
            //     // },
            //   })
            // })
        },

        // 监听消息接收
        handleMessageReceived: function (event) {
            // 需要判断toUser是不是自己
            let { navbarData } = app.globalData.context.data;
            try {
                // console.log("监听消息接收", event);
                let userData = uni.getStorageSync('userData');
                let videoCallsData = {};
                if (event && event.init === 'home') {
                    videoCallsData = event;
                } else {
                    let textStr = event.data[0].payload.text;
                    videoCallsData = textStr ? JSON.parse(textStr) : {};
                }
                console.log(userData.imUserID, event.data[0].to);
                if (userData.imUserID !== event.data[0].to) {
                    return;
                }
                console.log(videoCallsData);
                if (videoCallsData && videoCallsData.type === 'V') {
                    // 处于视频通话界面则不需要弹出视频通话提醒框 --- isMonitorCalls === "noMonitor"
                    if (navbarData && navbarData.isMonitorNewMessage && navbarData.isMonitorCalls === 'noMonitor') {
                        if (timer) {
                            clearInterval(timer);
                        }
                        return;
                    }
                    // if (videoCallsData && (videoCallsData.type === 'V' || videoCallsData.type === 'D')) {
                    app.globalData.context.setData(
                        {
                            visible: true,
                            videoCallsData
                        },
                        () => {
                            // if (videoCallsData.type === 'D') {
                            //   wx.vibrateLong({
                            //     success: (res) => {
                            //       console.log(res)
                            //     }
                            //   })
                            // }
                            // if (videoCallsData.type === 'V') {
                            //   app.globalData.context.vibrateLong();
                            //   app.globalData.context.queryPermissionStatus('noFn')
                            // }
                            app.globalData.context.vibrateLong();
                            app.globalData.context.queryPermissionStatus('noFn');
                        }
                    );
                } else if (videoCallsData && videoCallsData.type === 'D') {
                    return;
                } else if (videoCallsData && videoCallsData.type === 'E') {
                    app.globalData.context.setData(
                        {
                            visible: false
                        },
                        () => {
                            clearInterval(timer);
                            Toast({
                                context: app.globalData.context,
                                duration: 2000,
                                message: videoCallsData.userName + '医生已挂断视频呼叫。'
                            });
                            let msg = '您有一个视频呼叫未接听。';
                            app.globalData.context.$emit('checkForNewMessage', {
                                detail: {
                                    ...videoCallsData,
                                    newMsg: msg
                                }
                            }); // 首页弹出消息列
                        }
                    );
                } else {
                    let newMsgData = {
                        ...videoCallsData
                    };
                    let obj = {
                        M: newMsgData.userName + '：' + (newMsgData.text ? newMsgData.text : newMsgData.image ? '图片' : ''),
                        H: newMsgData.userName + '：' + (newMsgData.text ? newMsgData.text : newMsgData.image ? '图片' : ''),
                        B: newMsgData.patName + '您好,' + newMsgData.userName + '医生已停诊，请选择别的医生就诊。',
                        D: '您有一条待支付订单，请尽快支付。',
                        F: '您有一个待评价的订单未评价。可以点我直接去评价哦。'
                    };
                    newMsgData.newMsg = newMsgData && newMsgData.type ? obj[newMsgData.type] : newMsgData.text;
                    app.globalData.context.setData(
                        {
                            videoCallsData: newMsgData
                        },
                        () => {
                            app.globalData.context.handleShowHeaderMessage(event);
                        }
                    );
                }
            } catch (error) {
                console.log('CatchClause', error);
                console.log('CatchClause', error);
                console.log(error);
            }
        },

        // 是否弹出消息层
        handleShowHeaderMessage(event) {
            let { navbarData } = app.globalData.context.data;
            if (navbarData && navbarData.isMonitorNewMessage && navbarData.isMonitorNewMessage === 'homeNoModalMsg') {
                app.globalData.context.$emit('checkForNewMessage', {
                    detail: app.globalData.context.data.videoCallsData
                }); // 首页弹出消息列
            } else if (navbarData.isMonitorNewMessage === 'im') {
                app.globalData.context.$emit('handleMessageReceived', {
                    detail: event
                }); // 首页弹出消息列
            } else if (navbarData.isMonitorNewMessage === 'message') {
                app.globalData.context.$emit('scrolltoupper', {
                    detail: event
                }); // 首页弹出消息列
            } else {
                app.globalData.context.handleOverlayShow(); // 除首页外其他界面顶部展示新消息
            }
        },

        // 监听是否被踢下线
        monitorKickedOut: function (event) {
            console.log('monitorKickedOut', event);
            let userData = uni.getStorageSync('userData');
            Dialog.confirm({
                context: app.globalData.context,
                title: '账号异常',
                message: '您的账号在别处登录，是否重新登录???取消则接收不到消息，请确认之后操作。'
            })
                .then(() => {
                    app.globalData.context.login(userData.imUserID);
                    console.log('确定');
                })
                .catch((error) => {
                    console.log('取消了：', error);
                    app.globalData.isLogOut = false;
                });
        },

        // 监听是否有视频呼叫
        // monitorVideoCalls(isInterval) {
        //   // console.log("触发了monitorVideoCalls：", isInterval)
        //   let userData = wx.getStorageSync('userData');
        //   if (!(userData && userData.hisPatID)) {
        //     return;
        //   }
        //   let data = {
        //     params: [{
        //       patID: userData&&userData.hisPatID ? userData.hisPatID : ""
        //     }]
        //   }
        //   $http.post("urlS", this, {
        //     code: "02090010",
        //     data: data,
        //     namespace: "Y",
        //     success: function (res) {
        //       if (+res.errorCode === 0) {
        //         let refreshTime = res.result && res.result.refreshTime ? res.result.refreshTime : 30;
        //         if (res.result.doctorStatus === "Y" && !this.data.visible) {
        //           this.setData({ visible: true, videoCallsData: res.result });
        //         }
        //         if (isInterval !== 'no') { // 定时触发
        //           timer = setInterval(() => {
        //             this.monitorVideoCalls('no');
        //           }, refreshTime * 1000)
        //         }
        //       }
        //     }
        //   })
        // },

        // 关闭弹窗
        handleClose() {
            this.setData(
                {
                    visible: false
                },
                () => {
                    clearInterval(timer);
                }
            );
        },

        // 跳转至我的就诊
        goMyConsultation() {
            this.handleOverlayHide();
            let { videoCallsData } = this;
            console.log(videoCallsData);
            if (videoCallsData && videoCallsData.type === 'D') {
                uni.navigateTo({
                    url: '/pages/order/pages/orderType/orderType?admID=' + videoCallsData.admID
                });
            } else if (videoCallsData.type === 'F') {
                uni.navigateTo({
                    url:
                        '/pages/mine/evaluate/evaluate?admID=' +
                        videoCallsData.admID +
                        '&doctorname=' +
                        videoCallsData.userName +
                        '&doctorID=' +
                        videoCallsData.userID +
                        '&id=' +
                        (videoCallsData.msgID || '')
                });
            } else if (videoCallsData.type === 'M' || videoCallsData.type === 'H') {
                // 区分图咨询与视问诊跳转到相对应的界面
                uni.navigateTo({
                    url:
                        '/pages/message/pages/im/room/room?admID=' +
                        videoCallsData.admID +
                        '&userID=patient' +
                        videoCallsData.patID +
                        '&toUser=user' +
                        videoCallsData.userID +
                        '&toUserName=' +
                        videoCallsData.userName +
                        '&patName=' +
                        videoCallsData.patName
                });
            } else {
                uni.navigateTo({
                    url: '../../mine/myConsultation/myConsultation'
                });
            }
        },

        // 显示遮罩层
        handleOverlayShow() {
            app.globalData.context.setData({
                overlayVisible: true
            });
        },

        // 关闭遮罩层
        handleOverlayHide() {
            app.globalData.context.setData({
                overlayVisible: false
            });
        },

        // 点击图咨询按钮时匹配是否咨询的是同一个医生， 是的话则关闭全局消息弹窗
        matchOrNot(admid) {
            let { videoCallsData } = app.globalData.context.data;
            console.log(videoCallsData);
            if (admid === videoCallsData.admID) {
                app.globalData.context.handleOverlayHide();
            }
        },

        // 权限取消
        handleGoBack() {
            app.globalData.context.setData({
                scopeRecord: true,
                scopeCamera: true,
                visible: true
            });
        },

        // 查询权限状态
        queryPermissionStatus(isFn) {
            if (!isFn || isFn !== 'noFn') {
                console.log('触发了isFn');
                clearInterval(timer);
            }
            let { videoCallsData } = this;
            if (videoCallsData && videoCallsData.type === 'D') {
                uni.navigateTo({
                    url: '/pages/order/pages/orderType/orderType?admID=' + videoCallsData.admID
                });
                return;
            }
            uni.getSetting({
                success: (res) => {
                    console.log('查询权限状态', res);
                    let scopeRecord = true;
                    let scopeCamera = true;
                    if (!res.authSetting['scope.record']) {
                        scopeRecord = false;
                    }
                    if (!res.authSetting['scope.camera']) {
                        scopeCamera = false;
                    }
                    console.log('查询权限状态', scopeRecord, scopeCamera);
                    if (!scopeRecord || !scopeCamera) {
                        app.globalData.context.setData({
                            scopeRecord,
                            scopeCamera,
                            visible: true
                        });
                        if (isFn !== 'noFn') {
                            app.globalData.context.handleOpenPermission();
                        }
                    } else {
                        console.log('触发了更新');
                        app.globalData.context.setData({
                            scopeRecord: true,
                            scopeCamera: true,
                            visible: true
                        });
                        if (isFn !== 'noFn') {
                            app.globalData.context.seeADoctorImmediately();
                        }
                    }
                },
                fail: function (error) {
                    console.log('查询权限状态失败', error);
                }
            });
        },

        // 开启权限
        handleOpenPermission() {
            uni.openSetting({
                success: (res) => {
                    if (!res.authSetting['scope.record']) {
                        uni.authorize({
                            scope: 'scope.record',
                            success: () => {
                                console.log('获取麦克风权限成功。');
                                app.globalData.context.queryPermissionStatus('noFn');
                            },
                            fail: () => {
                                // Toast({
                                //   context: app.globalData.context,
                                //   message: "获取麦克风权限失败。"
                                // })
                                app.globalData.context.queryPermissionStatus('noFn');
                            }
                        });
                    } else {
                        app.globalData.context.queryPermissionStatus('noFn');
                    }
                    if (!res.authSetting['scope.camera']) {
                        uni.authorize({
                            scope: 'scope.camera',
                            success: () => {
                                console.log('获取摄像头权限成功。');
                                app.globalData.context.queryPermissionStatus('noFn');
                            },
                            fail: () => {
                                // Toast({
                                //   context: app.globalData.context,
                                //   message: "获取摄像头权限失败。"
                                // })
                                app.globalData.context.queryPermissionStatus('noFn');
                            }
                        });
                    } else {
                        app.globalData.context.queryPermissionStatus('noFn');
                    }
                },
                fail: function (error) {
                    console.log('授权设置失败', error);
                }
            });
        },

        // 立即看诊 -- 跳转至候诊室
        seeADoctorImmediately() {
            let { videoCallsData } = app.globalData.context.data;
            let data = {
                params: [
                    {
                        admID: videoCallsData.admID || '' // 就诊ID
                    }
                ]
            };

            $http.post('urlS', this, {
                code: '03100075',
                data: data,
                namespace: 'Y',
                success: function (res) {
                    if (+res.errorCode === 0) {
                        app.globalData.context.allowToJoin(res.result);
                    } else {
                        Toast({
                            context: app.globalData.context,
                            message: res.errorMessage
                        });
                    }
                },
                error: function (error) {
                    Toast({
                        context: app.globalData.context,
                        message: error
                    });
                }
            });
            // wx.navigateTo({ // 跳转到候诊室
            //   url: '/pages/index/pages/waitingConsulation/waitingConsulation?admID=' + videoCallsData.admID,
            // })
        },

        // 检查人员是否允许加入房间
        allowToJoin(visitRelatedInformation) {
            let data = {
                params: [
                    {
                        roomID: visitRelatedInformation.roomID || '',
                        // 房间ID
                        userType: 'P',
                        // U-医生,P-患者
                        userID: visitRelatedInformation.patID || '',
                        // 人员ID
                        frUser: visitRelatedInformation.frUserID || '' //
                    }
                ]
            };

            $http.post('urlS', this, {
                code: '02090003',
                data: data,
                namespace: 'Y',
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let path = '/pages/message/pages/im/trtcRoom/trtcRoom';
                        uni.navigateTo({
                            url: path,
                            success: (result) => {
                                result.eventChannel.emit('visitRelatedInformation', visitRelatedInformation);
                            }
                        });
                    } else {
                        Toast({
                            context: app.globalData.context,
                            message: res.errorMessage
                        });
                    }
                },
                error: function (error) {
                    Toast({
                        context: app.globalData.context,
                        message: error
                    });
                }
            });
        },

        cancelAnnoun: function () {
            app.globalData.context.setData({
                navbarDataClone: {
                    ...app.globalData.context.data.navbarData,
                    announcementData: []
                },
                announcementKey: null
            });
        },

        //下一条
        announcementNext: function () {
            if (app.globalData.context.data.announcementKey !== app.globalData.context.data.navbarData.announcementData.length - 1) {
                app.globalData.context.setData({
                    announcementKey: app.globalData.context.data.announcementKey + 1
                });
            } else {
                app.globalData.context.cancelAnnoun();
            }
        },

        // 切换医院
        handleChangeHosp: function () {
            // this.triggerEvent('handleChangeHosp');
        }
    },
    // 组件生命周期函数-在组件实例被从页面节点树移除时执行)
    destroyed: function () {
        // let _this = this;
        // app.globalData.tim.off(TIM.EVENT.MESSAGE_RECEIVED, _this.handleMessageReceived);
        // app.globalData.tim.off(TIM.EVENT.KICKED_OUT, _this.monitorKickedOut);
        // clearInterval(timer); // 清除定时器
    },
    created: function () {},
    watch: {
        navbarData: {
            handler: function (newVal, oldVal) {
                this.navbarDataClone = this.clone(this.navbarData);
                // console.log("触发了：observer", newVal, oldVal)
                if (JSON.stringify(newVal.isMonitorCalls) !== JSON.stringify(oldVal.isMonitorCalls)) {
                    this.setData(
                        {
                            navbarDataClone: newVal
                        },
                        () => {
                            console.log(this.navbarData);
                            if (!(this.navbarData && this.navbarData.isMonitorCalls && this.navbarData.isMonitorCalls === 'noMonitor')) {
                                // this.monitorMessageChanges();
                                app.globalData.context = this;
                            }
                        }
                    );
                }
            },

            immediate: true,
            deep: true
        }
    }
};
</script>
<style>
@import '../assets/css/iconfont.css';
@import '../assets/css/common.css'; /* 顶部要固定定位   标题要居中   自定义按钮和标题要和右边微信原生的胶囊上下对齐 */

.nav-wrap {
    position: fixed;
    width: 100%;
    top: 0;
    left: 0;
    color: #000;
    z-index: 9999999;
    background-size: 100% auto;
}

/* 标题要居中 */
.nav-title {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    max-width: 400rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin: auto;
    font-size: 32rpx;
    padding-bottom: 14px;
}

.nav-capsule {
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: absolute;
    width: 120rpx;
    left: 30rpx;
    top: 0;
    right: 0;
    bottom: 0;
    padding-bottom: 10px;
}

.nav-capsule .iconfont {
    margin-top: -14rpx;
}

.navbar-v-line {
    color: #ddd;
}

.nav-content {
    display: inline-block;
    width: 0;
}

.nav-capsule .iconfont {
    font-size: 36rpx;
}

/* 弹窗 */
.nav-wrap-modal .nav-wrap-modal-main {
    width: 100%;
    min-height: 521rpx;
    padding: 220rpx 42rpx 0 42rpx;
    box-sizing: border-box;
}

.nav-wrap-modal .nav-wrap-modal-content {
    width: 100%;
    color: #666;
    box-sizing: border-box;
    text-align: center;
}

.nav-wrap-modal .nav-wrap-modal-head {
    font-size: 36rpx;
    margin-bottom: 24rpx;
    font-weight: 700;
    color: #333;
}

.nav-wrap-modal .nav-wrap-modal-text {
    font-size: 28rpx;
    line-height: 48rpx;
}

.nav-wrap-modal .van-icon {
    color: #fff;
    font-size: 32rpx;
}

.nav-wrap-modal-btn {
    margin-top: 24rpx;
    width: 100%;
    padding: 0 48rpx;
    box-sizing: border-box;
}

.nav-wrap-modal-btn text {
    display: inline-block;
    width: 100%;
    text-align: center;
    height: 80rpx;
    line-height: 80rpx;
    color: #fff;
    background: linear-gradient(268deg, rgba(19, 165, 252, 1) 0%, rgba(7, 208, 255, 1) 100%);
    border-radius: 40rpx;
}

.new-message {
    position: fixed;
    left: 0;
    background: rgba(0, 0, 0, 0.5);
    color: #fff;
    width: 100%;
    z-index: 9999;
    padding: 12rpx 24rpx;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.new-message .new-message-text {
    max-width: 90%;
    display: flex;
    align-items: center;
    white-space: initial;
}

.new-message .new-message-text icon.iconfont {
    font-size: 48rpx;
    margin-right: 8rpx;
}

.new-message .text-delete {
    color: #fff;
}

.new-message-login {
    padding-right: 12rpx;
}

.new-message .new-message-btn {
    margin: 0 24rpx 0 12rpx;
}

.new-message .new-message-btn text {
    width: 120rpx;
    display: inline-block;
    text-align: center;
    padding: 12rpx;
    background: #1890ff;
    border-radius: 8rpx;
}

.nav-wrap-modal .van-popup__close-icon.van-popup__close-icon--top-right {
    color: #fff;
    top: 43rpx;
    right: 10rpx;
}

.nav-index {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    width: auto;
    line-height: inherit !important;
    height: 64rpx;
}

.nav-index-img {
    width: 27rpx;
    height: 33rpx;
}

.nav-index-img-new {
    width: 147rpx;
    height: 46rpx;
}

.nav-index-title-box {
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.nav-index-title {
    margin-left: 12rpx;
    margin-right: 10rpx;
    font-size: 34rpx;
    color: #fff;
    height: 48rpx;
}

.nav-index-text {
    font-weight: 400;
    color: #333333;
    line-height: 48px;
    margin-left: 15rpx;
    margin-bottom: 5rpx;
}

.en-text {
    font-size: 18rpx;
    padding-left: 6px;
    padding-right: 10px;
    color: rgba(255, 255, 255, 0.5);
}

.announcement {
    position: fixed;
    top: 30%;
    left: 8%;
    z-index: 10;
    background-color: #fff;
    width: 75%;
    border-radius: 14rpx;
    padding: 10rpx 30rpx;
}

.announcement .image {
    width: 220rpx;
    height: 200rpx;
    position: absolute;
    top: -111rpx;
    left: 36%;
}

.announcement .title-A {
    text-align: center;
    font-size: 34rpx;
    font-weight: 600;
    margin-top: 75rpx;
}

.announcement .SecondTitle-A {
    margin-top: 15rpx;
    font-size: 28rpx;
}

.announcement .time-A {
    text-align: right;
}

.announcement .cancel-A {
    display: inline-block;
    width: 47%;
    text-align: center;
    height: 80rpx;
    line-height: 80rpx;
}

.announcement .cancel-B {
    display: inline-block;
    width: 57%;
    text-align: center;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 8rpx;
}

.announcement .cancel-All {
    text-align: center;
    margin-top: 32rpx;
    margin-bottom: 15rpx;
}

.announcement .cancel-All .color {
    color: #fff;
    background-color: #1989fa;
    border-radius: 10rpx;
    margin-left: 10rpx;
}

.announcement .cancel-All .cancel {
    border: 1px solid #f1f1f1;
    border-radius: 10rpx;
}

.announcement .NoticeContent-A {
    font-size: 28rpx;
    color: #696969;
    text-indent: 2em;
}
</style>
