<template>
    <nav-bar :navbar-data="navbarData" @scrolltoupper="scrolltoupper" />
    <view class="message" :style="{ paddingTop: height +'px', height: '100vh', boxSizing: 'border-box'}">
        <scroll-view class="message-scroll" scroll-y="true" scroll-with-animation
            scroll-into-view="scrollSta" 
			@scrolltolower="scrolltolower" 
			@scrolltoupper="scrolltoupper"
            @scroll="handleScroll">
            <view class="message-list-intro" v-for="(item, index) in messageList" :key="index" @tap="handleGoBack" :data-page="item">
                <view class="message-list-intro-up">
                    <view class="message-list-intro-tip">
                        <view class="message-list-intro-name">{{ titleTip }}</view>
                        <view class="message-tip" v-if="item.statusCode !== 'R'"></view>
                    </view>
                    <view>
                        <text class="message-list-intro-date">{{ item.dateTime }}</text>
                    </view>
                </view>
                <view class="message-list-intro-down">预约医生 [{{ item.sendUserName }}] 预约时间[2020-12-13 10:00-12:00]</view>
            </view>
			<loadmore :status="loadMoreStatus" fontSize="24" iconColor="#1890FF" loadingColor="#1890FF" :line="true" />
        </scroll-view>
        <!-- <van-divider contentPosition="center">数据已全部加载</van-divider> -->
    </view>
</template>

<script>
import $http from "@/utils/https";
import Util from '@/utils/utils';
import httpConfig from '@/utils/httpConfig';
import NavBar from '@/components/navBar/index';
import VanDivider from '@/components/divider/index';
import Loadmore from '@/components/loadmore/loadmore';
const app = getApp()
export default {
    components: {
        'nav-bar': NavBar,
        'van-divider': VanDivider,
		'loadmore': Loadmore
    },
    data() {
        return {
            imgHost: httpConfig && httpConfig.imgHost,
            userData: {},
            messageList: [],
            height: app.globalData.height,
            navbarData: {
                isGoHome: true,
                isGoBack: true,
                title: "消息",
                isMonitorNewMessage: 'message'
            },
            currentPage: 1,
            unShowMesNum: 0,
            scrollSta: "", ///滚动条位置
			
            scrollShow: true, ///默认提示信息为数据加载成功
            visible: false,
            treeSelectData: [],
            total: 0,
            scrollHeight: 0,
            kefuLogo: httpConfig.imgHost + "/images/icon/kefu-logo.png",
            messageTypeCode: '',
            titleTip: '',
			loadMoreStatus: 'loadmore',
        }
    },
    onShow: function () {
        // 获取当前小程序的页面栈
        let pages = getCurrentPages();
        // 数组中索引最大的页面--当前页面
        let currentPage = pages[pages.length - 1];
        // 打印出当前页面中的 options
        console.log('currentPage.options === ', currentPage.options) //正常打印出 options 值
        if (currentPage.options && currentPage.options.messageTypeCode) {
            this.setData({
                messageTypeCode: currentPage.options.messageTypeCode
            }, () => {
                let navObj = this.navbarData
                let {
                    messageTypeCode
                } = this
                if (messageTypeCode == '2002') {
                    navObj.title = "视频问诊预约"
                    this.setData({
                        navbarData: navObj,
                        titleTip: "视频问诊预约成功"
                    })
                } else if (messageTypeCode == '2001') {
                    navObj.title = "图文问诊预约"
                    this.setData({
                        navbarData: navObj,
                        titleTip: "图文问诊预约成功"
                    })
                } else {
                    navObj.title = "待评价"
                    this.setData({
                        navbarData: navObj,
                        titleTip: "待评价订单"
                    })
                }
                this.upDateUserData();
            })
        }
    },
    methods: {
        //获取消息列表
        getMessageList: Util.debounce(function (page, type, lastMsg) {
			const { unShowMesNum, loadMoreStatus } = this;
			if (unShowMesNum == 0 && loadMoreStatus != 'loadmore') {
			    this.setData({
			        loadMoreStatus: 'nomore'
			    });
			    return;
			} else {
			    if (page !== 'init') {
			        this.setData({
			            loadMoreStatus: 'loading'
			        });
			    }
			}
            let data = {
                params: [{
                    receiveUser: this.userData.hisPatID,
                    receiveTypeCode: "P",
                    hospCode: this.$cache.get('userData').hisHospID,
                    messageTypeCode: this.messageTypeCode
                }],
                pagination: [{
                    pageSize: 10,
                    currentPage: page === 'init' ? 1 : this.currentPage
                }]
            }
            $http.post("urlS", this, {
                namespace: "Y",
                code: "03100201",
                data: data,
                namespace: "Y",
                success: function (res) {
                    this.setData({
                        scrollShow: true
                    }, () => {
                        if (+res.errorCode === 0) {
                            if (type === "toupper") {
                                this.processingMessageData(res.result, res.unreadNmber, lastMsg);
                            } else {
                                let messageList = type === "onShow" ? res.result : this.messageList.concat(res.result);
                                this.setData({
                                    messageList,
                                    unShowMesNum: res.remainingQty,
                                    total: res.unreadNmber,
                                    graphicUnread: res.unreadObj ? res.unreadObj.graphicUnread : '',
                                    videoUnread: res.unreadObj ? res.unreadObj.videoUnread : '',
                                    evaluateUnread: res.unreadObj ? res.unreadObj.evaluateUnread : '',
									loadMoreStatus: !res.remainingQty ? 'nomore' : 'loadmore'
                                })
                            }
                        } else {
                            this.setData({
                                messageList: []
                            })
                        }
                    })
                }
            })
        }),

        // 滚动条到顶部事件
        scrolltoupper() {
            let scrollSta = this.messageList && this.messageList.length > 0 ? 'm' + (this.messageList[0].ID) : '';
            this.getMessageList('init', "toupper", scrollSta)
        },

        // 滚动条到底部事件
        scrolltolower() {
            if (this.unShowMesNum > 0) {
                let currentPage = ++this.currentPage;
                let scrollSta = this.messageList && this.messageList.length > 0 ? 'm' + (this.messageList[this.messageList.length - 1].ID) : '';
                this.setData({
                    scrollSta,
                    scrollShow: false,
                    currentPage,
					loadmore: 'loading'
                }, () => {
                    this.getMessageList();
                })
            }
        },

        // 更新userData数据
        upDateUserData() {
            let newUserData = this.$cache.get('userData');
            this.setData({
                userData: newUserData,
                currentPage: 1,
            }, () => {
                this.getMessageList("init", "onShow");
            });
        },

        onChange(event) {
            const {
                picker,
                value,
                index
            } = event.detail;
            console.log(picker, value, index)
        },

        onClickShow() {
            this.setData({
                visible: true
            });
        },

        onClose() {
            this.setData({
                visible: false
            });
        },

        // 获取当前滚动高度
        handleScroll: function (event) {
            let {
                scrollTop
            } = event.detail
            this.setData({
                scrollHeight: scrollTop
            })
        },

        // 上拉消息查看是否有新消息
        processingMessageData(data, num, lastMsg) {
            if (num >= this.total) {
                let concatArr = data.concat(this.messageList);
                console.log(concatArr)
                let res = [];
                for (var i = 0, arrayLen = concatArr.length; i < arrayLen; i++) {
                    for (var j = 0, resLen = res.length; j < resLen; j++) {
                        if (concatArr[i].ID === res[j].ID) {
                            break;
                        }
                    }
                    if (j === resLen) {
                        res.push(concatArr[i])
                    }
                }
                this.setData({
                    messageList: res,
                    total: num
                }, () => {
                    if (this.scrollHeight > 80) {
                        this.setData({
                            scrollSta: lastMsg
                        })
                    }
                })
            }
        },

        ///修改消息状态并跳转
        changeStatus(e) {
            console.log(e)
            let item = e.currentTarget.dataset.page;
            let url = e.currentTarget.dataset.url;
            let data = {
                params: [{
                    data: [item.ID],
                    userID: "P",
                    statusID: '2'
                }]
            }
            $http.post("urlS", this, {
                namespace: "Y",
                code: "03100098",
                data: data,
                namespace: "Y",
                success: function (res) {
                    if (+res.errorCode === 0) {
                        if (item.eventCode === '2004') {
                            uni.switchTab({
                                url: '/pages/tabBar/order/order',
                            })
                            return;
                        } else if (url !== "") {
                            uni.navigateTo({
                                url: url,
                            })
                        }
                    } else {
                        console.log(res.errorMessage)
                    }
                }
            })
        },


        ///修改消息状态并跳转
        handleGoBack(event) {
            let itemData = event.currentTarget.dataset.page;
            let data = {
                params: [{
                    data: [itemData.ID],
                    userID: "P",
                    statusID: '2'
                }]
            }
            $http.post("urlS", this, {
                namespace: "Y",
                code: "03100098",
                data: data,
                namespace: "Y",
                success: function (res) {
                    if (+res.errorCode === 0) {
                        if (itemData.jumpPages.indexOf("tabBar") !== -1) {
                            uni.switchTab({
                                url: itemData.jumpPages.replace('../..', '/pages') //itemData.jumpPages
                            })
                        } else {
                            uni.navigateTo({
                                url: itemData.jumpPages.replace('../..', '/pages') //itemData.jumpPages
                            })
                        }
                    } else {
                        console.log(res.errorMessage)
                    }
                }
            })
        }
    },
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function (res) {
        if (res.from === 'button') {
            // 来自页面内转发按钮
            console.log(res.target)
        }
    }
}
</script>

<style scoped>
.message {
    overflow: auto;
    box-sizing: border-box;
}

.titel-img .van-icon__image {
    width: 108rpx !important;
    height: 84rpx !important;
}

.titel-img .van-info {
    left: 90rpx;
    transform: none !important;
    font-size: 20rpx !important;
    min-width: 28rpx !important;
    height: 28rpx !important;
    padding: 16rpx !important;
    align-items: center;
    display: flex;
    justify-content: center;
}

.message-title {
	width: 100%;
}

.message-title-img {
    margin-left: 35rpx;
    margin: 0 25rpx;
    width: 200rpx;
}

.message-list {
    background: #FFFFFF;
    margin-top: 20rpx;
}

.message-list-per {
    padding: 0 30rpx;
    display: flex;
    align-items: center;
    border-bottom: 1rpx solid #E5E5E5;
}

.per-img .van-icon__image {
    width: 80rpx !important;
    height: 80rpx !important;
    border-radius: 50%;
}

.per-img .van-info {
    left: 55rpx;
    top: -7rpx;
    transform: none !important;
    font-size: 20rpx !important;
    min-width: 28rpx !important;
    height: 28rpx !important;
    padding: 16rpx !important;
    align-items: center;
    display: flex;
    justify-content: center;
}

.pay-img .van-icon__image {
    width: 80rpx !important;
    height: 80rpx !important;
    border-radius: 50%;
}

.pay-img .van-info {
    left: 60rpx;
    transform: none !important;
    padding: 8rpx !important;
}

.message-list-intro {
	margin: 30rpx;
    padding: 30rpx;
    background: #FFFFFF;
    border-radius: 8px;
}

.message-list-intro-name {
    font-size: 30rpx;
    font-weight: 500;
    color: #333333;
    line-height: 42rpx;
}

.message-list-intro-up {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8rpx;
}

.message-list-intro-date {
    font-size: 24rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    line-height: 34rpx;
}

.message-list-intro-down {
    font-size: 26rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    line-height: 36rpx;
    letter-spacing: 2rpx;
    display: -webkit-box;
    overflow: hidden;
    text-overflow: ellipsis;
    word-break: break-all;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
}

.image-css {
    width: 80rpx;
    height: 80rpx;
}

.image-dot {
    width: 16rpx;
    min-width: 0;
    height: 16rpx;
    background-color: #F5222D;
    border-radius: 100%;
    margin-left: 66rpx;
}

.image-dot-doc {
    position: absolute;
    top: 36rpx;
    right: 40rpx;
    box-sizing: border-box;
    white-space: nowrap;
    text-align: center;
    -webkit-transform: translate(50%, -50%);
    transform: translate(50%, -50%);
    -webkit-transform-origin: 100%;
    transform-origin: 100%;
    min-width: 16px;
    min-width: var(--info-size, 16px);
    padding: 0 3px;
    padding: var(--info-padding, 0 3px);
    color: #fff;
    color: var(--info-color, #fff);
    font-weight: 500;
    font-weight: var(--info-font-weight, 500);
    font-family: PingFang SC, Helvetica Neue, Arial, sans-serif;
    font-family: var(--info-font-family, PingFang SC, Helvetica Neue, Arial, sans-serif);
    line-height: 14px;
    line-height: calc(var(--info-size, 16px) - var(--info-border-width, 1px)*2);
    background-color: #ee0a24;
    background-color: var(--info-background-color, #ee0a24);
    border: 1px solid #fff;
    border: var(--info-border-width, 1px) solid var(--white, #fff);
    border-radius: 16px;
    border-radius: var(--info-size, 16px);
    font-size: 20rpx !important;
}

.message-list-intro2 {
    padding: 30rpx;
    box-sizing: border-box;
    border-bottom: 1rpx solid #E5E5E5;
}

.message-list-intro-down2 {
    font-size: 26rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    line-height: 45rpx;

}

.message-tip {
    width: 16rpx;
    height: 16rpx;
    background: #FB3349;
    border: 2rpx solid #FFFFFF;
    border-radius: 50%;
    margin-left: 10rpx;
}

.message-list-intro-tip {
    display: flex;
    justify-content: center;
    align-items: center;
}

.mes-show {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #FFFFFF;
    padding: 20rpx;
    border-bottom: 1px solid #eeeeee;
}

.mes-icon {
    display: flex;
    justify-content: left;
    align-items: center;
}

.mes-tip {
    display: flex;
    justify-content: right;
    align-items: center;
}

.mes-text {
    margin-left: 30rpx;
    font-size: 32rpx;
    font-weight: 600;
    margin-bottom: 10rpx;
}

.image-dot-tip {
    box-sizing: border-box;
    white-space: nowrap;
    text-align: center;
    min-width: 32rpx;
    padding: 4rpx 10rpx;
    color: #fff;
    line-height: 28rpx;
    background-color: #f33f0e;
    border: 1px solid #fff;
    border-radius: 32rpx;
    font-size: 26rpx;
}

.detel {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f33f0e;
    padding: 0 19rpx;
    color: #ffffff;
}</style>