<template>
  <div class="page-container">
    <div class="page-header">
      <div class="header-info">
        <h1 class="page-title">受试者管理</h1>
        <p class="page-subtitle">查看与维护当前项目的所有受试者信息</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" v-if="canEdit" @click="showForm = true">
          <el-icon><Plus /></el-icon> 新增受试者
        </el-button>
      </div>
    </div>

    <el-card class="filter-card">
      <div class="filter-layout">
        <div class="filter-items">
          <div class="filter-item">
            <span class="filter-label">所属中心</span>
            <el-select
              v-model="filters.site_id"
              placeholder="全部中心"
              clearable
              filterable
              class="filter-select"
              @change="loadSubjects"
            >
              <el-option v-for="s in sites" :key="s.id" :label="s.name || s.id" :value="s.id" />
            </el-select>
          </div>
          <div class="filter-item">
            <span class="filter-label">当前状态</span>
            <el-select 
              v-model="filters.status" 
              placeholder="全部状态" 
              clearable 
              class="filter-select"
              @change="loadSubjects"
            >
              <el-option v-for="s in statuses" :key="s" :label="statusLabel(s)" :value="s" />
            </el-select>
          </div>
        </div>
        <div class="filter-reset">
          <el-button link @click="resetFilters">重置筛选</el-button>
        </div>
      </div>
    </el-card>

    <el-card class="table-card" v-loading="loading">
      <el-table :data="subjects" style="width: 100%" @row-click="goDetail" class="ctms-table">
        <el-table-column prop="subject_no" label="受试者编号" min-width="120">
          <template #default="scope">
            <span class="subject-no">{{ scope.row.subject_no }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="site_id" label="中心名称" min-width="180">
          <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 :type="statusTagType(scope.row.status)" size="small">
              {{ 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-column label="操作" width="100" fixed="right">
          <template #default>
            <el-button link type="primary">详细资料</el-button>
          </template>
        </el-table-column>
        
        <template #empty>
          <div class="empty-state">
            <el-icon class="empty-icon"><Document /></el-icon>
            <p>暂无符合条件的受试者</p>
          </div>
        </template>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, prev, pager, next, sizes"
          :page-size="pageSize"
          :current-page="page"
          :total="total"
          @current-change="onPageChange"
        />
      </div>
    </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 { Plus, Document } from "@element-plus/icons-vue";
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 resetFilters = () => {
  filters.value = { site_id: "", status: "" };
  loadSubjects();
};

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 statusTagType = (v: string) => {
  const map: Record<string, string> = {
    SCREENING: "info",
    ENROLLED: "warning",
    COMPLETED: "success",
    DROPPED: "danger",
  };
  return map[v] || "info";
};

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

<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
  gap: var(--ctms-spacing-lg);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: var(--ctms-text-main);
  margin: 0;
}

.page-subtitle {
  font-size: 14px;
  color: var(--ctms-text-secondary);
  margin-top: 4px;
}

.filter-card {
  margin-bottom: 0;
}

.filter-layout {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.filter-items {
  display: flex;
  gap: 24px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-label {
  font-size: 13px;
  font-weight: 500;
  color: var(--ctms-text-regular);
}

.filter-select {
  width: 200px;
}

.table-card {
  flex: 1;
}

.subject-no {
  font-weight: 600;
  color: var(--ctms-primary);
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.empty-state {
  padding: 40px 0;
  color: var(--ctms-text-disabled);
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

:deep(.el-table__row) {
  cursor: pointer;
}
</style>
