<template>
    <view class="message-list-page">
        <!-- 顶部导航栏 -->
        <view class="nav-header">
            <view class="nav-back-btn" @tap="onBack">
                <text class="back-text">返回</text>
            </view>
            <text class="nav-title">消息</text>
            <view class="nav-placeholder"></view>
        </view>

        <!-- 时间段查询 -->
        <view class="filter-bar">
            <view class="filter-row">
                <picker class="filter-date-picker" mode="date" :value="startDate" @change="onStartDateChange">
                    <view class="date-input">
                        <text class="date-text" :class="{ 'date-placeholder': !startDate }">{{ startDate || '开始日期' }}</text>
                        <view class="date-icon"></view>
                    </view>
                </picker>
                <text class="filter-to">至</text>
                <picker class="filter-date-picker" mode="date" :value="endDate" @change="onEndDateChange">
                    <view class="date-input">
                        <text class="date-text" :class="{ 'date-placeholder': !endDate }">{{ endDate || '结束日期' }}</text>
                        <view class="date-icon"></view>
                    </view>
                </picker>
                <view class="query-btn" @tap="onQuery">
                    <text class="query-btn-text">查 询</text>
                </view>
            </view>
        </view>

        <!-- 消息列表 -->
        <view class="page-content">
            <view class="message-list">
                <view
                    class="message-item"
                    v-for="(item, index) in displayList"
                    :key="index"
                    @tap="onItemTap(item)"
                >
                    <view class="avatar-circle" :class="item.avatarClass">
                        <image
                            v-if="item.avatarUrl && !item.avatarFailed"
                            class="avatar-img"
                            :src="item.avatarUrl"
                            mode="aspectFill"
                            @error="onAvatarError(index)"
                        ></image>
                        <image v-else class="avatar-img" :src="item.defaultAvatar" mode="aspectFill"></image>
                    </view>
                    <view class="message-content">
                        <view class="message-top">
                            <text class="message-name">{{ item.name }}</text>
                            <text class="message-time">{{ item.time }}</text>
                        </view>
                        <view class="message-bottom">
                            <text class="message-preview" :class="{ 'message-preview-bold': item.unread > 0 }">
                                {{ item.preview }}
                            </text>
                            <view v-if="item.unread > 0" class="unread-badge">
                                <text class="unread-text">{{ item.unread }}</text>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <view class="empty-tip" v-if="loading">
                <text class="empty-tip-text">加载中...</text>
            </view>
            <view class="empty-tip" v-else-if="displayList.length === 0">
                <text class="empty-tip-text">该时间段暂无消息</text>
            </view>
        </view>
    </view>
</template>

<script>
import { $http } from '../../../config/https.js';
import httpConfig from '../../../config/httpConfig.js';
import Cache from '../../../utils/cache.js';

// 接口编码
const API_CODE = {
    chatList: '03100110' // 查询聊天列表
};
// 默认头像（按性别）
const DEFAULT_AVATAR = {
    male: httpConfig.imgDomain + '/images/icon/gender-male.png',
    female: httpConfig.imgDomain + '/images/icon/gender-female.png',
    unknown: httpConfig.imgDomain + '/images/icon/doctor/helper.png'
};

export default {
    data() {
        return {
            // 消息列表（接口返回）
            messageList: [],
            // 加载状态
            loading: false,
            // 查询条件
            startDate: '',
            endDate: ''
        };
    },
    computed: {
        displayList() {
            return this.messageList;
        }
    },
    onLoad() {
        // 默认查询近 30 天
        const end = new Date();
        const start = new Date();
        start.setDate(start.getDate() - 30);
        this.endDate = this.formatDate(end);
        this.startDate = this.formatDate(start);
        this.loadMessageList();
    },
    methods: {
        // 格式化日期 YYYY-MM-DD
        formatDate(date) {
            const y = date.getFullYear();
            const m = String(date.getMonth() + 1).padStart(2, '0');
            const d = String(date.getDate()).padStart(2, '0');
            return `${y}-${m}-${d}`;
        },
        // 默认头像：按性别区分，未知性别用通用头像
        getDefaultAvatar(sexDesc) {
            if (sexDesc === '男') return DEFAULT_AVATAR.male;
            if (sexDesc === '女') return DEFAULT_AVATAR.female;
            return DEFAULT_AVATAR.unknown;
        },
        // 头像加载失败：切换为默认头像
        onAvatarError(index) {
            const item = this.messageList[index];
            if (!item || item.avatarFailed) return;
            item.avatarFailed = true;
        },
        // 消息预览文案：优先文本，其次按语音/视频/图片类型兜底
        getPreviewText(item) {
            if (item.consultText) return item.consultText;
            if (item.sound) return '[语音]';
            if (item.video) return '[视频]';
            if (item.picture) return '[图片]';
            return '暂无消息内容';
        },
        // 接口数据 -> 页面展示数据
        mapMessageItem(item) {
            const name = item.name || '';
            return Object.assign({}, item, {
                id: item.ID || '',
                name: name || '匿名用户',
                avatar: name ? name.substring(0, 1) : '匿',
                avatarUrl: item.personImage ? httpConfig.imgDomain + item.personImage : '',
                avatarFailed: false,
                defaultAvatar: this.getDefaultAvatar(item.sexDesc),
                avatarClass: name ? 'avatar-blue' : 'avatar-default',
                preview: this.getPreviewText(item),
                // 当天显示 HH:mm，更早显示周几/日期，为空时回退 time
                time: item.consultTime || String(item.time || '').substring(0, 5),
                unread: Number(item.noReadCount) || 0
            });
        },
        // 查询聊天列表
        loadMessageList() {
            const that = this;
            if (that.loading) return;
            that.loading = true;
            $http.post('urlDeault', this, {
                code: API_CODE.chatList,
                data: {
                    params: [
                        {
                            name: '',
                            type: '',
                            startDate: that.startDate,
                            endDate: that.endDate
                        }
                    ]
                },
                success: function (res) {
                    that.loading = false;
                    if (res.errorCode != '0') return;
                    const result = res.result || {};
                    const list = Array.isArray(result) ? result : result.data || result.list || [];
                    that.messageList = (Array.isArray(list) ? list : []).map(item => that.mapMessageItem(item));
                },
                fail: function () {
                    that.loading = false;
                }
            });
        },
        onBack() {
            uni.navigateBack();
        },
        onStartDateChange(e) {
            this.startDate = e.detail.value;
        },
        onEndDateChange(e) {
            this.endDate = e.detail.value;
        },
        onQuery() {
            if (this.startDate && this.endDate && this.startDate > this.endDate) {
                uni.showToast({ title: '开始日期不能晚于结束日期', icon: 'none' });
                return;
            }
            this.loadMessageList();
        },
        // 点击消息：缓存患者信息后进入图文问诊会话
        onItemTap(item) {
            if (!item.patID) {
                uni.showToast({ title: '该消息暂不支持查看', icon: 'none' });
                return;
            }
            const userData = Cache.get('userData') || {};
            Cache.set(
                'patientData',
                Object.assign({}, item, {
                    patID: item.patID,
                    patName: item.name,
                    patNo: item.patNo || '',
                    patSexDesc: item.sexDesc || '',
                    patAge: item.age || '',
                    admID: item.admID || '',
                    mobile: item.mobile || '',
                    hospID: item.hospID || userData.hospID || '',
                    locID: item.locID || userData.locID || ''
                })
            );
            // from=message：标记来源为消息列表，会话页据此隐藏就诊相关操作、且不请求依赖就诊ID的接口
            uni.navigateTo({
                url: '/pages/myConsultRoom/page/treatment/treatment?admtype=graphic&from=message'
            });
        }
    }
};
</script>

<style scoped>
.message-list-page {
    min-height: 100vh;
    background-color: #f5f6f8;
}

/* 顶部导航栏 */
.nav-header {
    height: 88rpx;
    background: linear-gradient(135deg, #4a9fff 0%, #2B84FF 100%);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 24rpx;
    padding-top: var(--status-bar-height, 44rpx);
}

.nav-back-btn {
    width: 120rpx;
    height: 48rpx;
    display: flex;
    align-items: center;
    justify-content: flex-start;
}

.back-text {
    font-size: 28rpx;
    color: #ffffff;
}

.nav-title {
    font-size: 34rpx;
    font-weight: 600;
    color: #ffffff;
    flex: 1;
    text-align: center;
}

.nav-placeholder {
    width: 120rpx;
    height: 48rpx;
}

/* 内容区 */
.page-content {
    padding: 20rpx 24rpx;
}

/* 查询条件栏 */
.filter-bar {
    background: #f5f6f8;
    padding: 20rpx 24rpx;
}

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

.filter-to {
    font-size: 26rpx;
    color: #1f2329;
    margin: 0 12rpx;
    flex-shrink: 0;
}

.filter-date-picker {
    flex: 1;
}

.date-input {
    height: 64rpx;
    background: #ffffff;
    border-radius: 12rpx;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 0 16rpx;
}

.date-text {
    font-size: 26rpx;
    color: #1f2329;
}

.date-placeholder {
    color: #b4b8c0;
}

.date-icon {
    width: 26rpx;
    height: 26rpx;
    border: 2rpx solid #e84747;
    border-radius: 4rpx;
    position: relative;
    flex-shrink: 0;
}

.date-icon::before {
    content: '';
    position: absolute;
    top: -7rpx;
    left: 3rpx;
    right: 3rpx;
    height: 3rpx;
    background: #e84747;
}

.date-icon::after {
    content: '17';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 14rpx;
    line-height: 1;
    color: #e84747;
}

.query-btn {
    width: 128rpx;
    height: 64rpx;
    background: #2B84FF;
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    margin-left: 16rpx;
}

.query-btn-text {
    font-size: 26rpx;
    font-weight: 500;
    color: #ffffff;
}

/* 空状态 */
.empty-tip {
    padding: 80rpx 0;
    display: flex;
    justify-content: center;
}

.empty-tip-text {
    font-size: 26rpx;
    color: #8b98a8;
}

.message-list {
    background: #ffffff;
    border-radius: 16rpx;
    overflow: hidden;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
}

.message-item {
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 28rpx 24rpx;
    border-bottom: 1rpx solid #f0f2f5;
}

.message-item:last-child {
    border-bottom: none;
}

.message-item:active {
    background-color: #f7f9fc;
}

/* 头像 */
.avatar-circle {
    width: 88rpx;
    height: 88rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20rpx;
    flex-shrink: 0;
}

.avatar-blue {
    background: #e8f1ff;
}

.avatar-default {
    background: #fff5e6;
}

.avatar-img {
    width: 88rpx;
    height: 88rpx;
    border-radius: 50%;
}

.avatar-text {
    font-size: 36rpx;
    font-weight: 600;
    color: #2B84FF;
}

.avatar-default .avatar-text {
    color: #ff8c42;
}

/* 消息内容 */
.message-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.message-top {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8rpx;
}

.message-name {
    font-size: 32rpx;
    font-weight: 600;
    color: #1f2329;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.message-time {
    font-size: 24rpx;
    color: #8b98a8;
    flex-shrink: 0;
    margin-left: 16rpx;
}

.message-bottom {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
}

.message-preview {
    flex: 1;
    font-size: 26rpx;
    color: #8b98a8;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.message-preview-bold {
    color: #4a5160;
    font-weight: 500;
}

/* 未读小红点 */
.unread-badge {
    min-width: 36rpx;
    height: 36rpx;
    padding: 0 8rpx;
    background: #ff3b30;
    border-radius: 18rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 16rpx;
    flex-shrink: 0;
}

.unread-text {
    font-size: 22rpx;
    font-weight: 600;
    color: #ffffff;
    line-height: 1;
}
</style>
