<template>
  <div class="page">
    <el-card class="mb-12">
      <div class="actions">
        <h3>伦理与启动管理</h3>
        <PermissionAction action="milestone.create">
          <el-button type="primary" @click="openCreate">新建节点</el-button>
        </PermissionAction>
      </div>
    </el-card>

    <el-card>
      <el-table :data="milestones" v-loading="loading" style="width: 100%" @row-click="goDetail">
        <el-table-column prop="name" label="名称" min-width="160">
          <template #default="scope">
            <el-link type="primary" @click.stop="goDetail(scope.row)">{{ scope.row.name || "—" }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="160">
          <template #default="scope">
            {{ typeLabel(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column label="中心" width="180">
          <template #default="scope">
            {{ siteName(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="负责人" width="160">
          <template #default="scope">
            {{ ownerName(scope.row.owner_id) }}
          </template>
        </el-table-column>
        <el-table-column label="计划日期" width="140">
          <template #default="scope">
            {{ displayDate(scope.row.planned_date) }}
          </template>
        </el-table-column>
        <el-table-column label="实际日期" width="140">
          <template #default="scope">
            {{ displayDate(scope.row.actual_date) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="140">
          <template #default="scope">
            <el-tag :type="statusColor(scope.row.status)">
              {{ statusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <PermissionAction action="milestone.create">
              <el-button type="primary" link size="small" @click.stop="openEdit(scope.row)">编辑</el-button>
            </PermissionAction>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <MilestoneForm
      v-model="showForm"
      :milestone="editingMilestone"
      :sites="sites"
      :members="members"
      @success="loadMilestones"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { fetchMilestones } from "../api/milestones";
import { fetchSites } from "../api/sites";
import { listMembers } from "../api/members";
import { useStudyStore } from "../store/study";
import PermissionAction from "../components/PermissionAction.vue";
import MilestoneForm from "../components/MilestoneForm.vue";
import {
  getMilestoneStatusColor,
  getMilestoneStatusLabel,
  getMilestoneTypeLabel,
} from "../dictionaries/milestone.dict";
import { displayDate, displayUser } from "../utils/display";

const study = useStudyStore();
const router = useRouter();

const milestones = ref<any[]>([]);
const sites = ref<any[]>([]);
const members = ref<any[]>([]);
const loading = ref(false);
const showForm = ref(false);
const editingMilestone = ref<any | null>(null);

const loadMilestones = async () => {
  if (!study.currentStudy) return;
  loading.value = true;
  try {
    const { data } = await fetchMilestones(study.currentStudy.id);
    milestones.value = data.items || data;
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "节点加载失败");
  } finally {
    loading.value = false;
  }
};

const loadSites = async () => {
  if (!study.currentStudy) return;
  try {
    const { data } = await fetchSites(study.currentStudy.id, { limit: 500 });
    sites.value = (data as any).items || data || [];
  } catch {
    sites.value = [];
  }
};

const loadMembers = async () => {
  if (!study.currentStudy) return;
  try {
    const { data } = await listMembers(study.currentStudy.id, { limit: 500 });
    members.value = Array.isArray(data) ? data : data.items || [];
  } catch {
    members.value = [];
  }
};

const openCreate = () => {
  editingMilestone.value = null;
  showForm.value = true;
};

const openEdit = (row: any) => {
  editingMilestone.value = row;
  showForm.value = true;
};

onMounted(() => {
  loadMilestones();
  loadSites();
  loadMembers();
});

const typeLabel = (v: string) => getMilestoneTypeLabel(v);
const statusLabel = (v: string) => getMilestoneStatusLabel(v);
const statusColor = (v: string) => getMilestoneStatusColor(v);

const memberMap = computed(() =>
  members.value.reduce<Record<string, string>>((acc, cur) => {
    const username =
      cur?.user?.full_name ||
      cur?.user?.display_name ||
      cur?.user?.username ||
      cur?.user?.email ||
      cur?.username ||
      cur?.email;
    if (cur?.user_id) acc[cur.user_id] = username || cur.user_id;
    return acc;
  }, {})
);

const siteName = (row: any) => {
  if (row?.site?.name) return row.site.name;
  const id = row?.site_id || row?.center_id;
  const name = id ? sites.value.find((s: any) => s.id === id)?.name : row?.site_name;
  return name || "—";
};

const ownerName = (ownerId: string) => {
  const fromPayload = milestones.value.find((m) => m.owner_id === ownerId)?.owner;
  return (
    fromPayload?.full_name ||
    fromPayload?.display_name ||
    fromPayload?.username ||
    fromPayload?.email ||
    displayUser(ownerId, { members: memberMap.value })
  );
};

const goDetail = (row: any) => {
  if (!row?.id) return;
  router.push({ name: "StudyMilestoneDetail", params: { milestoneId: row.id } });
};
</script>

<style scoped>
.page {
  padding: 16px;
}
.actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.mb-12 {
  margin-bottom: 12px;
}
</style>
