<template>
  <div class="page">
    <el-card class="mb-12">
      <div class="filters">
        <el-select
          v-model="filters.site_id"
          placeholder="中心"
          clearable
          filterable
          style="width: 200px"
          @change="loadSubjects"
        >
          <el-option v-for="s in sites" :key="s.id" :label="s.name || s.id" :value="s.id" />
        </el-select>
        <el-select v-model="filters.status" placeholder="状态" clearable @change="loadSubjects">
          <el-option v-for="s in statuses" :key="s" :label="statusLabel(s)" :value="s" />
        </el-select>
        <div class="spacer" />
        <el-button type="primary" v-if="canEdit" @click="showForm = true">新增受试者</el-button>
      </div>
    </el-card>

    <el-card>
      <el-table :data="subjects" v-loading="loading" style="width: 100%" @row-click="goDetail">
        <el-table-column prop="subject_no" label="受试者编号" />
        <el-table-column prop="site_id" label="中心">
          <template #default="scope">
            {{ siteName(scope.row.site_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag>{{ statusLabel(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="screening_date" label="筛选日期" width="140" />
        <el-table-column prop="enrollment_date" label="入组日期" width="140" />
      </el-table>
      <el-pagination
        class="pagination"
        layout="prev, pager, next"
        :page-size="pageSize"
        :current-page="page"
        :total="total"
        @current-change="onPageChange"
      />
    </el-card>

    <SubjectForm v-model="showForm" :sites="sites" @success="loadSubjects" />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { fetchSubjects } from "../api/subjects";
import { fetchSites } from "../api/sites";
import { useStudyStore } from "../store/study";
import { useAuthStore } from "../store/auth";
import SubjectForm from "../components/SubjectForm.vue";

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

const subjects = ref<any[]>([]);
const sites = ref<any[]>([]);
const loading = ref(false);
const total = ref(0);
const page = ref(1);
const pageSize = 10;
const siteMap = computed(() =>
  sites.value.reduce<Record<string, string>>((acc, cur) => {
    acc[cur.id] = cur.name || cur.id;
    return acc;
  }, {})
);

const statuses = ["SCREENING", "ENROLLED", "COMPLETED", "DROPPED"];

const filters = ref({
  site_id: "",
  status: "",
});

const showForm = ref(false);

const canEdit = computed(() => {
  const role = auth.user?.role;
  return role === "ADMIN" || role === "PM" || role === "CRA";
});

const loadSubjects = async () => {
  if (!study.currentStudy) return;
  loading.value = true;
  try {
    const params: Record<string, any> = {
      skip: (page.value - 1) * pageSize,
      limit: pageSize,
    };
    if (filters.value.site_id) params.site_id = filters.value.site_id;
    if (filters.value.status) params.status = filters.value.status;
    const { data } = await fetchSubjects(study.currentStudy.id, params);
    if (Array.isArray(data)) {
      subjects.value = data;
      total.value = data.length;
    } else {
      subjects.value = data.items || [];
      total.value = data.total || subjects.value.length;
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "受试者加载失败");
  } finally {
    loading.value = false;
  }
};

const onPageChange = (p: number) => {
  page.value = p;
  loadSubjects();
};

const goDetail = (row: any) => {
  router.push(`/study/subjects/${row.id}`);
};

const loadSites = async () => {
  if (!study.currentStudy) return;
  try {
    const { data } = await fetchSites(study.currentStudy.id);
    sites.value = data.items || data;
  } catch {
    // ignore
  }
};

onMounted(async () => {
  if (!auth.user && auth.token) {
    await auth.fetchMe().catch(() => {});
  }
  await loadSites();
  loadSubjects();
});

const statusLabel = (v: string) =>
  ({
    SCREENING: "筛选中",
    ENROLLED: "已入组",
    COMPLETED: "已完成",
    DROPPED: "已脱落",
  }[v] || v);

const siteName = (id: string) => siteMap.value[id] || id || "-";
</script>

<style scoped>
.page {
  padding: 16px;
}
.filters {
  display: flex;
  gap: 8px;
  align-items: center;
}
.spacer {
  flex: 1;
}
.pagination {
  margin-top: 12px;
  text-align: right;
}
.mb-12 {
  margin-bottom: 12px;
}
</style>
