<template>
    <view>
        <view
            :class="'nav-wrap ' + (navbarDataClone.bottom ? 'border-bottom-after' : '')"
            :style="
                'height: ' +
                (height * 2 + 80) +
                'rpx; background: ' +
                (navbarDataClone.background ? navbarDataClone.background : '#fff') +
                ' no-repeat; background-size: 100% 100%;'
            "
        >
            <!-- 导航栏 中间的标题 -->
            <view
                class="nav-title"
                :style="
                    'line-height: ' +
                    (height * 2 + 44) * 2 +
                    'rpx; color: ' +
                    (navbarDataClone.background ? '#fff' : '#333') +
                    ' ; text-align: ' +
                    (navbarDataClone.titleAlign ? navbarDataClone.titleAlign : 'center')
                "
            >
                {{ navbarDataClone.title }}
            </view>
            <!-- 导航栏  左上角的返回按钮 和home按钮 -->
            <view class="nav-capsule" :style="'line-height: ' + (height * 2 + 44) * 2 + 'rpx;'" v-if="navbarDataClone.isGoHome || navbarDataClone.isGoBack">
                <!-- 左上角的返回按钮，wx:if='{{!share}}'空制返回按钮显示
    从分享进入小程序时 返回上一级按钮不应该存在 -->
                <i
                    @tap="navbackFun"
                    v-if="!share && navbarDataClone.isGoBack"
                    class="iconfont icon-zuojiantou"
                    :style="'color: ' + (navbarDataClone.background ? '#fff' : '#999')"
                ></i>
                <i v-if="navbarDataClone.isGoHome && navbarDataClone.isGoBack" class="iconfont icon-shuxian"></i>
                <i @tap="backhomeFun" v-if="navbarDataClone.isGoHome" class="iconfont icon-index" :style="'color: ' + (navbarDataClone.background ? '#fff' : '#999')"></i>
            </view>
        </view>
        <van-popup v-if="visible" class="nav-wrap-modal" :show="visible" @close="handleClose" close-icon-position="top-right" custom-style="width: 80%; background: transparent;">
            <view :style="'background: url(' + messagePopupBg + ') no-repeat;background-size: 100% auto'" class="nav-wrap-modal-main">
                <view class="nav-wrap-modal-content">
                    <view class="nav-wrap-modal-head">邀请您视频看诊</view>
                    <view class="nav-wrap-modal-text">
                        医生：
                        <text class="docName">{{ docName }}</text>
                    </view>
                    <view class="nav-wrap-modal-text">
                        患者：
                        <text class="patName">{{ patName }}</text>
                    </view>
                </view>
                <view class="nav-wrap-modal-btn">
                    <text @tap.stop.prevent="seeADoctorImmediately">立即看诊</text>
                </view>
            </view>
        </van-popup>
        <view class="new-message" :style="'display: ' + (overlayVisible || navbarDataClone.overlayVisible ? 'flex' : 'none') + ';top:' + (height * 2 + 20) * 2 + 'rpx'">
            <view class="new-message-text" @tap="goMyConsultation">
                <i class="iconfont icon-xiaoxi"></i>
                {{ navbarData.message ? navbarData.message : '您有一条新的消息' }}
            </view>
            <view class="btn" :style="'width:' + (navbarDataClone.login ? '140' : '60') + 'rpx'">
                <view v-if="navbarDataClone.login" @tap="loginTim" class="relogin">重登</view>
                <mp-icon @tap.native="handleOverlayHide" class="text-delete" icon="close2" color="white" :size="28"></mp-icon>
            </view>
        </view>
    </view>
</template>

<script>
import Cache from '../../../utils/cache';
import TIM from 'tim-wx-sdk';
import { $http } from '../../../config/https.js';
import { httpconfig as httpConfig } from '../../../config/httpConfig.js';
import messageUtil from '../../../utils/message.js';
// 自定义导航栏
const app = getApp();
let timer = null;
export default {
    components: {},
    // 组件的对外属性，是属性名到属性设置的映射表
    data() {
        return {
            userData: Cache.get('userData'),
            height: 0,
            visible: false,
            message: '',
            received: false,
            overlayVisible: false,
            receivedMessage: {},
            patInfo: {},
            messagePopupBg: httpConfig.imgDomain + '/images/icon/message-popup.png',
            roomNo: '',
            share: '',
            docName: '',
            patName: '',

            navbarDataClone: {
                bottom: false,
                background: false,
                titleAlign: false,
                title: '',
                isGoHome: '',
                isGoBack: '',
                overlayVisible: '',
                login: false
            }
        };
    },
    props: {
        /*
			navbarData所包含的参数
			isGoHome 是否显示返回首页的图标
			isGoBack 是否显示返回上一页的图标
			title 当前界面的标题
			isMonitorCalls 是否需要监听医生来电提醒 默认不传则监听，传 noMonitor 则不监听
		*/
        navbarData: {
            //navbarData   由父页面传递的数据，变量名字自命名
            type: Object,

            default: () => ({})
        }
    },
	created() {
		console.log('created')
	},
    mounted() {
        // 处理小程序 attached 生命周期
        this.attached();
        // 处理小程序 ready 生命周期
        this.$nextTick(() => this.ready());
    },
    // 组件的方法，包括事件响应函数和任意的自定义方法，关于事件响应函数的使用
    methods: {
        handlePageShow: function () {
            let { navbarDataClone: navbarData } = this;
            navbarData.overlayVisible = app.globalData.overlayVisible;
            this.setData({
                overlayVisible: app.globalData.overlayVisible,
                userData: Cache.get('userData'),
                navbarDataClone: navbarData
            });
            if (app.globalData.timObj) {
                if (!this.received) {
                    app.globalData.timObj.on(TIM.EVENT.MESSAGE_RECEIVED, this.onMessageReceived.bind(this));
                    this.setData({
                        received: true
                    });
                }
            }
            if (navbarData.cleanPat == 'Y') {
                Cache.remove('patientData');
            }
        },

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

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

        ready: function () {},

        // 返回上一页面
        navbackFun() {
            if (!this.navbarData) {
                uni.navigateBack({
                    fail: function (res) {
                        uni.switchTab({
                            url: '/pages/tabBar/home/home'
                        });
                    }
                });
            } else {
                if (this.navbarData.backflag != '0') {
                    uni.navigateBack({
                        fail: function (res) {
                            uni.switchTab({
                                url: '/pages/tabBar/home/home'
                            });
                        }
                    });
                }
            }
        },

        //返回到首页
        backhomeFun() {
            let { navbarDataClone: navbarData } = this;
            uni.switchTab({
                url: '/pages/tabBar/home/home'
            });
        },

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

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

        onMessageReceived(event) {
            const patientData = Cache.get('patientData');
            const userData = Cache.get('userData');
            let _this = this;
            if (event.data) {
                if (event.data[0].payload.text) {
                    try {
                        var to = event.data[0].to;
                        if (to != 'user' + userData.userID) {
                            return;
                        }
                        var messageObj = JSON.parse(event.data[0].payload.text);
                        let { navbarDataClone: navbarData } = this;
                        this.setData({
                            receivedMessage: messageObj
                        });
                        var admID = messageObj.admID;
                        _this.getPatInfo(admID);
                        var type = messageObj.type;
                        if (type == 'M' && navbarData.imMessage == false) {
                            setTimeout(() => {
                                app.globalData.overlayVisible = false;
                            }, 500);
                        } else {
                            if (type != 'I') {
                                _this.handleOverlayShow();
                            }
                        }
                        switch (type) {
                            case 'A':
                                navbarData.message = '患者' + messageObj.patName + '预约了您';
                                break;
                            case 'C':
                                navbarData.message = '患者' + messageObj.patName + '发起了退费';
                                break;
                            case 'M':
                                break;
                            case 'I':
                                this.setData({
                                    visible: true,
                                    overlayVisible: false,
                                    docName: messageObj.userName,
                                    patName: messageObj.invitePatName,
                                    roomNo: messageObj.roomNo
                                });
                                break;
                        }
                    } catch {
                        console.log('CatchClause');
                        console.log('CatchClause');
                    }
                }
            }
        },

        /**
         * 接收到消息后查询发送消息的患者信息
         *
         * */
        getPatInfo: function (admID) {
            const userData = Cache.get('userData');
            let params = {
                params: [
                    {
                        admID: admID,
                        hospID: userData.hospID,
                        locID: userData.locID,
                        userID: userData.userID
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03100011',
                data: params,
                success: function (res) {
                    if (res.errorCode == '0') {
                        if (res.result.data.length > 0) {
                            this.setData({
                                patInfo: res.result.data[0]
                            });
                        }
                    }
                }
            });
        },

        // 跳转至我的就诊
        goMyConsultation() {
            let _this = this;
            let { receivedMessage, patInfo } = this;
            let patientData = Cache.get('patientData');
            if (patientData && patientData.admID != patInfo.admID) {
                uni.showModal({
                    title: '提示',
                    content: '是否确认切换就诊?如正在录医嘱或写病历，请勿切换',
                    success: function (res) {
                        if (res.confirm) {
                            uni.setStorage({
                                key: 'patientData',
                                data: patInfo,
                                success: function () {
                                    _this.handleOverlayHide();
                                    if (receivedMessage.type == 'M') {
                                        let admType = '';
                                        if (patInfo.resourceTypeCode == 'VIDEO') {
                                            admType = 'video';
                                        } else {
                                            admType = 'graphic';
                                        }
                                        uni.navigateTo({
                                            url: '/pages/myConsultRoom/page/treatment/treatment?admtype=' + admType
                                        });
                                    } else {
                                        uni.navigateTo({
                                            url: '/pages/myConsultRoom/page/graphicDateil/graphicDateil'
                                        });
                                    }
                                }
                            });
                        } else {
                        }
                    }
                });
            } else {
                uni.setStorage({
                    key: 'patientData',
                    data: patInfo,
                    success: function () {
                        _this.handleOverlayHide();
                        if (receivedMessage.type == 'M') {
                            let admType = '';
                            if (patInfo.resourceTypeCode == 'VIDEO') {
                                admType = 'video';
                            } else {
                                admType = 'graphic';
                            }
                            uni.navigateTo({
                                url: '/pages/myConsultRoom/page/treatment/treatment?admtype=' + admType
                            });
                        } else {
                            uni.navigateTo({
                                url: '/pages/myConsultRoom/page/graphicDateil/graphicDateil'
                            });
                        }
                    }
                });
            }
        },

        // 显示遮罩层
        handleOverlayShow() {
            app.globalData.overlayVisible = true;
            let { navbarDataClone: navbarData } = this;
            navbarData.overlayVisible = true;
            this.setData({
                overlayVisible: true,
                navbarDataClone: navbarData
            });
        },

        // 关闭遮罩层
        handleOverlayHide(event) {
            app.globalData.overlayVisible = false;
            let { navbarDataClone: navbarData } = this;
            navbarData.overlayVisible = false;
            this.setData({
                overlayVisible: false,
                navbarDataClone: navbarData
            });
        },

        loginTim: function () {
            let { navbarDataClone: navbarData } = this;
            navbarData.overlayVisible = false;
            navbarData.login = false;
            navbarData.message = '';
            this.setData({
                navbarDataClone: navbarData
            });
            messageUtil.loginTim();
        },

        seeADoctorImmediately: function () {
            if (!this.ifOnLine()) {
                return;
            }
            let path = '/pages/myConsultRoom/page/trtcRoom/trtcRoom';
            let roomNo = this.roomNo;
            messageUtil.allowToJoin(path, roomNo, 'Y');
        },

        /**
         * 判断是否在线
         */
        ifOnLine: function () {
            let TIMInfo = Cache.get('TIMInfo');
            let { navbarDataClone: navbarData } = this;
            if (TIMInfo.loginStatus == 'N') {
                navbarData.overlayVisible = true;
                navbarData.message = '您处于离线状态，请先登录';
                navbarData.login = true;
                this.setData({
                    navbarDataClone: navbarData
                });
                return false;
            } else {
                return true;
            }
        }
    },
    // 组件生命周期函数-在组件实例被从页面节点树移除时执行)
    destroyed: function () {
        clearInterval(timer); // 清除定时器
    },
    created: function () {},
    watch: {
        navbarData: {
            handler: function (newVal, oldVal) {
                this.navbarDataClone = this.clone(this.navbarData);
                console.log('触发了：observer', newVal, oldVal);
                const newMonitor = newVal && newVal.isMonitorCalls;
                const oldMonitor = oldVal && oldVal.isMonitorCalls;
                if (JSON.stringify(newMonitor) !== JSON.stringify(oldMonitor)) {
                    this.setData(
                        {
                            navbarDataClone: newVal
                        },
                        () => {}
                    );
                }
            },

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

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

.weui-icon {
    margin-top: 0rpx;
}

/* 标题要居中 */

.nav-title {
    position: absolute;
    text-align: center;
    max-width: 600rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    width: 100%;
    font-size: 37rpx;
    font-family: PingFang SC;
    font-weight: bold;
    color: rgba(255, 255, 255, 1);
}

.nav-capsule {
    display: flex;
    width: 140rpx;
    justify-content: space-between;
    position: absolute;
    left: 30rpx;
    top: 0;
    right: 0;
    bottom: 0;
    overflow: hidden;
}

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

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

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

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

.new-message .new-message-text {
    display: flex;
    align-items: center;
    width: calc(100% - 160rpx);
}

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

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

.relogin {
    border-radius: 50%;
    background: #1890ff;
    color: #fff;
    width: 70rpx;
    height: 70rpx;
    line-height: 70rpx;
    text-align: center;
    font-size: 26rpx;
    margin-top: 15rpx;
}

.btn {
    width: 160rpx;
    display: flex;
    justify-content: space-between;
}

/* 弹窗 */

.nav-wrap-modal .nav-wrap-modal-main {
    z-index: 9999;
    width: 100%;
    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: 32rpx;
    line-height: 48rpx;
}

.nav-wrap-modal .docName {
    font-size: 36rpx;
    color: #f00;
}

.nav-wrap-modal .patName {
    font-size: 36rpx;
    color: #1890ff;
}

.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;
}
</style>
