<template>
  <s-layout :bgStyle="{ color: '#f2f2f2' }" title="咨询记录">
    <scroll-view scroll-y="true" refresher-enabled="true" :refresher-triggered="triggered"
      @refresherrefresh="onRefresh">
      <view class="chat-list">
        <view v-for="item in chatList" :key="item.id" class="chat-item" @click="goToChat(item)">
          <view class="avatar">
            <image :src="item.userAvatar || activityright" mode="aspectFill"></image>
          </view>
          <view class="content">
            <view class="top">
              <text class="nickname">{{ item.userNickname }}</text>
              <text class="time">{{ formatTime(item.lastMessageTime) }}</text>
            </view>
            <view class="message">{{ parseMessage(item.lastMessageContent) }}</view>
          </view>
          <view v-if="item.relUserId == userInfo.id ? item.relUnreadMessageCount : item.adminUnreadMessageCount"
            class="unread-count">
            {{ item.relUserId == userInfo.id ? item.relUnreadMessageCount : item.adminUnreadMessageCount }}
          </view>
        </view>
      </view>
    </scroll-view>
  </s-layout>
</template>

<script setup>
import sheep from '@/sheep';
import { reactive, ref, toRefs, computed } from 'vue';
import { useWebSocket } from '@/sheep/hooks/useWebSocket';
import { onLoad, onShow } from '@dcloudio/uni-app';
import SpuHistoryApi from '@/sheep/api/product/history';
import activityright from '@/static/activity-right.png'
import {
  KeFuMessageContentTypeEnum,
  WebSocketMessageTypeConstants,
} from '@/pages/chat/util/constants';
const chatList = ref([]);
const triggered = ref(false);

const conversationListAxios = async () => {
  const res = await SpuHistoryApi.conversationList();
  if (res.code === 0) {
    chatList.value = res.data;
  }
}

const onRefresh = async () => {
  triggered.value = true;
  await conversationListAxios();
  triggered.value = false;
}

const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  const now = new Date();
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  }
  return date.toLocaleDateString('zh-CN');
}

const parseMessage = (content) => {
  try {
    const message = JSON.parse(content);
    return message.text.replace(/\[.*?\]/g, ''); // 移除表情符号
  } catch (e) {
    return content;
  }
}
const userInfo = computed(() => sheep.$store('user').userInfo);
console.log(userInfo.value.id, 44444)
const goToChat = (item) => {
  console.log(item, 44444)
  SpuHistoryApi.updateKefuMessageReadStatus({
    conversationId: item.id,
  })
  sheep.$router.go('/pages/chat/index', { conversationId: item.id, relUserId: userInfo.value.id === item.relUserId ? item.userId : item.relUserId })

}
const { options } = useWebSocket({
  // 连接成功
  onConnected: async () => { },
  // 收到消息
  onMessage: async (data) => {
    const type = data.type;
    if (!type) {
      console.error('未知的消息类型：' + data);
      return;
    }
    // 2.2 消息类型：KEFU_MESSAGE_TYPE
    if (type === WebSocketMessageTypeConstants.KEFU_MESSAGE_TYPE) {
      conversationListAxios();
      return;
    }
    // 2.3 消息类型：KEFU_MESSAGE_ADMIN_READ
    if (type === WebSocketMessageTypeConstants.KEFU_MESSAGE_ADMIN_READ) {
      console.log('管理员已读消息');
    }
  },
});
const isReconnecting = toRefs(options).isReconnecting; // 重连状态
onShow(() => {
  conversationListAxios();
})
onLoad(() => {
  // conversationListAxios();
});
</script>

<style lang="scss" scoped>
.chat-list {
  padding: 20rpx;
  height: calc(100vh - var(--window-top));

  .chat-item {
    display: flex;
    padding: 20rpx;
    background: #fff;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    position: relative;

    .avatar {
      width: 96rpx;
      height: 96rpx;
      margin-right: 20rpx;

      image {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
    }

    .content {
      flex: 1;

      .top {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10rpx;

        .nickname {
          font-size: 32rpx;
          color: #333;
        }

        .time {
          font-size: 24rpx;
          color: #999;
        }
      }

      .message {
        font-size: 28rpx;
        color: #666;
      }
    }

    .unread-count {
      position: absolute;
      top: 10rpx;
      right: 10rpx;
      min-width: 32rpx;
      height: 32rpx;
      line-height: 32rpx;
      text-align: center;
      background: #ff4d4f;
      color: #fff;
      border-radius: 16rpx;
      font-size: 20rpx;
      padding: 0 6rpx;
    }
  }
}
</style>
