<template>
  <div 
    v-if="visible" 
    class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
    @click.self="handleClose"
  >
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-4xl max-h-[90vh] flex flex-col">
      <!-- 弹框头部 -->
      <div class="flex items-center justify-between p-6 border-b border-gray-200">
        <div>
          <h2 class="text-2xl font-bold text-gray-900">聊天历史记录</h2>
          <p class="text-sm text-gray-600 mt-1">查看和搜索您的所有对话记录</p>
        </div>
        <button 
          @click="handleClose"
          class="text-gray-400 hover:text-gray-600 transition-colors p-2 rounded-full hover:bg-gray-100"
        >
          <i data-lucide="x" class="w-6 h-6"></i>
        </button>
      </div>

      <!-- 搜索和筛选区域 -->
      <div class="p-6 border-b border-gray-200 bg-gray-50">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <!-- 关键词搜索 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">搜索关键词</label>
            <div class="relative">
              <i data-lucide="search" class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"></i>
              <input
                v-model="searchKeyword"
                type="text"
                placeholder="输入关键词..."
                class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                @input="handleSearch"
              />
            </div>
          </div>

          <!-- 日期范围 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">开始日期</label>
            <input
              v-model="startDate"
              type="date"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              @change="handleDateFilter"
            />
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">结束日期</label>
            <input
              v-model="endDate"
              type="date"
              class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              @change="handleDateFilter"
            />
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="flex items-center justify-between mt-4">
          <div class="text-sm text-gray-600">
            共找到 {{ totalCount }} 条记录
          </div>
          <div class="flex space-x-2">
            <button
              @click="clearFilters"
              class="px-4 py-2 text-sm text-gray-600 hover:text-gray-800 transition-colors"
            >
              清除筛选
            </button>
            <button
              @click="refreshData"
              :disabled="loading"
              class="px-4 py-2 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50"
            >
              {{ loading ? '刷新中...' : '刷新' }}
            </button>
          </div>
        </div>
      </div>

      <!-- 消息列表 -->
      <div class="flex-1 overflow-y-auto p-6">
        <div v-if="loading" class="text-center py-8">
          <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
          <p class="mt-2 text-gray-600">加载中...</p>
        </div>

        <div v-else-if="messages.length === 0" class="text-center py-8 text-gray-500">
          <i data-lucide="message-circle" class="w-12 h-12 mx-auto mb-4 text-gray-300"></i>
          <p>暂无聊天记录</p>
        </div>

        <div v-else class="space-y-4">
          <div
            v-for="message in messages"
            :key="message.id"
            class="bg-gray-50 rounded-lg p-4 hover:bg-gray-100 transition-colors"
          >
            <div class="flex items-start justify-between">
              <div class="flex-1">
                <div class="flex items-center space-x-2 mb-2">
                  <span 
                    class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium"
                    :class="message.sender === 'user' ? 'bg-blue-100 text-blue-800' : 'bg-green-100 text-green-800'"
                  >
                    {{ message.sender === 'user' ? '我' : '开开' }}
                  </span>
                  <span class="text-xs text-gray-500">
                    {{ formatDateTime(message.createTime) }}
                  </span>
                </div>
                <p class="text-gray-900 leading-relaxed">{{ message.content }}</p>
                <div v-if="message.aiReply" class="mt-2 p-3 bg-white rounded border-l-4 border-green-400">
                  <p class="text-sm text-gray-700">{{ message.aiReply }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="totalPages > 1" class="p-6 border-t border-gray-200">
        <div class="flex items-center justify-between">
          <div class="text-sm text-gray-600">
            第 {{ currentPage }} 页，共 {{ totalPages }} 页
          </div>
          <div class="flex space-x-2">
            <button
              @click="goToPage(currentPage - 1)"
              :disabled="currentPage <= 1"
              class="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              上一页
            </button>
            <button
              @click="goToPage(currentPage + 1)"
              :disabled="currentPage >= totalPages"
              class="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              下一页
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import MessageService, { type MessageResponse, type PageResult } from '@/services/message'

interface Props {
  visible: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'close'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const loading = ref(false)
const messages = ref<MessageResponse[]>([])
const searchKeyword = ref('')
const startDate = ref('')
const endDate = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const totalCount = ref(0)
const totalPages = computed(() => Math.ceil(totalCount.value / pageSize.value))

// 搜索防抖
let searchTimeout: NodeJS.Timeout | null = null

// 方法
const handleClose = () => {
  emit('update:visible', false)
  emit('close')
}

const loadMessages = async () => {
  try {
    loading.value = true
    
    if (searchKeyword.value.trim()) {
      // 搜索模式
      const searchResult = await MessageService.searchUserMessages({
        keyword: searchKeyword.value.trim(),
        limit: 100,
        startTime: startDate.value ? `${startDate.value} 00:00:00` : undefined,
        endTime: endDate.value ? `${endDate.value} 23:59:59` : undefined
      })
      messages.value = searchResult
      totalCount.value = searchResult.length
      currentPage.value = 1
    } else {
      // 分页模式
      const pageResult = await MessageService.getUserMessages(currentPage.value, pageSize.value)
      messages.value = pageResult.records
      totalCount.value = pageResult.total
    }
  } catch (error) {
    console.error('加载消息失败:', error)
    ElMessage.error('加载聊天记录失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  if (searchTimeout) {
    clearTimeout(searchTimeout)
  }
  searchTimeout = setTimeout(() => {
    currentPage.value = 1
    loadMessages()
  }, 500)
}

const handleDateFilter = () => {
  currentPage.value = 1
  loadMessages()
}

const clearFilters = () => {
  searchKeyword.value = ''
  startDate.value = ''
  endDate.value = ''
  currentPage.value = 1
  loadMessages()
}

const refreshData = () => {
  loadMessages()
}

const goToPage = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    loadMessages()
  }
}

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 监听弹框显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    loadMessages()
    // 初始化图标
    setTimeout(() => {
      if (window.lucide) {
        window.lucide.createIcons()
      }
    }, 100)
  }
})

onMounted(() => {
  if (window.lucide) {
    window.lucide.createIcons()
  }
})
</script>

<style scoped>
/* 自定义滚动条 */
.overflow-y-auto::-webkit-scrollbar {
  width: 6px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
