<script setup lang="ts">
import { ElMessage } from "element-plus";
import { nextTick, reactive, ref, watch } from "vue";

import { api } from "../services/api";
import type { ChatDetail } from "../types/api";
import AdminPagination from "./AdminPagination.vue";

const props = defineProps<{ modelValue: boolean; sessionId: number | null }>();
const emit = defineEmits<{ "update:modelValue": [value: boolean] }>();
const detail = ref<ChatDetail | null>(null);
const loading = ref(false);
const messagesLoading = ref(false);
const bodyRef = ref<HTMLElement | null>(null);
const pager = reactive({ page: 1, pageSize: 20, total: 0 });

watch(
  () => [props.modelValue, props.sessionId] as const,
  async ([open, sessionId]) => {
    if (!open || !sessionId) return;
    detail.value = null;
    Object.assign(pager, { page: 1, total: 0 });
    await loadDetail(sessionId, 1, pager.pageSize);
  },
);

async function loadDetail(sessionId: number, page: number, pageSize: number) {
  loading.value = true;
  try {
    detail.value = await api.chatDetail(sessionId, {
      messagePage: page,
      messagePageSize: pageSize,
    });
    const messagePage = detail.value.messagesPage;
    Object.assign(pager, {
      page: messagePage?.page ?? page,
      pageSize: messagePage?.pageSize ?? pageSize,
      total: messagePage?.total ?? detail.value.messages.length,
    });
  } catch (error) {
    ElMessage.error(
      error instanceof Error ? error.message : "聊天详情加载失败",
    );
  } finally {
    loading.value = false;
  }
}

async function changeMessagePage(page: number, pageSize: number) {
  if (!props.sessionId || !detail.value) return;
  messagesLoading.value = true;
  try {
    const result = await api.chatMessages(props.sessionId, { page, pageSize });
    detail.value = {
      ...detail.value,
      messages: result.items,
      messagesPage: result,
    };
    Object.assign(pager, {
      page: result.page,
      pageSize: result.pageSize,
      total: result.total,
    });
    await nextTick();
    bodyRef.value?.scrollTo({ top: 0, behavior: "smooth" });
  } catch (error) {
    ElMessage.error(
      error instanceof Error ? error.message : "聊天消息加载失败",
    );
  } finally {
    messagesLoading.value = false;
  }
}
</script>

<template>
  <el-drawer
    :model-value="modelValue"
    size="760px"
    title="聊天详情"
    @update:model-value="emit('update:modelValue', $event)"
  >
    <div ref="bodyRef" v-loading="loading" class="chat-detail-body">
      <template v-if="detail">
        <section class="chat-summary">
          <div>
            <span>会话ID</span><strong>{{ detail.session.id }}</strong>
          </div>
          <div>
            <span>用户</span
            ><strong>{{ detail.session.userName || "-" }}</strong>
          </div>
          <div>
            <span>手机号</span
            ><strong>{{ detail.session.userPhone || "-" }}</strong>
          </div>
          <div>
            <span>消息数</span
            ><strong>{{ detail.session.messageCount }}</strong>
          </div>
        </section>
        <h3 class="detail-title">主题会话</h3>
        <el-collapse
          v-if="detail.topics?.length"
          class="topic-summary-collapse"
        >
          <el-collapse-item
            v-for="topic in detail.topics"
            :key="topic.id"
            :title="`#${topic.id} ${topic.title} / ${topic.status}`"
          >
            <section class="topic-summary-card">
              <div class="topic-summary-meta">
                <span>核心问题：{{ topic.coreQuestion }}</span
                ><span>消息数：{{ topic.messageCount }}</span
                ><span
                  >Token：{{ topic.tokenInput }}/{{ topic.tokenOutput }}</span
                ><span
                  >额度：{{ topic.quotaDeducted ? "已计入" : "不计入" }}</span
                ><span>开始：{{ topic.startedAt }}</span
                ><span>结束：{{ topic.endedAt || "-" }}</span>
              </div>
              <template v-if="topic.summary">
                <pre>{{ topic.summary.summary }}</pre>
                <div class="topic-summary-fields">
                  <p v-if="topic.summary.currentFocus">
                    <strong>本次关注</strong>{{ topic.summary.currentFocus }}
                  </p>
                  <p v-if="topic.summary.nextObservation">
                    <strong>可以继续留意</strong
                    >{{ topic.summary.nextObservation }}
                  </p>
                </div></template
              >
              <el-empty
                v-else
                description="该主题尚未沉淀摘要"
                :image-size="60"
              />
            </section>
          </el-collapse-item>
        </el-collapse>
        <el-empty v-else description="该会话暂无主题记录" :image-size="64" />
        <h3 class="detail-title">
          老师求助卡（{{ detail.helpCards?.length || 0 }}）
        </h3>
        <el-collapse
          v-if="detail.helpCards?.length"
          class="topic-summary-collapse"
          ><el-collapse-item
            v-for="card in detail.helpCards"
            :key="card.id"
            :title="`#${card.id} / 主题 #${card.topicSessionId} / ${card.copied ? '用户已复制' : '未复制'}`"
            ><section class="topic-summary-card">
              <div class="topic-summary-meta">
                <span>生成：{{ card.createdAt }}</span
                ><span>复制：{{ card.copiedAt || "-" }}</span
                ><span>来源：{{ card.source }}</span>
              </div>
              <pre>{{ card.content }}</pre>
            </section></el-collapse-item
          ></el-collapse
        >
        <el-empty
          v-else
          description="该会话暂无用户生成的求助卡"
          :image-size="64"
        />
        <h3 class="detail-title">
          班级分享稿（{{ detail.shareDrafts?.length || 0 }}）
        </h3>
        <el-collapse
          v-if="detail.shareDrafts?.length"
          class="topic-summary-collapse"
          ><el-collapse-item
            v-for="draft in detail.shareDrafts"
            :key="draft.id"
            :title="`#${draft.id} / 主题 #${draft.topicSessionId} / ${draft.copied ? '用户已复制' : '未复制'}`"
            ><section class="topic-summary-card">
              <div class="topic-summary-meta">
                <span>生成：{{ draft.createdAt }}</span
                ><span>复制：{{ draft.copiedAt || "-" }}</span
                ><span>来源：{{ draft.source }}</span>
              </div>
              <pre>{{ draft.content }}</pre>
            </section></el-collapse-item
          ></el-collapse
        >
        <el-empty
          v-else
          description="该会话暂无用户生成的班级分享稿"
          :image-size="64"
        />
        <h3 class="detail-title">完整对话</h3>
        <AdminPagination
          class="chat-detail-pagination top"
          :page="pager.page"
          :page-size="pager.pageSize"
          :total="pager.total"
          @change="changeMessagePage"
        />
        <section v-loading="messagesLoading" class="conversation-list">
          <article
            v-for="message in detail.messages"
            :key="message.id"
            class="conversation-message"
            :class="message.role"
          >
            <div class="message-meta">
              <strong>{{
                message.role === "user" ? "用户" : "大本营答疑助手"
              }}</strong
              ><span>{{ message.createdAt }}</span>
            </div>
            <pre>{{ message.content }}</pre>
            <div class="message-extra">
              <span>状态：{{ message.messageStatus }}</span
              ><span v-if="message.tokenInput"
                >输入 Token：{{ message.tokenInput }}</span
              ><span v-if="message.tokenOutput"
                >输出 Token：{{ message.tokenOutput }}</span
              ><span v-if="message.responseTimeMs"
                >耗时：{{ message.responseTimeMs }}ms</span
              >
            </div>
          </article>
        </section>
        <AdminPagination
          class="chat-detail-pagination"
          :page="pager.page"
          :page-size="pager.pageSize"
          :total="pager.total"
          @change="changeMessagePage"
        />
        <h3 class="detail-title">关联 AI 请求</h3>
        <el-collapse
          ><el-collapse-item
            v-for="log in detail.aiLogs"
            :key="log.id"
            :title="`请求 #${log.id} / ${log.status}`"
            ><div class="ai-log-grid">
              <span>模型：{{ log.modelName || "-" }}</span
              ><span>知识库：{{ log.knowledgeIds || "-" }}</span
              ><span>命中数：{{ log.retrieveCount }}</span
              ><span>Token：{{ log.totalToken || "-" }}</span
              ><span>耗时：{{ log.costMs || "-" }}ms</span
              ><span>时间：{{ log.createdAt }}</span>
            </div>
            <section
              v-if="log.retrievedChunks?.length"
              class="retrieval-chunks"
            >
              <article
                v-for="chunk in log.retrievedChunks"
                :key="`${log.id}-${chunk.index}`"
                class="retrieval-chunk"
              >
                <div class="chunk-head">
                  <strong
                    >#{{ chunk.index }}
                    {{ chunk.knowledgeName || "未知知识库" }}</strong
                  ><span>{{ chunk.title || "未命名片段" }}</span>
                </div>
                <pre>{{ chunk.content }}</pre>
                <a
                  v-if="chunk.sourceUrl"
                  :href="chunk.sourceUrl"
                  target="_blank"
                  rel="noreferrer"
                  >查看来源</a
                >
              </article>
            </section>
            <el-empty
              v-else
              description="本条请求未保存召回片段"
              :image-size="64"
            />
            <pre class="prompt-preview">{{
              log.prompt || "无 Prompt 记录"
            }}</pre>
            <p v-if="log.errorMessage" class="error-text">
              {{ log.errorMessage }}
            </p></el-collapse-item
          ></el-collapse
        >
      </template>
      <el-empty
        v-else-if="!loading"
        description="聊天详情加载失败或暂无数据"
        :image-size="80"
      />
    </div>
  </el-drawer>
</template>
