<template>
    <view>
        <!-- pages/components/messageCenter/messageCenter.wxml -->
        <view
            v-if="messageTypeShow != 'false'"
            :data-item="item"
            :data-index="index"
            @tap="checkMessageType"
            class="messTypeList"
            v-for="(item, index) in messageType"
            :key="index"
        >
            <button :class="index == messageTypeIndex ? 'messageType checkReson' : 'messageType'">{{ item.messageTypeDesc }}</button>

            <mp-badge v-if="item.qty != '' && item.qty != 0" class="notRead" :content="item.qty"></mp-badge>
        </view>

        <view :class="messageTypeShow != 'false' ? 'messageview' : 'messageview1'">
            <scroll-view class="scroll-view" :scroll-y="true" @scrolltolower="scrollLower" lower-threshold="30">
                <view class="messageContent" v-if="arrayMessage.length > 0">
                    <view class="row textLeft homeMessageBox" :data-item="item" @tap="clickMessage" v-for="(item, index) in arrayMessage" :key="index">
                        <view class="col-2 textCenter iconImg">
                            <image :src="item.sendUser == 'KF001' ? imgDomain + '/images/icon/doctor/helper.png' : domain + item.patImg" class="patImage"></image>
                            <mp-badge v-if="item.eventCode == '2009' && item.unReadMsg != '0'" :content="item.unReadMsg" style="position: absolute; top: -0.2em; right: -0.2em" />
                            <mp-badge v-if="item.eventCode != '2009' && item.statusCode == 'U'" style="position: absolute; top: -0.2em; right: 0.2em" />
                        </view>

                        <view class="col-10 patInfo">
                            <view class="row patientDetail">
                                <view class="patientInfo1" v-if="item.sendUser != 'KF001'">
                                    <text class="text">{{ item.patName }}</text>
                                    <text class="text">{{ item.patNo }}</text>
                                    <text class="text textEnd">{{ item.patAge }}</text>
                                </view>
                                <view class="patientInfo1" v-else>客服消息</view>
                            </view>
                            <view class="message">
                                <text class="content">{{ item.consultText || item.eventDesc }}</text>
                                <text class="textRight">{{ item.updateDate }} {{ item.updateTime }}</text>
                                <!-- <text wx:if="{{!statusCode}}" class="readStatus {{item.statusCode}}">{{item.statusDesc}}</text> -->
                            </view>
                        </view>
                    </view>
                </view>
                <view v-else class="no-data">
                    <image class="none" :src="domain + '/images/icon/doctor/none.png'"></image>
                    <view class="none-text">暂无消息</view>
                </view>
                <van-toast id="van-toast" />
            </scroll-view>
        </view>
    </view>
</template>

<script>
import Cache from '../../../utils/cache';
import notice from '@/pages/components/notice/notice';
// pages/components/messageCenter/messageCenter.js
import { $http } from '../../../config/https.js';
import TIM from 'tim-wx-sdk';
import Toast from '../../../utils/toast';
const app = getApp();
import { httpconfig as httpConfig } from '../../../config/httpConfig.js';
export default {
    components: {
        notice
    },
    data() {
        return {
            arrayMessage: [],
            received: false,
            pageSize: 10,
            // 条数
            currentPage: 1,
            // 页数
            hasMoreData: false,
            //判断是是否加载完毕
            messageType: [],
            messageTypeIndex: 0,
            tyepCode: '',
            domain: httpConfig.domain,
            imgDomain: httpConfig.imgDomain
        };
    },
    /**
     * 可以使用全局样式
     */
    options: {
        addGlobalClass: true
    },
    /**
     * 组件的属性列表
     */
    props: {
        statusCode: {
            type: String,
            default: ''
        },
        messageTypeShow: String
    },
    mounted() {
        // 处理小程序 attached 生命周期
        this.attached();
        // 处理小程序 ready 生命周期
        this.$nextTick(() => this.ready());
    },
    /**
     * 组件的方法列表
     */
    methods: {
        handlePageShow: function () {
            if (!this.received && app.globalData.timObj) {
                app.globalData.timObj.on(TIM.EVENT.MESSAGE_RECEIVED, this.onMessageReceived.bind(this));
                this.setData({
                    received: true
                });
            }
            this.setData({
                currentPage: 1
            });
            this.getMessageList();
            this.getMessageTypeList();
        },

        handlePageHide: function () {},
        ready: function () {},
        attached: function () {},

        checkMessageType: function (e) {
            var index = e.currentTarget.dataset.index;
            var typeCode = this.messageType[index].messageTypeCode;
            if (index != this.messageTypeIndex) {
                this.setData(
                    {
                        messageTypeIndex: index,
                        currentPage: 1,
                        tyepCode: typeCode
                    },
                    () => {
                        this.getMessageList();
                    }
                );
            }
        },

        getMessageTypeList: function (e) {
            let userData = Cache.get('userData');
            let data = {
                params: [
                    {
                        receiveUser: userData.userID,
                        receiveTypeCode: 'U',
                        appPropCode: 'DocMsgTips'
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03100112',
                data: data,
                success: function (res) {
                    console.log(res);
                    if (res.errorCode == '0') {
                        this.setData({
                            messageType: res.result.data
                        });
                    }
                }
            });
        },

        /**屏幕下滑至最底部 */
        scrollLower: function () {
            let { hasMoreData, currentPage } = this;
            if (hasMoreData) {
                Toast.loading({
                    mask: true,
                    message: '加载中...'
                });
                this.setData(
                    {
                        currentPage: currentPage + 1
                    },
                    () => {
                        this.getMessageList(true); // 传参标识 表示是滚动加载
                    }
                );
            } else {
                uni.showToast({
                    title: '没有更多数据啦',
                    icon: 'none'
                });
            }
        },

        onMessageReceived(event) {
            if (event.data) {
                if (event.data[0].payload.text) {
                    try {
                        var messageObj = JSON.parse(event.data[0].payload.text);
                        if (messageObj.type != 'V' && messageObj.type != 'I') {
                            this.setData(
                                {
                                    messageTypeIndex: index,
                                    currentPage: 1,
                                    tyepCode: typeCode,
                                    arrayMessage: []
                                },
                                () => {
                                    this.getMessageList();
                                }
                            );
                        }
                    } catch {
                        console.log('CatchClause');
                        console.log('CatchClause');
                    }
                }
            }
        },

        /**
         * 获取消息列表
         */
        getMessageList: function (searchType) {
            let that = this;
            let { currentPage, arrayMessage, pageSize } = this;
            let userData = Cache.get('userData');
            if (userData) {
                let data = {
                    params: [
                        {
                            receiveUser: userData.userID,
                            receiveTypeCode: 'U',
                            statusCode: this.statusCode,
                            messageTypeCode: this.tyepCode
                        }
                    ],
                    pagination: [
                        //页码信息
                        {
                            pageSize: pageSize,
                            currentPage: currentPage
                        }
                    ]
                };
                $http.post('urlDeault', this, {
                    code: '03100097',
                    data: data,
                    success: function (res) {
                        console.log(res);
                        if (res.errorCode == '0') {
                            let newHasMoreData = false;
                            if (res.result.length === pageSize) {
                                newHasMoreData = true;
                            }
                            let newVideoAdmList = [];
                            if (searchType) {
                                newVideoAdmList = arrayMessage.concat(res.result);
                            } else {
                                newVideoAdmList = res.result;
                            }
                            this.setData({
                                hasMoreData: newHasMoreData,
                                arrayMessage: newVideoAdmList
                            });
                            if (res.unreadNmber) {
                                let object = {};
                                object.index = 1;
                                object.text = res.unreadNmber + '';
                                uni.setTabBarBadge(object);
                            } else {
                                let object = {};
                                object.index = 1;
                                uni.removeTabBarBadge(object);
                            }
                        }
                    }
                });
            }
        },

        /**
         * 点击消息
         */
        clickMessage: function (event) {
            const { item } = event.currentTarget.dataset;
            if (item.sendUser == 'KF001') {
                uni.navigateTo({
                    url: '/pages/myConsultRoom/page/treatment/treatment?help=true',
                    success: function (res) {}
                });
            } else {
                this.getPatInfo(item);
            }
            if (item.statusCode == 'U') {
                this.readMessage(item);
            }
        },

        /**
         * 消息读取
         */
        readMessage: function (item) {
            const userData = Cache.get('userData');
            let params = {
                params: [
                    {
                        data: [item.ID],
                        userID: userData.userID,
                        statusID: '',
                        statusCode: 'R'
                    }
                ]
            };
            $http.post('urlDeault', this, {
                code: '03100098',
                data: params,
                success: function (res) {}
            });
        },

        /**
         * 接收到消息后查询发送消息的患者信息
         *
         * */
        getPatInfo: function (item) {
            const userData = Cache.get('userData');
            let params = {
                params: [
                    {
                        admID: item.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) {
                            let patientData = res.result.data[0];
                            uni.setStorage({
                                key: 'patientData',
                                data: res.result.data[0],
                                success: function () {
                                    if (item.eventCode == '2007') {
                                        uni.navigateTo({
                                            url: '/pages/entryWrite/page/Entry/prescription/prescAuditDetail/prescAuditDetail?prescNo=' + item.content
                                        });
                                    } else if (item.eventCode == '2008') {
                                        uni.navigateTo({
                                            url: '/pages/entryWrite/page/Entry/Entry?select=2&addText=添加医嘱'
                                        });
                                    } else if (item.eventCode == '2009') {
                                        let admType = 'video';
                                        if ((patientData.resourceTypeCode = 'IMAGE')) {
                                            admType = 'graphic';
                                        }
                                        uni.navigateTo({
                                            url: '/pages/myConsultRoom/page/treatment/treatment?admtype=' + admType
                                        });
                                    } else {
                                        uni.navigateTo({
                                            url: '/pages/myConsultRoom/page/graphicDateil/graphicDateil'
                                        });
                                    }
                                }
                            });
                        }
                    }
                }
            });
        }
    },
    created: function () {}
};
</script>
<style>
/* @import '../../tabBar/home/home.css'; */

.scroll-view {
    height: calc(100% - 30rpx);
    padding-bottom: 20rpx;
}

.no-data {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    padding-top: 60rpx;
}

.no-data .none {
    width: 408rpx;
    height: 359rpx;
}

.no-data .none-text {
    text-align: center;
    margin-top: 20rpx;
}

.messageContent {
    width: 100%;
}

.msgItem {
    height: 200rpx;
    width: 100%;
}

.left {
    width: 20%;
    float: left;
}

.right {
    width: 80%;
    float: left;
}

.patInfo {
    height: calc(100% - 20rpx);
    width: calc(83% - 22px);
    padding: 10rpx 20rpx;
}

.patientInfo1 {
    white-space: nowrap;
}

.patientDetail {
    height: 90rpx;
    width: 100%;
    line-height: 90rpx;
}

.message {
    height: 90rpx;
    width: 100%;
    line-height: 90rpx;
    float: left;
    border-bottom: 0px;
}

.readStatus {
    background: #ff0;
    float: right;
    margin-left: 20rpx;
    padding: 0 10rpx;
}

.U {
    background: #ff0;
}

.R {
    background: #f4f2f2;
}

.message .content {
    height: 100%;
    width: 60%;
    padding: 0px 15rpx;
    border-bottom: 0px;
    font-size: 0.95rem;
    border-right: 0px solid #ccc;
}

.text {
    font-size: 0.9rem;
    padding: 0px 15rpx;
    border-right: 1px solid #ccc;
}

.textEnd {
    border-right: 0px solid #ccc;
}

.textRight {
    float: right;
    font-size: 0.9rem;
    border-right: 0px solid #ccc;
}

.iconImg {
    height: 200rpx;
}

.patImage {
    width: 100rpx;
    height: 100rpx;
    padding: 50rpx 0;
}

.messageview {
    overflow: auto;
    height: calc(100% - 70px);
}

.messageview1 {
    overflow: auto;
}

.messageType {
    width: auto !important;
    height: 60rpx;
    font-size: 28rpx;
    color: #999999;
    background-color: white;
    border-radius: 20px;
    padding: 1rpx 20rpx 50rpx 20rpx !important;
    font-weight: 500;
    margin-left: 10rpx;
    float: left;
    margin-top: 10rpx;
    line-height: 2;
    box-shadow: -1px 0 0 #e9e9e9, 0 -1px 0 #e9e9e9, 0 1px 0 #e9e9e9, 1px 0 0 #e9e9e9;
}

.messageType::after,
.messageType::before {
    border-radius: 20px;
}

.checkReson {
    background-color: dodgerblue;
    color: #fff;
}

.notRead {
    width: 38rpx;
    float: left;
    position: relative;
    right: 0.8em;
    margin-left: -22rpx;
    margin-top: -7rpx;
}

.messTypeList {
    width: auto;
    height: auto;
    margin-left: 10px;
}
</style>
