<template>
  <div class="study-home-container" v-if="study.currentStudy">
    <!-- 概览头部 -->
    <div class="home-header">
      <div class="header-content">
        <h1 class="welcome-title">项目概览</h1>
        <p class="study-info">
          <span class="study-name">{{ study.currentStudy.name }}</span>
          <span class="study-divider">/</span>
          <span class="study-code">{{ study.currentStudy.code }}</span>
        </p>
      </div>
      <div class="header-meta">
        <el-tag effect="plain" class="role-tag">我的角色: {{ auth.user?.role }}</el-tag>
      </div>
    </div>

    <!-- 数据指标网格 -->
    <div class="stats-grid">
      <div class="stats-item">
        <KpiCard
          title="节点完成率"
          :value="progress?.milestones_done ?? 0"
          :unit="` / ${progress?.milestones_total ?? 0}`"
          :subtext="milestoneCompletionRate"
          :loading="loading.progress"
          :icon="List"
        />
      </div>
      <div class="stats-item">
        <KpiCard 
          title="逾期 AE" 
          :value="overdueAes" 
          unit="例"
          subtext="需尽快跟进处理"
          :loading="loading.overdueAes" 
          :icon="Warning"
        />
      </div>
      <div class="stats-item">
        <KpiCard 
          title="逾期数据问题" 
          :value="overdueQueries" 
          unit="项"
          subtext="严禁滞留超过 48h"
          :loading="loading.overdueQueries" 
          :icon="QuestionFilled"
        />
      </div>
      <div class="stats-item">
        <KpiCard
          title="费用总额"
          :value="formatAmount(financeSummary?.total_amount ?? 0)"
          :subtext="`累计已支付：¥${formatAmount(financeSummary?.paid_amount ?? 0)}`"
          :loading="loading.finance"
          :icon="Money"
        />
      </div>
    </div>

    <!-- 通知/警告 -->
    <el-alert
      v-if="overdueAes > 0 || overdueQueries > 0"
      type="warning"
      title="存在逾期未处理事项，请及时关注项目的合规性与进度。"
      show-icon
      :closable="false"
      class="home-alert"
    />
    <el-alert
      v-else
      type="success"
      title="项目运行状态良好，所有关键指标均在可控范围内。"
      show-icon
      :closable="false"
      class="home-alert"
    />

    <!-- 快捷模块 -->
    <div class="quick-nav-section">
      <QuickActions />
    </div>
  </div>
  
  <div v-else class="empty-state-container">
    <el-empty description="请先在顶部选择一个当前项目" />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { useAuthStore } from "../store/auth";
import { useStudyStore } from "../store/study";
import { fetchFinanceSummary, fetchOverdueAesCount, fetchOverdueQueriesCount, fetchProgress } from "../api/dashboard";
import KpiCard from "../components/KpiCard.vue";
import QuickActions from "../components/QuickActions.vue";
import { List, Warning, QuestionFilled, Money } from "@element-plus/icons-vue";

const auth = useAuthStore();
const study = useStudyStore();

const progress = ref<any>(null);
const financeSummary = ref<any>(null);
const overdueAes = ref<number>(0);
const overdueQueries = ref<number>(0);

const loading = ref({
  progress: false,
  finance: false,
  overdueAes: false,
  overdueQueries: false,
});

const milestoneCompletionRate = computed(() => {
  const total = progress.value?.milestones_total ?? 0;
  if (!total) return "暂无节点";
  const rate = (progress.value?.milestones_done ?? 0) / total;
  return `总体进度: ${(rate * 100).toFixed(0)}%`;
});

const formatAmount = (val: number) => {
  return new Intl.NumberFormat('zh-CN', { minimumFractionDigits: 2 }).format(val);
};

const loadData = async () => {
  const studyId = study.currentStudy?.id;
  if (!studyId) return;

  loading.value.progress = true;
  loading.value.finance = true;
  loading.value.overdueAes = true;
  loading.value.overdueQueries = true;

  try {
    const [pRes, fRes, aesRes, dqRes] = await Promise.allSettled([
      fetchProgress(studyId),
      fetchFinanceSummary(studyId),
      fetchOverdueAesCount(studyId),
      fetchOverdueQueriesCount(studyId),
    ]);

    if (pRes.status === "fulfilled") progress.value = pRes.value.data;
    if (fRes.status === "fulfilled") financeSummary.value = fRes.value.data;
    if (aesRes.status === "fulfilled") overdueAes.value = aesRes.value.data?.total ?? 0;
    if (dqRes.status === "fulfilled") overdueQueries.value = dqRes.value.data?.total ?? 0;
  } finally {
    loading.value.progress = false;
    loading.value.finance = false;
    loading.value.overdueAes = false;
    loading.value.overdueQueries = false;
  }
};

const resetData = () => {
  progress.value = null;
  financeSummary.value = null;
  overdueAes.value = 0;
  overdueQueries.value = 0;
};

onMounted(() => {
  loadData();
});

watch(
  () => study.currentStudy?.id,
  () => {
    resetData();
    loadData();
  }
);
</script>

<style scoped>
.study-home-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.home-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  padding-bottom: 8px;
}

.welcome-title {
  font-size: 28px;
  font-weight: 700;
  color: var(--ctms-text-main);
  margin: 0;
}

.study-info {
  margin: 8px 0 0;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 15px;
  color: var(--ctms-text-secondary);
}

.study-divider {
  opacity: 0.3;
}

.role-tag {
  background-color: #fff;
  border-color: var(--ctms-primary-hover);
  color: var(--ctms-primary);
  font-weight: 500;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.home-alert {
  border: none;
  border-left: 4px solid;
  border-radius: 4px;
}

.quick-nav-section {
  margin-top: 8px;
}

.empty-state-container {
  padding-top: 100px;
}

@media (max-width: 1200px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
