<template>
  <view class="message-page">
    <Loading type="page" :loading="pageLoading" />

    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="navbar-content">
        <text class="navbar-title">消息</text>
      </view>
    </view>

    <!-- 消息列表区域 -->
    <scroll-view 
      class="message-scroll" 
      scroll-y 
      :style="{ paddingTop: (statusBarHeight + 44) + 'px' }"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="handleRefresh"
    >
      <!-- 聊天会话列表 -->
      <view class="session-list" v-if="sessions.length > 0">
        <view 
          class="session-item" 
          v-for="session in sessions" 
          :key="session.sessionId"
          @click="handleSessionClick(session)"
        >
          <view class="session-avatar">
            <image class="avatar-img" :src="session.targetAvatar || '/static/logo.png'" mode="aspectFill" />
            <view class="unread-badge" v-if="session.unreadCount > 0">
              <text>{{ session.unreadCount > 99 ? '99+' : session.unreadCount }}</text>
            </view>
          </view>

          <view class="session-info">
            <view class="session-header">
              <text class="session-nickname">{{ session.targetNickname }}</text>
              <text class="session-time">{{ formatTime(session.lastMessageTime) }}</text>
            </view>
            <view class="session-content">
              <text class="last-message">{{ session.lastMessage || '暂无消息' }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 未登录状态 -->
      <view class="empty-state" v-else-if="!pageLoading && !userStore.isLoggedIn">
        <image src="/static/ic_empty.png" mode="aspectFit" class="empty-icon" />
        <text class="empty-text">登录后查看消息</text>
        <button class="login-btn" @click="handleLogin">立即登录</button>
      </view>

      <!-- 无聊天记录 -->
      <view class="empty-state" v-else-if="!pageLoading && sessions.length === 0">
        <image src="/static/ic_empty.png" mode="aspectFit" class="empty-icon" />
        <text class="empty-text">暂无聊天记录</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useChatStore } from '@/store/chat.js'
import { useUserStore } from '@/store/user.js'
import { getSessions } from '@/api/chat.js'
import { formatTimestamp } from '@/utils/format.js'
import Loading from '@/components/Loading/index.vue'

const chatStore = useChatStore()
const userStore = useUserStore()

const pageLoading = ref(true)
const isRefreshing = ref(false)
const statusBarHeight = ref(20)
const sessions = ref([])

const getSystemInfo = () => {
  uni.getSystemInfo({
    success: (res) => {
      statusBarHeight.value = res.statusBarHeight || 20
    }
  })
}

const loadSessions = async () => {
  if (!userStore.isLoggedIn) return

  try {
    const res = await getSessions()
    if (res?.success) {
      sessions.value = res.data || []
      chatStore.setSessions(sessions.value)
    }
  } catch (error) {
    console.error('加载会话列表失败:', error)
  }
}

const initPage = async () => {
  pageLoading.value = true
  try {
    await loadSessions()
  } finally {
    pageLoading.value = false
  }
}

const handleRefresh = async () => {
  isRefreshing.value = true
  try {
    await loadSessions()
  } finally {
    isRefreshing.value = false
  }
}

const formatTime = (timestamp) => formatTimestamp(timestamp)

const handleSessionClick = (session) => {
  chatStore.setCurrentSession(session.sessionId)
  uni.navigateTo({
    url: `/pages/chat/index?sessionId=${session.sessionId}&targetUserId=${session.targetUserId}&nickname=${session.targetNickname}&avatar=${encodeURIComponent(session.targetAvatar || '')}`
  })
}

const handleLogin = () => {
  uni.navigateTo({ url: '/pages/login/index' })
}

watch(() => chatStore.sessions, (newSessions) => {
  if (newSessions?.length) {
    sessions.value = newSessions
  }
}, { deep: true })

onShow(() => {
  if (userStore.isLoggedIn) {
    loadSessions()
  }
})

onMounted(() => {
  getSystemInfo()
  initPage()
})
</script>

<style lang="scss" scoped>
.message-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  z-index: 100;

  .navbar-content {
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;

    .navbar-title {
      font-size: 17px;
      font-weight: 600;
      color: #333;
    }
  }
}

.message-scroll {
  min-height: 100vh;
  background-color: #fff;
}

.session-list {
  .session-item {
    display: flex;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #f5f5f5;

    &:active {
      background-color: #f8f8f8;
    }

    .session-avatar {
      position: relative;
      width: 48px;
      height: 48px;
      margin-right: 12px;

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

      .unread-badge {
        position: absolute;
        top: -4px;
        right: -4px;
        min-width: 18px;
        height: 18px;
        padding: 0 4px;
        background-color: #ff4d4f;
        border-radius: 9px;
        display: flex;
        align-items: center;
        justify-content: center;

        text {
          font-size: 11px;
          color: #fff;
        }
      }
    }

    .session-info {
      flex: 1;
      overflow: hidden;

      .session-header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 6px;

        .session-nickname {
          font-size: 15px;
          font-weight: 500;
          color: #333;
        }

        .session-time {
          font-size: 12px;
          color: #999;
        }
      }

      .session-content {
        .last-message {
          font-size: 13px;
          color: #999;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100px 20px;

  .empty-icon {
    width: 100px;
    height: 100px;
    margin-bottom: 16px;
    opacity: 0.6;
  }

  .empty-text {
    font-size: 16px;
    color: #666;
    margin-bottom: 16px;
  }

  .login-btn {
    width: 120px;
    height: 40px;
    line-height: 40px;
    background: linear-gradient(135deg, #FFBDC2 0%, #FF8A93 100%);
    border-radius: 20px;
    font-size: 15px;
    color: #fff;
    border: none;
  }
}
</style>
