<template>
  <div class="page">
    <el-card class="mb-12">
      <div class="filters">
        <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>
        <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>
        <el-switch v-model="filters.overdue" active-text="仅逾期" @change="loadAes" />
        <div class="spacer" />
        <el-button type="primary" v-if="canCreate" @click="showForm = true">新建不良事件</el-button>
      </div>
    </el-card>

    <el-card>
      <el-table :data="aes" v-loading="loading" 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 prop="seriousness" label="严重性" width="140">
          <template #default="scope">
            {{ seriousnessLabel(scope.row.seriousness) }}
          </template>
        </el-table-column>
        <el-table-column prop="onset_date" label="发生日期" width="140" />
        <el-table-column prop="report_due_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-column label="操作" width="140">
          <template #default="scope">
            <el-button
              v-if="showClose(scope.row)"
              type="danger"
              size="small"
              @click.stop="onClose(scope.row)"
            >
              关闭 AE
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="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, ElMessageBox } from "element-plus";
import { fetchAes, updateAe } from "../api/aes";
import { fetchSubjects } from "../api/subjects";
import { useStudyStore } from "../store/study";
import { useAuthStore } from "../store/auth";
import AeForm from "../components/AeForm.vue";
import { aeMachine, getAvailableActions } from "../state-machine";
import { evaluateAction } from "../guards/actionGuard";
import { logAudit } from "../audit";

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 subjectMap = computed(() =>
  subjects.value.reduce<Record<string, string>>((acc, cur) => {
    acc[cur.id] = cur.subject_no || cur.id;
    return acc;
  }, {})
);

const statuses = ["NEW", "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 = 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 goDetail = (row: any) => {
  router.push(`/study/aes/${row.id}`);
};

const statusLabel = (v: string) =>
  ({
    NEW: "新增",
    FOLLOW_UP: "随访中",
    CLOSED: "已关闭",
  }[v] || v);

const seriousnessLabel = (v: string) =>
  ({
    SERIOUS: "严重",
    NON_SERIOUS: "非严重",
  }[v] || v);

const showClose = (row: any) => {
  const actions = getAvailableActions(aeMachine, row.status);
  const has = actions.some((a) => a.key === "close");
  if (!has) return false;
  const decision = evaluateAction({
    actorRole: auth.user?.role || null,
    requiredPermission: "ae.close",
    stateMachine: aeMachine,
    currentState: row.status,
    actionKey: "close",
  });
  return decision.allowed;
};

const onClose = async (row: any) => {
  if (!study.currentStudy) return;
  const action = getAvailableActions(aeMachine, row.status).find((a) => a.key === "close");
  const decision = evaluateAction({
    actorRole: auth.user?.role || null,
    requiredPermission: "ae.close",
    stateMachine: aeMachine,
    currentState: row.status,
    actionKey: "close",
  });
  if (!decision.allowed) {
    ElMessage.warning(decision.reason || "当前不可执行该操作");
    logAudit(decision.auditType, {
      targetId: row.id,
      targetName: row.term,
      reason: decision.reason,
      severity: decision.severity,
    });
    return;
  }
  if (action?.confirm) {
    const ok = await ElMessageBox.confirm(action.confirmText || "确认关闭？", "提示", {
      type: action.danger ? "warning" : "info",
    }).catch(() => null);
    if (!ok) return;
  }
  try {
    await updateAe(study.currentStudy.id, row.id, { status: action?.to || "CLOSED" });
    ElMessage.success("已关闭");
    logAudit("AE_CLOSED", {
      targetId: row.id,
      targetName: row.term,
      before: { status: row.status },
      after: { status: action?.to || "CLOSED" },
      severity: "normal",
    });
    loadAes();
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "操作失败");
    logAudit("AE_CLOSED", {
      targetId: row.id,
      targetName: row.term,
      before: { status: row.status },
      after: { status: action?.to || "CLOSED" },
      severity: "warning",
      reason: e?.response?.data?.message,
    });
  }
};

onMounted(async () => {
  if (!auth.user && auth.token) {
    await auth.fetchMe().catch(() => {});
  }
  await loadSubjects();
  loadAes();
});
</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>
