<script setup lang="ts">
import { onMounted, onUnmounted, watch } 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 type { ChatMessageModel } from '@/model/consult.model';
import { watchDebounced } from '@vueuse/core';

defineOptions({ name: 'CurrentDayChatHistory' });

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

// 传入的聊天记录对象结构
interface ChatRecordData {
  startTime?: string; // 开始咨询时间
  endTime?: string; // 结束咨询时间
  items?: ChatMessageModel[]; // 聊天记录列表
  id?: number; // 记录ID
}

interface Props {
  row?: ChatRecordData; // 传入的聊天记录对象
  onClose?: () => void;
}

const props = defineProps<Props>();

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

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


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

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

// 本地消息列表（从传入的 row 中提取）
const localMessages = ref<DisplayMessage[]>([]);

// 初始化数据
onMounted(() => {
  console.log('props.row===传入的聊天记录', props);
  // 处理传入的聊天记录
  if (props.row) {
    processChatRecord(props.row);
  }
});

// 监听传入的 row 变化
watch(
  () => props.row,
  (newRow) => {
    if (newRow) {
      processChatRecord(newRow);
      // 重置搜索状态
      isSearchMode.value = false;
      searchMessages.value = [];
      searchKeyword.value = '';
    }
  },
  { deep: true }
);

onUnmounted(() => {
  // 清理工作（如果需要）
});

// 处理传入的聊天记录对象
function processChatRecord(record: ChatRecordData) {
  const messages: DisplayMessage[] = [];
  const recordId = record.id || 0;

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

  // 添加聊天记录 items
  if (record.items && record.items.length > 0) {
    for (let i = 0; i < record.items.length; i++) {
      messages.push(record.items[i] 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 unknown as DisplayMessage);
  }

  localMessages.value = messages;
}

// 本地搜索功能
function performLocalSearch(keyword: string) {
  if (!keyword || !keyword.trim()) {
    isSearchMode.value = false;
    searchMessages.value = [];
    return;
  }

  isSearchMode.value = true;
  const keywordLower = keyword.toLowerCase();
  
  searchMessages.value = localMessages.value.filter((msg) => {
    // 排除图片消息，只搜索文本消息
    if (msg.messageType === '2') {
      return false;
    }
    // 搜索消息内容
    if (msg.messageContent && msg.messageContent.toLowerCase().includes(keywordLower)) {
      return true;
    }
    // 搜索时间
    if (msg.sendTime && formatTime(msg.sendTime).includes(keyword)) {
      return true;
    }
    return false;
  });
}

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

  // 正常模式：返回本地消息列表
  return localMessages.value;
});
watchDebounced(
  searchKeyword,
  (newVal: any) => {
    if (newVal && newVal.trim()) {
      // 有搜索关键词，执行本地搜索
      performLocalSearch(newVal.trim());
    } else {
      // 清空搜索，恢复正常模式
      isSearchMode.value = false;
      searchMessages.value = [];
    }
  },
  { 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">
      <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">{{ msg.messageContent }}</div>
          </div>
          <div class="message-time" v-if="msg.sendType !== '3'">{{ formatTime(msg.sendTime) }}</div>
        </div>
      </div>
      <!-- 空状态提示 -->
      <div v-if="filteredMessages.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;
  }

  .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>
