<template>
  <div class="ctms-page">
    <div class="ctms-page-header">
      <div>
        <h1 class="ctms-page-title">不良事件</h1>
      </div>
      <div class="ctms-page-actions">
        <el-button type="primary" v-if="canCreate" @click="showForm = true">新建不良事件</el-button>
      </div>
    </div>

    <el-card class="ctms-filter-card">
      <div class="ctms-filter-row">
        <div class="ctms-filter-item">
          <span class="ctms-filter-label">状态</span>
          <el-select v-model="filters.status" placeholder="全部" clearable @change="loadAes">
            <el-option v-for="s in statuses" :key="s" :label="statusLabel(s)" :value="s" />
          </el-select>
        </div>
        <div class="ctms-filter-item">
          <span class="ctms-filter-label">SAE</span>
          <el-select v-model="filters.seriousness" placeholder="全部" clearable @change="loadAes">
            <el-option v-for="s in seriousnessOptions" :key="s" :label="seriousnessLabel(s)" :value="s" />
          </el-select>
        </div>
        <div class="ctms-filter-item">
          <span class="ctms-filter-label">仅逾期</span>
          <el-switch v-model="filters.overdue" @change="loadAes" />
        </div>
        <div class="ctms-filter-spacer" />
      </div>
    </el-card>

    <el-card class="ctms-table-card">
      <el-table :data="aes" v-loading="loading" class="ctms-table" style="width: 100%" @row-click="goDetail">
        <el-table-column prop="term" label="事件" />
        <el-table-column label="受试者" width="200">
          <template #default="scope">
            {{ subjectMap[scope.row.subject_id] || scope.row.subject_id || "-" }}
          </template>
        </el-table-column>
        <el-table-column label="中心" width="200">
          <template #default="scope">
            {{ siteName(subjectSiteMap[scope.row.subject_id]) }}
          </template>
        </el-table-column>
        <el-table-column prop="seriousness" label="SAE" width="120">
          <template #default="scope">
            {{ seriousnessLabel(scope.row.seriousness) }}
          </template>
        </el-table-column>
        <el-table-column prop="severity" label="严重程度" width="140">
          <template #default="scope">
            {{ severityLabel(scope.row.severity) }}
          </template>
        </el-table-column>
        <el-table-column prop="onset_date" label="发生日期" width="140" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.is_overdue ? 'danger' : 'info'">{{ statusLabel(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="ctms-pagination"
        layout="prev, pager, next"
        :page-size="pageSize"
        :current-page="page"
        :total="total"
        @current-change="onPageChange"
      />
    </el-card>

    <AeForm v-model="showForm" :subjects="subjects" @success="loadAes" />
  </div>
</template>

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

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

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

const statuses = ["FOLLOW_UP", "CLOSED"];
const seriousnessOptions = ["SERIOUS", "NON_SERIOUS"];

const filters = ref({
  status: "",
  seriousness: "",
  overdue: false,
});

const showForm = ref(false);

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

const loadAes = async () => {
  if (!study.currentStudy) return;
  loading.value = true;
  try {
    const params: Record<string, any> = { skip: (page.value - 1) * pageSize, limit: pageSize };
    if (filters.value.status) params.status_filter = filters.value.status;
    if (filters.value.seriousness) params.seriousness = filters.value.seriousness;
    if (filters.value.overdue) params.overdue = true;
    const { data } = await fetchAes(study.currentStudy.id, params);
    const mapOverdue = (list: any[]) =>
      list.map((item) => ({
        ...item,
        is_overdue:
          item.is_overdue ??
          (item.report_due_date && item.status !== "CLOSED" && new Date() > new Date(item.report_due_date)),
      }));
    if (Array.isArray(data)) {
      aes.value = mapOverdue(data);
      total.value = data.length;
    } else {
      const items = data.items || [];
      aes.value = mapOverdue(items);
      total.value = data.total || aes.value.length;
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "AE 加载失败");
  } finally {
    loading.value = false;
  }
};

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

const loadSubjects = async () => {
  if (!study.currentStudy) return;
  try {
    const { data } = await fetchSubjects(study.currentStudy.id, { skip: 0, limit: 500 });
    subjects.value = data.items || data || [];
  } catch {
    // ignore
  }
};

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

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

const siteName = (id?: string) => {
  if (!id) return "-";
  return siteMap.value[id] || id;
};

const statusLabel = (v: string) =>
  ({
    FOLLOW_UP: "随访中",
    CLOSED: "结束",
    NEW: "随访中",
  }[v] || v);

const seriousnessLabel = (v: string) => getDictLabel(aeSeriousnessDict, v) || v;
const severityLabel = (v: string) => getDictLabel(aeSeverityDict, v) || v;


onMounted(async () => {
  if (!auth.user && auth.token) {
    await auth.fetchMe().catch(() => {});
  }
  await Promise.all([loadSubjects(), loadSites()]);
  loadAes();
});
</script>

<style scoped>
</style>
