<template>
  <div class="page" v-if="issue">
    <el-card class="mb-12">
      <div class="header">
        <div>
          <h3>风险与问题</h3>
          <p>{{ issue.title }}</p>
        </div>
        <PermissionAction action="issue.close">
          <el-button type="danger" size="small" @click="closeIssue">关闭</el-button>
        </PermissionAction>
      </div>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="类别">{{ issue.category }}</el-descriptions-item>
        <el-descriptions-item label="等级">{{ issue.level }}</el-descriptions-item>
        <el-descriptions-item label="截止日期">{{ issue.due_date }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ statusLabel(issue.status) }}</el-descriptions-item>
        <el-descriptions-item label="描述">{{ issue.description }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-tabs>
      <el-tab-pane label="评论">
        <CommentList :study-id="studyId" entity-type="issues" :entity-id="issue.id" :can-comment="true" />
      </el-tab-pane>
      <el-tab-pane label="附件">
        <AttachmentList
          :study-id="studyId"
          entity-type="issues"
          :entity-id="issue.id"
          :show-uploader="true"
        />
      </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 { fetchIssues, updateIssue } from "../api/issues";
import { useStudyStore } from "../store/study";
import { useAuthStore } from "../store/auth";
import PermissionAction from "../components/PermissionAction.vue";
import { usePermission } from "../utils/permission";
import CommentList from "../components/CommentList.vue";
import AttachmentList from "../components/attachments/AttachmentList.vue";

const route = useRoute();
const study = useStudyStore();
const auth = useAuthStore();
const issue = ref<any | null>(null);
const studyId = computed(() => study.currentStudy?.id || "");
const { can } = usePermission();
const canEdit = computed(() => can("issue.close"));

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

const closeIssue = async () => {
  await ElMessageBox.confirm("确定要关闭该风险/问题吗？该操作不可撤销，请谨慎确认。", "提示");
  if (!study.currentStudy || !issue.value) return;
  try {
    await updateIssue(study.currentStudy.id, issue.value.id, { status: "CLOSED" });
    ElMessage.success("已关闭");
    load();
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "更新失败");
  }
};

const statusLabel = (v: string) =>
  ({
    OPEN: "开放",
    MITIGATING: "处理中",
    CLOSED: "已关闭",
  }[v] || v);

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>
