<script setup lang="ts">
import { onMounted, onUnmounted, nextTick } from 'vue';
import { Image, Input, Button } from 'ant-design-vue';
import { UserOutlined, RobotOutlined, SearchOutlined, CustomerServiceOutlined } from '@ant-design/icons-vue';
import dayjs from 'dayjs';
import { getConsultRecordListMethod, getConsultChatListMethod } from '@/request/api/consult.api';
import type { ChatRecordModel, ChatMessageModel, ConsultantPeopleModel } from '@/model/consult.model';
import { watchDebounced } from '@vueuse/core';
import { renderMarkdown } from '@/tools/markdown';

defineOptions({ name: 'ChatHistory' });

// 扩展的消息接口（用于添加开始/结束标记）
type DisplayMessage = ChatMessageModel & {
  id: number | string; // 确保 id 可以是字符串（用于标记消息）
  isRecordStart?: boolean; // 是否是记录开始标记
  isRecordEnd?: boolean; // 是否是记录结束标记
};

interface Props {
  data?: ConsultantPeopleModel;
  messages?: ChatMessageModel[];
  onClose?: () => void;
}

const props = defineProps<Props>();

const emits = defineEmits<{
  close: [];
}>();

// 搜索关键词（支持内容和时间搜索）
const searchKeyword = ref('');

// 分页相关
const pageSize = 10; // 每页加载数量
const currentPage = ref(1);
const loading = ref(false);
const hasMore = ref(true);
const messagesContainerRef = ref<HTMLElement | null>(null);
// 当前显示的聊天记录
const displayedRecords = ref<ChatRecordModel[]>([]);

// 搜索模式下的消息列表
const searchMessages = ref<ChatMessageModel[]>([]);

// 是否处于搜索模式
const isSearchMode = ref(false);

// 总记录数
const totalRecords = ref(0);

// 初始化数据（加载第一页）
onMounted(async () => {
  // 重置状态
  currentPage.value = 1;
  displayedRecords.value = [];
  searchMessages.value = [];
  isSearchMode.value = false;
  hasMore.value = true;
  await getChatRecordList();

  // 等待DOM更新后添加滚动监听
  nextTick(() => {
    if (messagesContainerRef.value) {
      messagesContainerRef.value.addEventListener('scroll', handleScroll);
    }
  });
});

onUnmounted(() => {
  // 移除滚动监听
  if (messagesContainerRef.value) {
    messagesContainerRef.value.removeEventListener('scroll', handleScroll);
  }
  // 清理定时器
  if (scrollTimer) {
    clearTimeout(scrollTimer);
    scrollTimer = null;
  }
});
// 获取搜索聊天记录列表
async function getSearchChatRecordList(keyword: string) {
  if (loading.value) return;
  
  loading.value = true;
  isSearchMode.value = true;
  
  try {
    const patientId = (props.data as any)?.patientId || (props.data as any)?.id?.toString();
    if (!patientId) {
      console.error('缺少患者ID');
      hasMore.value = false;
      loading.value = false;
      return;
    }
    
    // 重置分页
    currentPage.value = 1;
    
    const res = await getConsultChatListMethod(currentPage.value, pageSize, patientId, {
      keyWord: keyword,
    });
    
    if (res && res.data && res.data.length > 0) {
      totalRecords.value = res?.total || 0;
      // 搜索模式下，直接用搜索结果替换所有记录
      searchMessages.value = res.data;
      
      // 检查是否还有更多数据
      if (searchMessages.value.length >= totalRecords.value || res.data.length < pageSize) {
        hasMore.value = false;
      } else {
        hasMore.value = true;
      }
    } else {
      searchMessages.value = [];
      hasMore.value = false;
    }
  } catch (error) {
    console.error('获取搜索聊天记录失败:', error);
    searchMessages.value = [];
    hasMore.value = false;
  } finally {
    loading.value = false;
  }
}

// 获取聊天记录列表
async function getChatRecordList() {
  if (loading.value) return;
  loading.value = true;
  try {
    // 使用 patientId 或 id 作为患者ID
    const patientId = (props.data as any)?.patientId || (props.data as any)?.id?.toString();
    if (!patientId) {
      console.error('缺少患者ID');
      hasMore.value = false;
      loading.value = false;
      return;
    }
    const res = await getConsultRecordListMethod(currentPage.value, pageSize, patientId);
    if (res && res.data && res.data.length > 0) {
      totalRecords.value = res?.total || 0;
      // 追加到数组末尾
      displayedRecords.value = [...displayedRecords.value, ...res.data];
      // 检查是否还有更多数据
      if (displayedRecords.value.length >= totalRecords.value || res.data.length < pageSize) {
        hasMore.value = false;
      }
    } else {
      hasMore.value = false;
    }
  } catch (error) {
    console.error('获取聊天记录失败:', error);
    hasMore.value = false;
  } finally {
    loading.value = false;
  }
}

// 加载更多记录
async function loadMoreMessages() {
  if (loading.value || !hasMore.value) return;

  currentPage.value++;
  
  // 如果是搜索模式，加载更多搜索结果
  if (isSearchMode.value && searchKeyword.value) {
    await loadMoreSearchMessages();
  } else {
    await getChatRecordList();
  }
}

// 加载更多搜索结果
async function loadMoreSearchMessages() {
  if (loading.value) return;
  
  loading.value = true;
  
  try {
    const patientId = (props.data as any)?.patientId || (props.data as any)?.id?.toString();
    if (!patientId) {
      console.error('缺少患者ID');
      hasMore.value = false;
      loading.value = false;
      return;
    }
    
    const res = await getConsultChatListMethod(currentPage.value, pageSize, patientId, {
      keyWord: searchKeyword.value,
    });
    
    if (res && res.data && res.data.length > 0) {
      // 追加到搜索结果
      searchMessages.value = [...searchMessages.value, ...res.data];
      
      // 检查是否还有更多数据
      if (searchMessages.value.length >= totalRecords.value || res.data.length < pageSize) {
        hasMore.value = false;
      }
    } else {
      hasMore.value = false;
    }
  } catch (error) {
    console.error('加载更多搜索结果失败:', error);
    hasMore.value = false;
  } finally {
    loading.value = false;
  }
}

// 处理滚动事件（使用节流避免频繁触发）
let scrollTimer: number | null = null;
function handleScroll(e: Event) {
  // 节流处理，避免频繁触发
  if (scrollTimer) {
    clearTimeout(scrollTimer);
  }

  scrollTimer = window.setTimeout(() => {
    const target = e.target as HTMLElement;
    // 当滚动到底部附近时（距离底部100px内），加载更多消息
    const scrollTop = target.scrollTop;
    const scrollHeight = target.scrollHeight;
    const clientHeight = target.clientHeight;
    const distanceToBottom = scrollHeight - scrollTop - clientHeight;

    if (distanceToBottom <= 100 && hasMore.value && !loading.value) {
      loadMoreMessages();
    }
    scrollTimer = null;
  }, 100);
}

// 将所有记录展平为消息列表，并添加开始/结束标记
const filteredMessages = computed(() => {
  // 如果是搜索模式，直接返回搜索消息列表
  if (isSearchMode.value && searchMessages.value.length > 0) {
    return searchMessages.value as DisplayMessage[];
  }

  // 正常模式：处理聊天记录
  const records = displayedRecords.value;
  if (!records || records.length === 0) {
    return [];
  }

  const messages: DisplayMessage[] = [];

  // 使用 for 循环替代 forEach，性能更好
  for (let i = 0; i < records.length; i++) {
    const record = records[i];
    const recordId = record.id || i;

    // 添加开始咨询标记（每条记录的开始）
    const startTime = (record as any).startTime;
    if (startTime) {
      messages.push({
        id: `start-${recordId}`,
        sendType: '3', // 系统消息
        messageType: '1', // 文本
        messageContent: `开始咨询 ${formatTime(startTime)}`,
        sendTime: startTime,
        consultRecordId: record.id,
        isRecordStart: true,
      } as DisplayMessage);
    }

    // 展平每条记录的 items，直接使用原始数据（避免扩展运算符，直接引用）
    const items = record.items;
    if (items && items.length > 0) {
      // 直接 push items，避免扩展运算符的开销
      for (let j = 0; j < items.length; j++) {
        messages.push(items[j] as DisplayMessage);
      }
    }

    // 添加结束咨询标记（每条记录的结束）
    if (record.endTime) {
      messages.push({
        id: `end-${recordId}`,
        sendType: '3', // 系统消息
        messageType: '1', // 文本
        messageContent: `咨询结束 ${formatTime(record.endTime)}`,
        sendTime: record.endTime,
        consultRecordId: record.id,
        isRecordEnd: true,
      } as DisplayMessage);
    }
  }

  return messages;
});
watchDebounced(
  searchKeyword,
  async (newVal: any) => {
    const patientId = (props.data as any)?.patientId || (props.data as any)?.id?.toString();
    if (!patientId) {
      console.error('缺少患者ID');
      return;
    }
    
    if (newVal && newVal.trim()) {
      // 有搜索关键词，执行搜索
      await getSearchChatRecordList(newVal.trim());
    } else {
      // 清空搜索，恢复正常模式
      isSearchMode.value = false;
      searchMessages.value = [];
      // 重置分页并重新加载正常记录
      currentPage.value = 1;
      displayedRecords.value = [];
      hasMore.value = true;
      await getChatRecordList();
    }
  },
  { debounce: 500 }
);

// 格式化时间
function formatTime(time: string) {
  return dayjs(time).format('MM-DD HH:mm:ss');
}

// 关闭弹窗
function handleClose() {
  emits('close');
  if (props.onClose) {
    props.onClose();
  }
}
</script>

<template>
  <div class="chat-history-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <Input v-model:value="searchKeyword" placeholder="请输入搜索内容或时间" allow-clear>
        <template #prefix>
          <SearchOutlined />
        </template>
      </Input>
    </div>

    <!-- 聊天记录列表 -->
    <div class="messages-container" ref="messagesContainerRef">
      <div v-for="msg in filteredMessages" :key="msg.id" class="message-item" :class="msg.sendType">
        <div class="message-avatar" v-if="msg.sendType !== '3'">
          <UserOutlined v-if="msg.sendType === '1'" />
          <RobotOutlined v-else-if="msg.sendType === '4'" />
          <CustomerServiceOutlined v-else-if="msg.sendType === '2'" />
        </div>
        <div class="message-content-wrapper" :class="msg.sendType">
          <div class="message-content" :class="msg.sendType">
            <Image
              v-if="msg.messageType === '2'"
              :src="msg.messageContent"
              alt="图片"
              style="width: 200px; height: 200px"
              class="message-image"
              :preview="{
                src: msg.messageContent,
              }"
            />
            <div v-else class="message-text" v-html="renderMarkdown(msg.messageContent)"></div>
          </div>
          <div class="message-time" v-if="msg.sendType !== '3'">{{ formatTime(msg.sendTime) }}</div>
        </div>
      </div>

      <!-- 加载提示 -->
      <div v-if="loading" class="loading-more">加载中...</div>
      <div v-else-if="!hasMore && displayedRecords.length > 0" class="no-more">无更多数据</div>
    </div>

    <!-- 关闭按钮 -->
    <div class="close-button-container">
      <Button type="primary" @click="handleClose" block class="close-btn">关闭</Button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.chat-history-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.search-container {
  flex-shrink: 0;
  padding-bottom: 16px;

  :deep(.ant-input) {
    width: 100%;
  }
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px 0;
  min-height: 0;
  display: flex;
  flex-direction: column;

  .loading-more,
  .no-more {
    text-align: center;
    padding: 12px;
    color: #999;
    font-size: 12px;
    flex-shrink: 0;
  }
}

.close-button-container {
  flex-shrink: 0;
  padding-top: 16px;
  margin-top: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  .close-btn {
    width: 10%;
  }
}

.message-item {
  display: flex;
  margin-bottom: 16px;
  width: 100%;

  // sendType: 1-患者
  &[class*=' 1'],
  &[class^='1 '],
  &[class$=' 1'],
  &[class='1'] {
    justify-content: flex-start;

    .message-avatar {
      order: 1;
    }

    .message-content-wrapper {
      order: 2;
    }

    .message-content {
      // background: #fff;
      background: #f0f0f0;
      color: #333;
      border-radius: 8px 8px 8px 0;
    }
  }

  // sendType: 2-医生 4-AI
  &[class*=' 2'],
  &[class^='2 '],
  &[class$=' 2'],
  &[class='2'],
  &[class*=' 4'],
  &[class^='4 '],
  &[class$=' 4'],
  &[class='4'] {
    justify-content: flex-end;

    .message-avatar {
      order: 2;
    }

    .message-content-wrapper {
      order: 1;
      align-items: flex-end;
    }

    .message-content {
      background: #1890ff;
      color: #fff;
      border-radius: 8px 8px 0 8px;
    }
  }

  // sendType: 3-系统
  &[class*=' 3'],
  &[class^='3 '],
  &[class$=' 3'],
  &[class='3'] {
    justify-content: center;
    margin: 8px 0;

    .message-content {
      background: transparent;
      color: #999;
      font-size: 12px;
      padding: 4px 0;
    }
  }
}

.message-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f0f0;
  margin: 0 8px;
  flex-shrink: 0;
}

.message-content-wrapper {
  max-width: 60%;
  display: flex;
  flex-direction: column;

  // sendType: 1-患者
  &[class*=' 1'],
  &[class^='1 '],
  &[class$=' 1'],
  &[class='1'] {
    align-items: flex-start;

    .message-time {
      text-align: left;
      padding-left: 4px;
      margin-top: 4px;
    }
  }

  // sendType: 2-医生 4-AI
  &[class*=' 2'],
  &[class^='2 '],
  &[class$=' 2'],
  &[class='2'],
  &[class*=' 4'],
  &[class^='4 '],
  &[class$=' 4'],
  &[class='4'] {
    align-items: flex-end;

    .message-time {
      text-align: right;
      padding-right: 4px;
      margin-top: 4px;
    }
  }

  // sendType: 3-系统
  &[class*=' 3'],
  &[class^='3 '],
  &[class$=' 3'],
  &[class='3'] {
    align-items: center;
    width: 100%;
    max-width: 100%;
  }
}

.message-content {
  padding: 8px 12px;
  word-wrap: break-word;
  word-break: break-word;
  white-space: pre-wrap;
  overflow-wrap: break-word;
  max-width: 100%;
  box-sizing: border-box;

  .message-text {
    display: block;
    word-wrap: break-word;
    word-break: break-word;
    white-space: pre-wrap;
    overflow-wrap: break-word;
    width: 100%;
    line-height: 1.5;
    
    // Markdown 渲染样式
    :deep(strong) {
      font-weight: bold;
    }
  }

  .message-image {
    max-width: 120px;
    max-height: 120px;
    border-radius: 8px;
    display: block;
    cursor: pointer;

    :deep(img) {
      max-width: 120px !important;
      max-height: 120px !important;
      width: auto !important;
      height: auto !important;
      border-radius: 8px;
      display: block;
      object-fit: contain;
    }
  }
}

.message-time {
  font-size: 12px;
  color: #999;
  padding: 0 4px;
}
</style>
