<template>
	<uni-navbar-lite :showLeft=false :show-right=false title="我的消息"></uni-navbar-lite>
	<view class="page-container">
<!-- 	<view>
		<text class="page-header"> 我的消息 </text>
	</view> -->
    <view class="list-page">
        <!-- 搜索栏 -->
        <view class="search-bar">
            <view class="search-box">
                <image class="search-icon" src="/static/images/workbench/list/1.png" mode="aspectFit"></image>
                <input class="search-input" type="text" placeholder="请输入关键字查询" v-model="keyword" @input="handleInput" @confirm="handleSearch" />
                <view v-if="keyword.length > 0" class="clear-btn" @tap="handleClear">
                    <text class="clear-btn-text">×</text>
                </view>
                <view class="search-btn" @tap="handleSearch">
                    <text class="search-btn-text">搜索</text>
                </view>
            </view>
        </view>

        <!-- 状态标签 -->
        <view class="status-tabs">
            <view 
                class="status-tab" 
                :class="{ 'active': currentStatus === '' }" 
                @tap="handleStatusChange('')"
            >
                <text class="status-tab-text" :class="{ 'active-text': currentStatus === '' }">全部</text>
            </view>
            <view 
                class="status-tab" 
                :class="{ 'active': currentStatus === 'UNREAD' }" 
                @tap="handleStatusChange('UNREAD')"
            >
                <text class="status-tab-text" :class="{ 'active-text': currentStatus === 'UNREAD' }">未读</text>
            </view>
            <view 
                class="status-tab" 
                :class="{ 'active': currentStatus === 'READ' }" 
                @tap="handleStatusChange('READ')"
            >
                <text class="status-tab-text" :class="{ 'active-text': currentStatus === 'READ' }">已读</text>
            </view>
        </view>

        <!-- 列表内容 -->
        <common-list 
            :dataList="dataList" 
            :loading="loading" 
            :refreshing="refreshing" 
            :hasMore="hasMore" 
            @refresh="handleRefresh" 
            @loadMore="loadMore"
            @itemClick="handleItemClick"
        >
            <template #default="{ item, index }">
                <view class="list-item" :class="{ 'unread': getStatus(item) === 'UNREAD' }">
                    <view class="item-container">
                        <view class="item-header">
                            <text class="item-title">{{ getMessageTitle(item) }}</text>
                            <text class="item-status" :class="'status-' + getStatus(item)">{{ getStatusText(item) }}</text>
                        </view>
                        <view class="item-content">
                            <text class="content-text">{{ getMessageContent(item) }}</text>
                        </view>
                        <view class="item-footer">
                            <text class="create-time">{{ getCreateTime(item) }}</text>
                        </view>
                    </view>
                </view>
            </template>
        </common-list>
		<custom-tabbar :current="2" />
    </view>
	</view>
</template>

<script setup lang="uts">
    import { ref, onBeforeUnmount, onMounted } from 'vue'
    import { getMessageList, markMessageAsRead } from '../../api/message/index'

    // 列表数据
    const dataList = ref<any[]>([])
    const keyword = ref<string>("")
    const currentStatus = ref<string>("")
    const page = ref<number>(1)
    const pageSize: number = 10
    const hasMore = ref<boolean>(true)
    const loading = ref<boolean>(false)
    const refreshing = ref<boolean>(false)
    const total = ref<number>(0)

    // 获取消息标题
    const getMessageTitle = (item: any | null): string => {
        if (item == null) return ''
        const jsonItem = item as UTSJSONObject
        const val = jsonItem['messageTitle']
        return val != null ? val.toString() : ''
    }

    // 获取消息内容
    const getMessageContent = (item: any | null): string => {
        if (item == null) return ''
        const jsonItem = item as UTSJSONObject
        const val = jsonItem['messageContent']
        return val != null ? val.toString() : ''
    }

    // 获取消息状态
    const getStatus = (item: any | null): string => {
        if (item == null) return ''
        const jsonItem = item as UTSJSONObject
        const val = jsonItem['status']
        return val != null ? val.toString() : ''
    }

    // 获取状态文本
    const getStatusText = (item: any | null): string => {
        const status = getStatus(item)
        switch (status) {
            case 'UNREAD': return '未读'
            case 'READ': return '已读'
            default: return status
        }
    }

    // 获取创建时间
    const getCreateTime = (item: any | null): string => {
        if (item == null) return ''
        const jsonItem = item as UTSJSONObject
        const val = jsonItem['createTime']
        return val != null ? val.toString() : ''
    }

    // 获取消息ID
    const getMessageId = (item: any | null): string => {
        if (item == null) return ''
        const jsonItem = item as UTSJSONObject
        const val = jsonItem['messageId']
        return val != null ? val.toString() : ''
    }

    // 加载列表数据
    const loadData = async (isRefresh: boolean): Promise<void> => {
        if (loading.value) {
            refreshing.value = false
            return
        }

        try {
            loading.value = true

            if (isRefresh) {
                page.value = 1
            }

            // 调用 API
            const result = await getMessageList(page.value, pageSize, keyword.value, currentStatus.value)

            // 提取响应数据
            const resultObj = result as UTSJSONObject
            const rows = resultObj['rows']
            const responseTotal = resultObj['total'] as number

            if (rows != null) {
                const newData = rows as any[]
                if (isRefresh) {
                    dataList.value = newData
                } else {
                    dataList.value = [...dataList.value, ...newData]
                }

                total.value = responseTotal
                hasMore.value = dataList.value.length < responseTotal
            } else {
                if (isRefresh) {
                    dataList.value = []
                }
                hasMore.value = false
            }

        } catch (e: any) {
            uni.showToast({
                title: e.message ?? '加载失败',
                icon: 'none'
            })
        } finally {
            loading.value = false
            setTimeout(() => {
                refreshing.value = false
            }, 100)
        }
    }

    // 下拉刷新
    const handleRefresh = async (): Promise<void> => {
        refreshing.value = true
        await loadData(true)
    }

    // 加载更多
    const loadMore = (): void => {
        if (!hasMore.value || loading.value) {
            return
        }
        page.value++
        loadData(false)
    }

    // 搜索
    const handleSearch = (): void => {
        page.value = 1
        loadData(true)
    }

    // 输入时搜索
    const handleInput = (): void => {
        page.value = 1
        loadData(true)
    }

    // 清除搜索
    const handleClear = (): void => {
        keyword.value = ''
        page.value = 1
        loadData(true)
    }

    // 切换状态标签
    const handleStatusChange = (status: string): void => {
        currentStatus.value = status
        page.value = 1
        loadData(true)
    }

    // 点击列表项
    const handleItemClick = (item: any | null, index: number): void => {
        if (item == null) return
        const messageId = getMessageId(item)
        if (messageId.length == 0) return
        
        // 标记为已读
        if (getStatus(item) == 'UNREAD') {
            markMessageAsRead(messageId).then(() => {
                // 重新加载数据
                loadData(true)
                // 通知tabbar更新未读消息数量
                uni.$emit('updateUnreadCount')
            }).catch((e) => {
                console.error('标记已读失败:', e)
            })
        }
        
        // 可以在这里添加跳转到消息详情页的逻辑
    }

    // 组件卸载前清理
    onBeforeUnmount(() => {
        refreshing.value = false
        loading.value = false
    })

    // 初始化
    onMounted(() => {
        loadData(true)
    })
</script>

<style lang="scss">
	.page-container {
	    flex: 1;
	    background-color: #f5f8fe;
	    padding-top: env(safe-area-inset-top);
		background-color: #e8f0f9;
		padding: 20rpx 10rpx 20rpx 10rpx;
	}
	.page-header{
		font-size: 32rpx;
		color: #333333;
		font-weight: bold;
		padding-top:20px;
		padding-bottom: 10px;
	}
    .list-page {
        flex: 1;
        background-color: #e8f0f9;
    }

    .search-bar {
        padding: 20rpx 30rpx;
        background-color: #d7eafe;
    }

    .search-box {
        flex-direction: row;
        align-items: center;
        height: 72rpx;
        padding: 0 24rpx;
        background-color: #f5f5f5;
        border-radius: 36rpx;

        .search-icon {
            width: 32rpx;
            height: 32rpx;
            margin-right: 12rpx;
        }

        .search-input {
            flex: 1;
            font-size: 28rpx;
            color: #333333;
        }

        .search-btn {
            padding: 10rpx 20rpx;
            background-color: #007aff;
            border-radius: 8rpx;
            margin-left: 10rpx;
        }

        .search-btn-text {
            color: #ffffff;
            font-size: 24rpx;
        }

        .clear-btn {
            width: 36rpx;
            height: 36rpx;
            border-radius: 18rpx;
            background-color: #cccccc;
            align-items: center;
            justify-content: center;
            margin-left: 10rpx;
        }

        .clear-btn-text {
            color: #ffffff;
            font-size: 24rpx;
            font-weight: bold;
        }
    }

    .status-tabs {
        display: flex;
        flex-direction: row;
        padding: 0rpx 30rpx 20rpx;
        background-color: #d7eafe;
    }

    .status-tab {
        flex: 1;
        padding: 16rpx 0;
        text-align: center;
        margin-right: 16rpx;
        border-radius: 8rpx;
        background-color: #f5f5f5;
        justify-content: center;
        align-items: center;

        &:last-child {
            margin-right: 0;
        }

        &.active {
            background-color: #007aff;
        }

        .status-tab-text {
            font-size: 26rpx;
            color: #666666;

            &.active-text {
                color: #ffffff;
                font-weight: bold;
            }
        }
    }

    .list-item {
        margin: 16rpx 30rpx;
        background-color: #ffffff;
        border-radius: 12rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
        
        &.unread {
            border-left: 4rpx solid #007aff;
        }
    }

    .item-container {
        padding: 20rpx;
    }

    .item-header {
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 12rpx;

        .item-title {
            flex: 1;
            font-size: 28rpx;
            color: #333333;
            font-weight: bold;
        }

        .item-status {
            font-size: 20rpx;
            padding: 6rpx 12rpx;
            border-radius: 6rpx;
            
            &.status-UNREAD {
                background-color: #e6f7ff;
                color: #007aff;
            }
            &.status-READ {
                background-color: #f6ffed;
                color: #52c41a;
            }
        }
    }

    .item-content {
        margin-bottom: 12rpx;
        
        .content-text {
            font-size: 24rpx;
            color: #666666;
            line-height: 36rpx;
        }
    }

    .item-footer {
        display: flex;
        justify-content: flex-end;
        
        .create-time {
            font-size: 20rpx;
            color: #999999;
        }
    }
</style>
