<script setup>
import { nextTick, onMounted, ref, watch } from 'vue';

import { MessageOutlined } from '@ant-design/icons-vue';
import { Spin } from 'ant-design-vue';

import { useChatStore } from '../stores/chat.ts';
import { useUserStore } from '../stores/user.ts';
import { getTransferAssistantConfig } from '#/views/system/transfer-question/api';
import MessageBubble from './MessageBubble.vue';

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

const emit = defineEmits(['open-prescription', 'transfer-import-success']);

const messagesContainer = ref(null);
const loadingMessages = ref(false);
const loadingOlderMessages = ref(false); // 加载历史消息状态
const isLoading = ref(false); // 加载历史消息状态
// const chatStore.hasMore = ref(true); // 是否有更多历史消息
const oldScrollHeight = ref(0); // 已加载次数

// 助理配置缓存
const assistantConfig = ref({
  name: '医生助理',
  avatar: '',
});

// 加载助理配置
const loadAssistantConfig = async () => {
  try {
    const result = await getTransferAssistantConfig();
    // 兼容不同的API响应格式：res.data.result 或 res.result
    // const result = res?.data?.result ?? res?.result;
    if (result) {
      assistantConfig.value = {
        name: result.name || '医生助理',
        avatar: result.avatar || '',
      };
    }
  } catch (error) {
    console.error('加载助理配置失败:', error);
  }
};

// 初始化时加载助理配置
onMounted(() => {
  loadAssistantConfig();
});

// 获取发送者信息
const getSenderInfo = (message) => {
  const senderId = message.sender_user_id || message.senderId;

  // 如果是医生助理发送的消息
  if (senderId === 'doctor_assistant') {
    return {
      nick_name: assistantConfig.value.name,
      avatar: assistantConfig.value.avatar || assistantConfig.value.name.charAt(0),
      color: '#4cc9f0',
    };
  }

  // 如果是当前医生发送的消息
  if (senderId === userStore.currentUser.doctor_id || senderId === `doctor-${userStore.currentUser.doctor_id}`) {
    return {
      nick_name: userStore.currentUser.nick_name,
      avatar: userStore.currentUser.nick_name.charAt(0),
      color: userStore.currentUser.color || '#4cc9f0',
    };
  }

  // 其他情况（患者发送的消息）
  return {
    nick_name: chatStore.currentFriend?.nick_name || '未知用户',
    avatar:
      chatStore.currentFriend?.avatar ||
      chatStore.currentFriend?.nick_name.charAt(0) ||
      '?',
    color: chatStore.currentFriend?.color || '#ff6b6b',
  };
};

// 滚动到底部
const scrollToBottom = (type = 0) => {
  if (type === 1) {
    nextTick(() => {
      console.table('高度', {
        o: oldScrollHeight.value,
        n: messagesContainer.value.scrollHeight,
        '-': messagesContainer.value.scrollHeight - oldScrollHeight.value,
      });
      messagesContainer.value.scrollTop =
        messagesContainer.value.scrollHeight - oldScrollHeight.value;
    });
    return;
  }
  if (messagesContainer.value) {
    nextTick(() => {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    });
  }
};

// 加载历史消息
const loadOlderMessages = async () => {
  if (loadingOlderMessages.value || !chatStore.hasMore) return;

  oldScrollHeight.value = messagesContainer.value.scrollHeight;
  loadingOlderMessages.value = true;
  isLoading.value = true;

  try {
    // 模拟网络请求延迟
    await new Promise((resolve) => setTimeout(resolve, 1800));

    // 生成模拟的历史消息
    chatStore.generateOldMessages();

  } finally {
    loadingOlderMessages.value = false;
  }
};

// 处理滚动事件
const handleScroll = () => {
  if (!messagesContainer.value) return;

  const { scrollTop, scrollHeight, clientHeight } = messagesContainer.value;

  // 滚动到顶部时加载更多
  if (
    scrollTop < 100 &&
    !loadingOlderMessages.value &&
    chatStore.hasMore
  ) {
    loadOlderMessages();
  }
};

// 监听消息变化，自动滚动到底部
watch(
  () => chatStore.messages.length,
  () => {
    if (isLoading.value === true) {
      isLoading.value = false;
      scrollToBottom(1);
      return;
    }
    scrollToBottom();
  },
);

// 监听当前好友变化，重新加载消息
watch(
  () => chatStore.currentFriend,
  (newFriend, oldFriend) => {
    if (newFriend?.id !== oldFriend?.id) {
      // 重置加载状态
      chatStore.hasMore = true;
      scrollToBottom();
    }
  },
);

onMounted(() => {
  scrollToBottom();
});
</script>

<template>
  <div
    ref="messagesContainer"
    class="message-list-background flex-1 overflow-y-auto bg-gray-50 p-5 dark:bg-gray-900 min-h-0"
    @scroll="handleScroll"
  >
    <Spin :spinning="loadingMessages" tip="加载消息中...">
      <!-- 空状态 -->
      <div
        v-if="chatStore.messages.length === 0 && chatStore.currentFriend"
        class="flex h-full min-h-[300px] w-full items-center justify-center py-10 text-center text-gray-500 dark:text-gray-400"
      >
        <MessageOutlined class="mb-2 text-4xl mr-2" />
        <p>开始与 {{ chatStore.currentFriend.nick_name }} 对话吧！</p>
      </div>

      <!-- 消息列表 -->
      <div v-if="!loadingMessages">
        <!-- 顶部加载提示 -->
        <div v-if="loadingOlderMessages" class="py-3 text-center">
          <Spin size="small" tip="加载历史消息中..." />
        </div>

        <!-- 没有更多消息提示 -->
        <div
          v-if="!chatStore.hasMore"
          class="py-3 text-center text-sm text-gray-400"
        >
          没有更多消息了
        </div>

        <div
          v-for="(msg, index) in chatStore.messages"
          :key="msg.id || index"
          class="clear-both mb-6"
        >
          <MessageBubble
            :is-sent="msg.isSent"
            :message="msg"
            :sender-info="getSenderInfo(msg)"
            @open-prescription="(registerId) => emit('open-prescription', registerId)"
            @transfer-import-success="(data) => emit('transfer-import-success', data)"
          />
        </div>
      </div>
    </Spin>
  </div>
</template>

<style>
.message-list-background {
  background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" opacity="0.03"><rect width="100" height="100" fill="none"/><path d="M0,0 L100,100 M100,0 L0,100" stroke="currentColor"/></svg>');
  background-size: 200px 200px;
}
</style>
