<template>
    <view class="msg-wrap">
        <!-- 顶部 tab：全部 / 未读 -->
        <!-- <view class="msg-tabs">
            <view
                v-for="(item, index) in navTab"
                :key="index"
                :class="'msg-tab ' + (currentTab == index ? 'msg-tab-active' : '')"
                @tap="switchTab"
                :data-index="index"
            >
                <text>{{ item.descripts }}</text>
            </view>
        </view> -->

        <scroll-view class="msg-scroll" :scroll-y="true">
            <view v-if="arrayMessage.length > 0" class="msg-list">
                <view class="msg-card" :data-item="item" @tap="clickMessage" v-for="(item, index) in arrayMessage" :key="index" hover-class="msg-card-hover" hover-stay-time="80">
                    <view class="msg-avatar">
                        <image :src="imgDomain + '/images/icon/doctor/helper.png'" class="msg-avatar-img"></image>
                        <view v-if="item.recordStatusCode == 'U'" class="msg-dot"></view>
                    </view>
                    <view class="msg-body">
                        <view class="msg-top">
                            <text class="msg-name">{{ item.patName }}</text>
                            <text class="msg-event">{{ item.eventDesc }}</text>
                            <text class="msg-time">{{ item.sendDate }} {{ item.sendTime }}</text>
                        </view>
                        <view class="msg-bottom">
                            <text class="msg-text">{{ item.message }}</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>
        </scroll-view>
    </view>
</template>

<script>
import Cache from '../../../utils/cache';
import notice from '@/pages/components/notice/notice';
// pages/components/messageCenter/messageCenter.js
import TIM from 'tim-wx-sdk';
import { $http } from '../../../config/https.js';
import unreadMessageUtil from '../../../utils/unreadMessage.js';
const app = getApp();
import { httpconfig as httpConfig } from '../../../config/httpConfig.js';
export default {
    components: {
        notice
    },
    data() {
        return {
            arrayMessage: [],
            received: false,
            domain: httpConfig.domain,
            imgDomain: httpConfig.imgDomain,
            navTab: [
                { id: 0, code: 'ALL', descripts: '全部' },
                { id: 1, code: 'U', descripts: '未读' }
            ],
            currentTab: 1
        };
    },
    /**
     * 可以使用全局样式
     */
    options: {
        addGlobalClass: true
    },
    /**
     * 组件的属性列表
     */
    props: {
        statusCode: {
            type: String,
            default: ''
        },
        messageTypeShow: String
    },
    mounted() {
        // 处理小程序 attached 生命周期
        this.attached();
        // 处理小程序 ready 生命周期
        this.$nextTick(() => {
            this.ready();
            // 兜底：Vue3 下 pageLifetimes $children 不可靠，handlePageShow 可能不会被调用，
            // 首次挂载时主动加载数据
            this.handlePageShow();
        });
    },
    /**
     * 组件的方法列表
     */
    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.getMessageList();
        },

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

        /** 切换 tab */
        switchTab: function (e) {
            var index = e.currentTarget.dataset.index;
            if (index == this.currentTab) return;
            this.setData(
                {
                    currentTab: index,
                    arrayMessage: []
                },
                function () {
                    this.getMessageList();
                }
            );
        },

        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.getMessageList();
                        }
                    } catch (e) {
                        console.log('onMessageReceived parse error:', e);
                    }
                }
            }
        },

        /**
         * 获取消息列表
         * 接口文档：docs/文档.md (code: 04180005)
         * 根据 tab 传 messageStatusCode：未读=U，全部=ALL
         */
        getMessageList: function () {
            let that = this;
            let userData = Cache.get('userData');
            if (!userData) return;
            var tabItem = this.navTab[this.currentTab];
            var isUnreadTab = this.currentTab == 1;
            unreadMessageUtil.fetchUnreadMessages({
                messageStatusCode: tabItem ? tabItem.code : 'U',
                pageSize: 999,
                success: function (res) {
                    that.setData({
                        arrayMessage: res.list || []
                    });
                    // 仅在"未读"tab下根据未读总数更新底栏红点
                    if (isUnreadTab) {
                        unreadMessageUtil.updateMessageRedDot(res.total || 0);
                    }
                }
            });
        },

        /**
         * 点击消息
         * 未读消息一律调 04180007 标记已读
         * eventID 为 1/2/3/21/22 时通过 03100011 获取患者数据后跳转图文问诊治疗页
         */
        clickMessage: function (e) {
            var item = e.currentTarget.dataset.item;
            if (!item) return;

            // 未读消息标记为已读（与跳转同步进行，不阻塞）
            if (item.recordStatusCode == 'U' && item.receiveID) {
                unreadMessageUtil.markAsRead(item.receiveID);
                // 本地立即更新状态，移除小红点
                var list = this.arrayMessage;
                for (var i = 0; i < list.length; i++) {
                    if (list[i].receiveID == item.receiveID) {
                        list[i].recordStatusCode = 'R';
                        break;
                    }
                }
                this.setData({ arrayMessage: list });
            }

            // eventID 为 1/2/3/21/22 时，获取患者数据并跳转
            var allowEventIDs = ['1', '2', '3', '21', '22'];
            if (allowEventIDs.indexOf(String(item.eventID)) < 0) return;

            this.getPatInfo(item);
        },

        /**
         * 根据 admID 获取患者数据，缓存后跳转图文问诊治疗页
         * 参考首页"继续接诊"按钮逻辑
         */
        getPatInfo: function (item) {
            let userData = Cache.get('userData');
            if (!userData) return;
            $http.post(
                'urlDeault',
                this,
                {
                    code: '03100011',
                    data: {
                        params: [
                            {
                                admID: item.admID,
                                hospID: userData.hospID,
                                locID: userData.locID,
                                userID: userData.userID
                            }
                        ]
                    },
                    success: function (res) {
                        if (res.errorCode == '0' && res.result.data && res.result.data.length > 0) {
                            Cache.set('patientData', res.result.data[0]);
                            uni.navigateTo({
                                url: '/pages/myConsultRoom/page/treatment/treatment?admtype=graphic'
                            });
                        }
                    }
                },
                { error: 'Y' }
            );
        }
    },
    created: function () {}
};
</script>
<style>
.msg-wrap {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding: 80rpx 0 60rpx 0;
}

.msg-tabs {
    flex-shrink: 0;
    display: flex;
    flex-direction: row;
    align-items: center;
    background: #ffffff;
    padding: 12rpx 20rpx;
    gap: 16rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.03);
}

.msg-tab {
    flex: 1;
    height: 64rpx;
    line-height: 64rpx;
    text-align: center;
    font-size: 28rpx;
    color: #4a5160;
    background: #f4f6fa;
    border-radius: 32rpx;
    transition: all 0.2s;
}

.msg-tab-active {
    background: #1687ff;
    color: #ffffff;
    font-weight: 600;
}

.msg-scroll {
    flex: 1;
    min-height: 0;
    width: 100%;
}

.msg-list {
    padding: 16rpx 20rpx 20rpx;
}

.msg-card {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    background: #ffffff;
    border-radius: 16rpx;
    padding: 24rpx 20rpx;
    margin-bottom: 16rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}

.msg-card-hover {
    background: #f7f9fc;
}

.msg-avatar {
    position: relative;
    flex: 0 0 80rpx;
    width: 80rpx;
    height: 80rpx;
    margin-right: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.msg-avatar-img {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    background: #eef2f7;
}

.msg-dot {
    position: absolute;
    top: -2rpx;
    right: -2rpx;
    width: 16rpx;
    height: 16rpx;
    border-radius: 50%;
    background: #f54a45;
    border: 2rpx solid #ffffff;
}

.msg-body {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
}

.msg-top {
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 12rpx;
    margin-bottom: 10rpx;
}

.msg-name {
    font-size: 30rpx;
    font-weight: 600;
    color: #1f2329;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 160rpx;
}

.msg-event {
    font-size: 24rpx;
    color: #1687ff;
    background: #eaf4ff;
    padding: 2rpx 12rpx;
    border-radius: 6rpx;
    white-space: nowrap;
    flex-shrink: 0;
}

.msg-time {
    font-size: 22rpx;
    color: #b6bcc7;
    margin-left: auto;
    white-space: nowrap;
    flex-shrink: 0;
}

.msg-bottom {
    display: flex;
    flex-direction: row;
    align-items: center;
}

.msg-text {
    font-size: 26rpx;
    color: #8b98a8;
    line-height: 36rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

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

.no-data .none {
    width: 300rpx;
    height: 264rpx;
}

.no-data .none-text {
    text-align: center;
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #999;
}
</style>
