<template>
  <view class="page-container">
    <view class="page-header">
      <PageHeader title="在线咨询" :is-back="false" :border-bottom="false" />
    </view>
    
    <scroll-view 
      class="page-main" 
      scroll-y
      enable-back-to-top
    >
      <view class="main-content">
        <!-- 聊天会话列表 -->
        <view 
          class="chat-item" 
          v-for="(item, index) in displayChatList" 
          :key="item.id || index" 
          @click="openChat(item)"
        >
          <view class="chat-avatar-wrapper">
            <image class="chat-avatar" :src="item.avatar"></image>
            <!-- 未读数角标 -->
            <view class="unread-badge" v-if="item.unreadCount > 0">
              {{ item.unreadCount > 99 ? '99+' : item.unreadCount }}
            </view>
          </view>
          
          <view class="chat-content">
            <view class="chat-header">
              <text class="chat-name">{{ item.name }}</text>
              <text class="chat-time">{{ item.displayTime }}</text>
            </view>
            <view class="chat-preview">
              <text class="preview-text">{{ item.displayPreview }}</text>
            </view>
          </view>
        </view>

        <!-- 无数据提示 -->
        <view class="empty-container" v-if="chatList.length === 0">
          <image class="empty-image" src="/static/common/icon/empty-chat.png"></image>
          <text class="empty-text">暂无咨询消息</text>
          <text class="empty-hint">学生咨询后会显示在这里</text>
        </view>
      </view>
    </scroll-view>

    <view class="page-tabbar">
      <TabBar :currentPath="'/pages/consultation/index'" @change="handleTabChange" />
    </view>
  </view>
</template>

<script>
import TabBar from "@/components/TabBar-optimized.vue";
import PageHeader from "@/components/PageHeader.vue";

export default {
  name: "ConsultationPage",
  components: {
    TabBar,
    PageHeader,
  },
  computed: {
    // 补充展示字段，便于模板直接使用
    unreadMap() {
      const map = {};
      const list = this.$store?.state?.vuex_userMsgList || [];
      list.forEach((item) => {
        const id = this.getDialogueId(item);
        const count =
          item?.unReadCount ??
          item?.unreadCount ??
          item?.unread ??
          null;
        if (id && typeof count === "number") {
          map[id] = count;
        }
      });
      return map;
    },
    displayChatList() {
      // 合并接口首帧列表 + 实时更新列表，按 id 匹配覆盖
      const realtime = this.$store?.state?.vuex_userMsgList || [];
      const baseList = this.chatList || [];

      const rtMap = {};
      realtime.forEach((item) => {
        const id = this.getDialogueId(item);
        if (id) rtMap[id] = item;
      });

      const merged = baseList.map((item) => {
        const id = this.getDialogueId(item);
        const rt = id ? rtMap[id] : null;
        const source = rt || item;
        const unread =
          typeof this.unreadMap[id] === "number"
            ? this.unreadMap[id]
            : source?.unReadCount ??
              source?.unreadCount ??
              source?.unread ??
              0;

        return {
          ...item,
          ...rt,
          id,
          dialogueManagementId: id,
          DialogueManagementId: id,
          userId:
            source?.receiverId ||
            source?.friendId ||
            source?.userId ||
            item?.userId ||
            "",
          avatar:
            source?.receiverHeadSculptureUrl ||
            source?.avatar ||
            source?.friendAvatar ||
            "/static/avatar/default-avatar.png",
          displayTime: this.formatTime(
            source?.lastMessageTime ||
              source?.lastSendTime ||
              source?.sendDate ||
              item?.lastMessageTime ||
              ""
          ),
          displayPreview:
            source?.lastMessage ||
            source?.message ||
            item?.lastMessage ||
            "暂无消息",
          unreadCount: unread,
        };
      });

      // 追加实时列表中基线不存在的会话
      realtime.forEach((item) => {
        const id = this.getDialogueId(item);
        if (!id) return;
        const exists = merged.some((row) => row.id === id);
        if (!exists) {
          const unread =
            typeof this.unreadMap[id] === "number"
              ? this.unreadMap[id]
              : item?.unReadCount ??
                item?.unreadCount ??
                item?.unread ??
                0;
          merged.unshift({
            ...item,
            id,
            dialogueManagementId: id,
            DialogueManagementId: id,
            userId:
              item?.receiverId ||
              item?.friendId ||
              item?.userId ||
              "",
            avatar:
              item?.receiverHeadSculptureUrl ||
              item?.avatar ||
              item?.friendAvatar ||
              "/static/avatar/default-avatar.png",
            displayTime: this.formatTime(
              item?.lastMessageTime ||
                item?.lastSendTime ||
                item?.sendDate ||
                ""
            ),
            displayPreview:
              item?.lastMessage || item?.message || "暂无消息",
            unreadCount: unread,
          });
        }
      });

      return merged;
    },
  },
  data() {
    return {
      // 聊天会话列表
      chatList: [],
      totalCount: 0,
      isLoading: false,
      hasLoaded: false,
    };
  },
  
  onLoad() {
    // 加载聊天列表
    this.loadChatList().finally(() => {
      this.hasLoaded = true;
    });
  },
  
  onShow() {
    // 页面显示时刷新列表
    if (this.hasLoaded) {
      this.refreshChatList();
    }
  },
  
  methods: {
    handleTabChange(path, index) {
      console.log("切换到标签页:", path, index);
    },
    
    // 打开聊天页面前标记已读
    async openChat(item) {
      console.log("打开聊天:", item);

      if (item?.id) {
        try {
          await this.$u.api.ReadMessageApi({
            dialogueManagementId: item.id,
          });
        } catch (err) {
          console.error("[在线咨询] 标记已读失败", err);
        }
      }

      this.$store.dispatch("selectTeacherChatItem", {
        id: item.id,
        receiverId: item.userId,
      });
    },
    
    // 加载聊天列表
    async loadChatList() {
      if (this.isLoading) return;
      this.isLoading = true;

      try {
        const res = await this.$u.api.GetDialogueListApi();
        const list = (res && res.data && res.data.item1) || [];

        this.chatList = this.normalizeDialogueList(list);
        // 同步到全局会话列表，便于后续实时合并
        this.$store.commit("set_UserMsgList", this.chatList);
        this.$store.commit("upsert_DialogueTypeMap", {
          list: this.chatList,
          type: 1,
        });
        this.totalCount = res?.data?.item2 || list.length;
      } catch (error) {
        console.error("[在线咨询] 获取会话列表失败", error);
        uni.showToast({
          title: "获取会话列表失败",
          icon: "none",
        });
      } finally {
        this.isLoading = false;
      }
    },
    
    // 刷新聊天列表
    refreshChatList() {
      this.loadChatList();
    },

    // 规范化接口返回的会话列表数据
    normalizeDialogueList(list = []) {
      return list.map((item, index) => {
        const unread =
          typeof item?.unReadCount === "number"
            ? item.unReadCount
            : item?.unreadCount || 0;

        const id =
          item?.dialogueManagementId ||
          item?.DialogueManagementId ||
          item?.dialogueId ||
          item?.friendId ||
          item?.id ||
          index;

        return {
          id,
          dialogueManagementId: id,
          DialogueManagementId: id,
          userId: item?.receiverId || item?.friendId || item?.userId || "",
          friendId: item?.receiverId || item?.friendId || item?.userId || "",
          name:
            item?.receiverName ||
            item?.friendName ||
            item?.userName ||
            item?.title ||
            "",
          avatar: this.buildAvatarUrl(
            item?.receiverHeadSculptureUrl ||
              item?.avatar ||
              item?.friendAvatar
          ),
          lastMessage: item?.lastMessage || "暂无消息",
          lastMessageTime: this.formatTime(
            item?.lastMessageTime || item?.lastSendTime || item?.startTime
          ),
          unreadCount: unread,
        };
      });
    },

    // 拼装头像地址，兼容相对路径
    buildAvatarUrl(url) {
      const fallback = "/static/avatar/default-avatar.png";
      if (!url) return fallback;
      if (/^https?:\/\//i.test(url)) return url;
      const baseUrl = this.$u?.http?.config?.baseUrl || "";
      if (baseUrl) return `${baseUrl}/${url}`;
      return url.startsWith("/") ? url : `/${url}`;
    },

    // 格式化时间显示
    formatTime(timeStr) {
      if (!timeStr) return "";
      const date = new Date(timeStr);
      if (!isNaN(date.getTime())) {
        const month = (date.getMonth() + 1).toString().padStart(2, "0");
        const day = date.getDate().toString().padStart(2, "0");
        const hours = date.getHours().toString().padStart(2, "0");
        const minutes = date.getMinutes().toString().padStart(2, "0");
        return `${month}/${day} ${hours}:${minutes}`;
      }
      // 回退到字符串裁剪
      return String(timeStr).replace("T", " ").slice(5, 16);
    },

    // 统一获取会话唯一标识
    getDialogueId(item) {
      return (
        item?.dialogueManagementId ||
        item?.DialogueManagementId ||
        item?.dialogueId ||
        item?.friendId ||
        item?.id ||
        ""
      );
    },
  },
};
</script>

<style scoped>
/* ===== 页面容器 - 主流三段式布局 ===== */
.page-container {
  /* 固定定位，占满整个视口 */
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  
  /* Flex 布局 */
  display: flex;
  flex-direction: column;
  
  /* 背景色 */
  background-color: #f5f6fa;
  
  /* 防止溢出 */
  overflow: hidden;
}

/* ===== 头部导航 ===== */
.page-header {
  /* 不收缩，固定高度 */
  flex-shrink: 0;
  
  /* 层级 */
  z-index: 100;
}

/* ===== 内容区域 ===== */
.page-main {
  /* 占据剩余空间 */
  flex: 1;
  
  /* 重要：防止 flex 子元素溢出 */
  height: 0;
  
  /* 允许滚动 */
  overflow-y: auto;
  
  /* iOS 滚动优化 */
  -webkit-overflow-scrolling: touch;
}

/* ===== 内容内层 ===== */
.main-content {
  /* 内边距 */
  /* padding: 10px; */
  padding: 10px 0 10px 0;
  /* 底部留出 TabBar 空间 + 安全区域 */
  padding-bottom: calc(50px + env(safe-area-inset-bottom) + 10px);
  
  /* 最小高度（确保可以滚动） */
  min-height: 100%;
}

/* ===== 底部导航 ===== */
.page-tabbar {
  /* 不收缩，固定高度 */
  flex-shrink: 0;
  
  /* 层级 */
  z-index: 100;
}

/* ===== 聊天列表项 ===== */
.chat-item {
  display: flex;
  padding: 15px;
  background: #fff;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.2s;
}

.chat-item:active {
  background-color: #f5f5f5;
}

.chat-avatar-wrapper {
  position: relative;
  margin-right: 12px;
}

.chat-avatar {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  background-color: #e8e8e8;
}

.unread-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  min-width: 18px;
  height: 18px;
  padding: 0 5px;
  background: #ff4d4f;
  border-radius: 9px;
  color: #fff;
  font-size: 11px;
  line-height: 18px;
  text-align: center;
  border: 2px solid #fff;
}

.chat-content {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.chat-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-time {
  font-size: 12px;
  color: #999;
  flex-shrink: 0;
}

.chat-preview {
  display: flex;
  align-items: center;
}

.preview-text {
  font-size: 13px;
  color: #999;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

/* ===== 空状态 ===== */
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100px 20px;
}

.empty-image {
  width: 120px;
  height: 120px;
  margin-bottom: 20px;
}

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

.empty-hint {
  font-size: 13px;
  color: #999;
}
</style>
