<template>
  <div class="page" v-if="ae">
    <el-card class="mb-12">
      <div class="header">
        <div>
          <h3>AE 详情</h3>
          <p>{{ ae.term }}</p>
        </div>
        <el-button v-if="canClose" :type="ae.status === 'CLOSED' ? 'primary' : 'danger'" size="small" @click="toggleClose">
          {{ ae.status === "CLOSED" ? "重新打开" : "关闭" }}
        </el-button>
      </div>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="受试者ID">{{ ae.subject_id }}</el-descriptions-item>
        <el-descriptions-item label="严重性">{{ ae.seriousness }}</el-descriptions-item>
        <el-descriptions-item label="严重程度">{{ ae.severity }}</el-descriptions-item>
        <el-descriptions-item label="发生日期">{{ ae.onset_date }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ ae.status }}</el-descriptions-item>
        <el-descriptions-item label="描述">{{ ae.description }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-tabs>
      <el-tab-pane label="评论">
        <CommentList :study-id="studyId" entity-type="aes" :entity-id="ae.id" :can-comment="true" />
      </el-tab-pane>
      <el-tab-pane label="附件">
        <AttachmentList :study-id="studyId" entity-type="aes" :entity-id="ae.id" :can-upload="canClose" />
      </el-tab-pane>
    </el-tabs>
  </div>
  <div v-else class="page">
    <el-skeleton rows="4" animated />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { fetchAes, updateAe } from "../api/aes";
import { useStudyStore } from "../store/study";
import { useAuthStore } from "../store/auth";
import CommentList from "../components/CommentList.vue";
import AttachmentList from "../components/AttachmentList.vue";

const route = useRoute();
const study = useStudyStore();
const auth = useAuthStore();

const ae = ref<any | null>(null);
const studyId = computed(() => study.currentStudy?.id || "");

const canClose = computed(() => {
  // CRA 也显示按钮，后端会校验权限
  return true;
});

const enrichOverdue = (item: any) => {
  if (!item) return item;
  return {
    ...item,
    is_overdue:
      item.is_overdue ??
      (item.report_due_date && item.status !== "CLOSED" && new Date() > new Date(item.report_due_date)),
  };
};

const load = async () => {
  if (!study.currentStudy) return;
  try {
    const { data } = await fetchAes(study.currentStudy.id, { skip: 0, limit: 500 });
    const list = data.items || data || [];
    ae.value = enrichOverdue(list.find((item: any) => item.id === route.params.aeId));
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "AE 加载失败");
  }
};

const toggleClose = async () => {
  if (!study.currentStudy || !ae.value) return;
  const targetStatus = ae.value.status === "CLOSED" ? "FOLLOW_UP" : "CLOSED";
  await ElMessageBox.confirm(
    `确认将该 AE 状态设置为 ${targetStatus === "CLOSED" ? "CLOSED" : "FOLLOW_UP"}？`,
    "提示"
  );
  try {
    const resp = await updateAe(study.currentStudy.id, ae.value.id, { status: targetStatus });
    ElMessage.success("状态已更新");
    ae.value = enrichOverdue(resp.data);
    await load();
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "更新失败");
  }
};

onMounted(async () => {
  if (!auth.user && auth.token) {
    await auth.fetchMe().catch(() => {});
  }
  load();
});
</script>

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