<script setup lang="ts">
import type { ChatHistoryItem } from '@af-mobile-client-vue3/components/common/MateChat/types'
import { getHistories } from '@af-mobile-client-vue3/components/common/MateChat/apiService'
import { useChatHistoryCache } from '@af-mobile-client-vue3/components/common/MateChat/composables/useChatHistoryCache'
import { Empty, Icon, Loading, Popup, Popover as VanPopover } from 'vant'
import { ref } from 'vue'
import 'vant/es/popup/style'
import 'vant/es/empty/style'
import 'vant/es/loading/style'
import 'vant/es/icon/style'
import 'vant/es/popover/style'

interface Props {
  /**
   * 头部左侧 Logo 图片
   */
  logoImage: string
  /**
   * 头部标题文案
   */
  title: string
  /**
   * 历史对话弹层标题
   */
  historyTitle?: string
  /**
   * FastGPT 应用 ID
   */
  appId: string
  /**
   * FastGPT API Key
   */
  appKey: string
  /**
   * 是否显示标题
   */
  showTitle: boolean
}

interface SessionItem {
  chatId: string
  title: string
  lastTime: string
}

interface Emits {
  /**
   * 选择某条历史会话
   */
  (e: 'selectSession', session: SessionItem): void
  /**
   * 新建对话
   */
  (e: 'newConversation'): void
}

const props = withDefaults(defineProps<Props>(), {
  historyTitle: '对话历史',
})

const emit = defineEmits<Emits>()

const showHistory = ref(false)
const isLoading = ref(false)
const sessionList = ref<SessionItem[]>([])
const showMenu = ref(false)

const menuActions: { text: string, key: 'new' | 'history', icon: string }[] = [
  { text: '新对话', key: 'new', icon: 'add-o' },
  { text: '历史对话', key: 'history', icon: 'clock-o' },
]

// 使用历史会话缓存
const { getCachedHistory, setCachedHistory } = useChatHistoryCache()

function handleOpenHistory() {
  showHistory.value = true
  fetchSessions()
}

function handleSelectSession(session: SessionItem) {
  emit('selectSession', session)
  showHistory.value = false
}

/**
 * 处理下拉菜单点击
 */
function handleMenuSelect(action: { text: string, key: 'new' | 'history', icon?: string }) {
  showMenu.value = false
  if (action.key === 'new') {
    emit('newConversation')
    return
  }
  if (action.key === 'history') {
    handleOpenHistory()
  }
}

/**
 * 格式化时间字符串为日期时间字符串
 */
function formatDateTime(timeString: string): string {
  try {
    const date = new Date(timeString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}`
  }
  catch {
    return timeString
  }
}

/**
 * 将接口返回的历史会话数据转换为组件需要的格式
 */
function transformHistoryItem(item: ChatHistoryItem): SessionItem {
  return {
    chatId: item.chatId || '',
    title: item.title || item.customTitle || '未命名会话',
    lastTime: item.updateTime ? formatDateTime(item.updateTime) : '',
  }
}

async function fetchSessions() {
  // 先检查缓存
  const cachedList = getCachedHistory(props.appId, props.appKey)
  if (cachedList) {
    // 使用缓存数据
    sessionList.value = cachedList.map(transformHistoryItem)
    return
  }

  // 缓存不存在或已过期，从服务器获取
  isLoading.value = true
  try {
    const response = await getHistories(props.appId, props.appKey, 0, 5)

    // 转换数据格式
    if (response.data?.list && Array.isArray(response.data.list)) {
      // 缓存数据
      setCachedHistory(props.appId, props.appKey, response.data.list)
      sessionList.value = response.data.list.map(transformHistoryItem)
    }
    else {
      sessionList.value = []
      // 缓存空数组，避免重复请求
      setCachedHistory(props.appId, props.appKey, [])
    }
  }
  catch (error) {
    console.error('获取历史会话失败:', error)
    sessionList.value = []
  }
  finally {
    isLoading.value = false
  }
}
</script>

<template>
  <div class="matechat-header-wrapper">
    <McHeader
      :logo-img="showTitle ? props.logoImage : ''"
      :title="showTitle ? props.title : ''"
      :logo-clickable="false"
    >
      <template #operationArea>
        <VanPopover
          v-model:show="showMenu"
          placement="bottom-end"
          :actions="menuActions"
          @select="handleMenuSelect"
        >
          <template #reference>
            <div class="matechat-header-history-btn">
              <Icon name="ellipsis" size="16" />
            </div>
          </template>
        </VanPopover>
      </template>
    </McHeader>

    <Popup
      v-model:show="showHistory"
      position="center"
      round
      :overlay="true"
      class="matechat-history-popup"
    >
      <div class="matechat-history-card">
        <div class="matechat-history-card__header">
          <span class="matechat-history-card__title">
            {{ props.historyTitle }}
          </span>
        </div>
        <div class="matechat-history-card__content">
          <div v-if="isLoading" class="matechat-history-card__loading">
            <Loading size="24px" />
          </div>
          <template v-else>
            <div
              v-if="sessionList.length"
              class="matechat-history-card__list"
            >
              <div
                v-for="session in sessionList"
                :key="session.chatId"
                class="matechat-history-card__item"
                @click="handleSelectSession(session)"
              >
                <div class="matechat-history-card__item-title">
                  {{ session.title }}
                </div>
                <div class="matechat-history-card__item-time">
                  {{ session.lastTime }}
                </div>
              </div>
            </div>
            <div v-else class="matechat-history-card__empty">
              <Empty description="无数据" />
            </div>
          </template>
        </div>
      </div>
    </Popup>
  </div>
</template>

<style scoped lang="less">
.matechat-header-wrapper {
  position: relative;
}

.matechat-header-history-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 8px;
  background-color: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(0, 0, 0, 0.08);
  box-shadow: 0 1px 3px rgba(15, 23, 42, 0.12);
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    background-color: #ffffff;
    transform: translateY(-0.5px);
    box-shadow: 0 2px 6px rgba(15, 23, 42, 0.16);
  }
}

.matechat-history-popup {
  .matechat-history-card {
    width: 320px;
    max-width: 80vw;
    background-color: #ffffff;
    box-shadow: 0 12px 32px rgba(0, 0, 0, 0.15);
    padding: 16px 16px 12px;
    box-sizing: border-box;

    &__header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;
    }

    &__title {
      font-size: 16px;
      font-weight: 600;
      color: #252b3a;
    }

    &__content {
      min-height: 120px;
      max-height: 260px;
      overflow: auto;
    }

    &__loading {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 24px 0;
    }

    &__list {
      display: flex;
      flex-direction: column;
      gap: 8px;
    }

    &__item {
      padding: 10px 8px;
      border-radius: 0;
      cursor: pointer;
      transition: all 0.2s ease;

      &:hover {
        background-color: #f5f6f9;
      }
    }

    &__item-title {
      font-size: 14px;
      color: #252b3a;
      margin-bottom: 2px;
    }

    &__item-time {
      font-size: 12px;
      color: #a0a4af;
    }

    &__empty {
      padding: 16px 0 8px;

      :deep(.van-empty__image) {
        width: 80px;
        height: 80px;
      }

      :deep(.van-empty__description) {
        font-size: 13px;
        color: #a0a4af;
      }
    }
  }
}
</style>
