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

import { api } from "../services/api";
import type { AdminUserDetail } from "../types/api";

const props = defineProps<{ modelValue: boolean; userId: number | null }>();
defineEmits<{ "update:modelValue": [value: boolean] }>();

const detail = ref<AdminUserDetail | null>(null);
const loading = ref(false);
const reportGenerating = ref("");
const settlementRetrying = ref<number | null>(null);

watch(
  () => [props.modelValue, props.userId] as const,
  ([open, userId]) => {
    if (open && userId) void loadDetail(userId);
  },
  { immediate: true },
);

async function loadDetail(userId = props.userId) {
  if (!userId) return;
  loading.value = true;
  try {
    detail.value = await api.userDetail(userId);
  } finally {
    loading.value = false;
  }
}

async function generateReport(type: "weekly" | "monthly" | "stage") {
  if (!detail.value) return;
  reportGenerating.value = type;
  try {
    await api.generateUserReport(detail.value.user.id, { reportType: type });
    await loadDetail(detail.value.user.id);
    ElMessage.success("报告任务已进入后台队列，不会阻塞聊天服务");
  } catch (error) {
    ElMessage.error(error instanceof Error ? error.message : "报告生成失败");
  } finally {
    reportGenerating.value = "";
  }
}

async function retryTopicSettlement(topicId: number) {
  if (!detail.value || settlementRetrying.value !== null) return;
  settlementRetrying.value = topicId;
  try {
    await api.retryTopicSettlement(detail.value.user.id, topicId);
    await loadDetail(detail.value.user.id);
    ElMessage.success("主题沉淀任务已重新进入后台队列");
  } catch (error) {
    ElMessage.error(
      error instanceof Error ? error.message : "主题沉淀重试失败",
    );
  } finally {
    settlementRetrying.value = null;
  }
}

function reportStatusLabel(status: string) {
  return (
    (
      {
        pending: "等待生成",
        running: "生成中",
        success: "已完成",
        fallback: "已降级沉淀",
        empty: "暂无沉淀",
        failed: "生成失败",
      } as Record<string, string>
    )[status] || status
  );
}

function formatMoney(value?: number | null, currency = "CNY") {
  if (typeof value !== "number") return "-";
  if (currency === "MIXED") return "多币种，见明细";
  return `${currency || "CNY"} ${value.toFixed(6)}`;
}
</script>

<template>
  <el-drawer
    :model-value="modelValue"
    size="860px"
    title="用户详情"
    @update:model-value="$emit('update:modelValue', $event)"
  >
    <div v-loading="loading" class="user-detail-body">
      <template v-if="detail">
        <section class="user-detail-head">
          <div>
            <h3>
              {{
                detail.user.name || detail.user.nickname || detail.user.phone
              }}
            </h3>
            <p>
              {{ detail.user.phone }} ·
              {{ detail.user.status === 1 ? "已启用" : "已停用" }}
            </p>
          </div>
          <div class="user-detail-tags">
            <el-tag
              v-if="detail.metrics.isHighFrequency"
              type="warning"
              effect="plain"
              >高频使用</el-tag
            >
            <el-tag v-if="detail.metrics.isInactive" type="info" effect="plain"
              >近30天低活跃</el-tag
            >
            <el-tag type="success" effect="plain">{{
              detail.user.entitlement?.name || "默认基础版"
            }}</el-tag>
          </div>
        </section>

        <section class="chat-summary user-metric-grid">
          <div>
            <span>本月主题</span
            ><strong
              >{{ detail.metrics.monthTopics }}/{{
                detail.user.entitlement?.monthlyTopicLimit ?? "不限"
              }}</strong
            >
          </div>
          <div>
            <span>近30天活跃</span
            ><strong>{{ detail.metrics.recentActiveDays }} 天</strong>
          </div>
          <div>
            <span>总会话</span
            ><strong>{{ detail.metrics.totalSessions }}</strong>
          </div>
          <div>
            <span>总消息</span
            ><strong>{{ detail.metrics.totalMessages }}</strong>
          </div>
          <div>
            <span>主题总数</span
            ><strong>{{ detail.metrics.totalTopics }}</strong>
          </div>
          <div>
            <span>AI 请求</span
            ><strong>{{ detail.metrics.aiRequestCount }}</strong>
          </div>
          <div>
            <span>总 Token</span
            ><strong>{{ detail.metrics.totalToken }}</strong>
          </div>
          <div>
            <span>估算成本</span
            ><strong>{{
              formatMoney(
                detail.metrics.estimatedCost,
                detail.metrics.costCurrency,
              )
            }}</strong>
          </div>
        </section>

        <section class="audit-detail-grid">
          <div>
            <span>权益有效期</span
            ><strong>{{
              detail.user.entitlement?.expiredAt ||
              detail.user.expiredAt ||
              "长期有效"
            }}</strong>
          </div>
          <div>
            <span>最近登录</span
            ><strong>{{ detail.user.lastLoginAt || "-" }}</strong>
          </div>
          <div>
            <span>最近发言</span
            ><strong>{{ detail.metrics.lastMessageAt || "-" }}</strong>
          </div>
          <div>
            <span>生成记录</span
            ><strong
              >求助卡 {{ detail.metrics.helpCardCount }} / 分享稿
              {{ detail.metrics.shareDraftCount }}</strong
            >
          </div>
        </section>

        <h3 class="detail-title">近期实修回顾</h3>
        <section v-if="detail.growthProfile" class="topic-summary-card">
          <pre>{{ detail.growthProfile.reviewText || "暂无近期回顾" }}</pre>
          <div
            v-if="detail.growthProfile.currentFocus"
            class="topic-summary-fields"
          >
            <p>
              <strong>近期关注</strong>{{ detail.growthProfile.currentFocus }}
            </p>
          </div>
        </section>
        <el-empty
          v-else
          description="该用户暂无新版近期实修回顾，将在下一次主题沉淀后生成"
          :image-size="64"
        />

        <section class="user-report-head">
          <div>
            <h3 class="detail-title">周期实修回顾</h3>
            <p>
              只基于本周期主题摘要回顾近期关注，不评价成长结果；同一周期重复生成会覆盖旧版本。
            </p>
          </div>
          <div class="user-report-actions">
            <el-button size="small" @click="loadDetail()">刷新状态</el-button>
            <el-button
              size="small"
              :loading="reportGenerating === 'weekly'"
              @click="generateReport('weekly')"
              >生成周报</el-button
            >
            <el-button
              size="small"
              :loading="reportGenerating === 'monthly'"
              @click="generateReport('monthly')"
              >生成月报</el-button
            >
            <el-button
              size="small"
              :loading="reportGenerating === 'stage'"
              @click="generateReport('stage')"
              >生成阶段回顾</el-button
            >
          </div>
        </section>
        <el-collapse
          v-if="detail.recentReports.length"
          class="topic-summary-collapse"
        >
          <el-collapse-item
            v-for="report in detail.recentReports"
            :key="report.id"
            :title="`#${report.id} ${report.title} / ${reportStatusLabel(report.status)}`"
          >
            <section class="topic-summary-card">
              <div class="topic-summary-meta">
                <span>状态：{{ reportStatusLabel(report.status) }}</span
                ><span>类型：{{ report.reportTypeLabel }}</span>
                <span
                  >周期：{{ report.periodStart }} 至
                  {{ report.periodEnd }}</span
                ><span>来源主题：{{ report.sourceTopicIds.length }}</span>
                <span>来源摘要：{{ report.sourceSummaryIds.length }}</span
                ><span>模型：{{ report.modelName || "-" }}</span>
                <span
                  >触发方式：{{
                    report.generatedBy.startsWith("schedule:")
                      ? "系统定时"
                      : "管理员手动"
                  }}</span
                >
                <span
                  >执行次数：{{ report.attemptCount }}/{{
                    report.maxAttempts
                  }}</span
                >
                <span v-if="report.nextRunAt"
                  >下次执行：{{ report.nextRunAt }}</span
                ><span>完成时间：{{ report.finishedAt || "-" }}</span>
              </div>
              <p v-if="report.errorMessage" class="report-error">
                最近错误：{{ report.errorMessage }}
              </p>
              <pre v-if="report.content">{{ report.content }}</pre>
              <p
                v-else-if="
                  report.status === 'pending' || report.status === 'running'
                "
                class="report-pending"
              >
                后台正在生成报告，可以先关闭抽屉，稍后回来查看。
              </p>
            </section>
          </el-collapse-item>
        </el-collapse>
        <el-empty v-else description="该用户暂无周期报告" :image-size="64" />

        <h3 class="detail-title">最近主题</h3>
        <el-collapse
          v-if="detail.recentTopics.length"
          class="topic-summary-collapse"
        >
          <el-collapse-item
            v-for="topic in detail.recentTopics"
            :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.updatedAt }}</span>
              </div>
              <template v-if="topic.summary">
                <div class="topic-summary-meta">
                  <span
                    >沉淀状态：{{
                      reportStatusLabel(topic.summary.status)
                    }}</span
                  >
                  <span
                    >执行次数：{{ topic.summary.attemptCount }}/{{
                      topic.summary.maxAttempts
                    }}</span
                  >
                  <span v-if="topic.summary.lastStartedAt"
                    >开始执行：{{ topic.summary.lastStartedAt }}</span
                  >
                  <span v-if="topic.summary.finishedAt"
                    >完成：{{ topic.summary.finishedAt }}</span
                  >
                </div>
                <p v-if="topic.summary.errorMessage" class="report-error">
                  最近错误：{{ topic.summary.errorMessage }}
                </p>
                <pre
                  v-if="
                    topic.summary.status === 'success' ||
                    topic.summary.status === 'fallback'
                  "
                  >{{ topic.summary.summary }}</pre
                >
                <p
                  v-else-if="
                    topic.summary.status === 'pending' ||
                    topic.summary.status === 'running'
                  "
                  class="report-pending"
                >
                  主题已结束，摘要和近期实修回顾正在后台生成。
                </p>
                <div
                  v-if="
                    topic.summary.status === 'success' ||
                    topic.summary.status === 'fallback'
                  "
                  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>
                <el-button
                  v-if="topic.summary.status === 'failed'"
                  size="small"
                  type="primary"
                  :loading="settlementRetrying === topic.id"
                  @click="retryTopicSettlement(topic.id)"
                  >重新沉淀</el-button
                >
              </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.recentHelpCards.length }}）
        </h3>
        <el-collapse
          v-if="detail.recentHelpCards.length"
          class="topic-summary-collapse"
        >
          <el-collapse-item
            v-for="card in detail.recentHelpCards"
            :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.recentShareDrafts.length }}）
        </h3>
        <el-collapse
          v-if="detail.recentShareDrafts.length"
          class="topic-summary-collapse"
        >
          <el-collapse-item
            v-for="draft in detail.recentShareDrafts"
            :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"
        />
      </template>
    </div>
  </el-drawer>
</template>
