<template>
  <div class="page">
    <el-card class="mb-12">
      <div class="filters">
        <el-select v-model="filters.status" placeholder="状态" clearable @change="loadIssues">
          <el-option v-for="s in statuses" :key="s" :label="s" :value="s" />
        </el-select>
        <el-select v-model="filters.level" placeholder="等级" clearable @change="loadIssues">
          <el-option v-for="l in levels" :key="l" :label="l" :value="l" />
        </el-select>
        <el-select v-model="filters.category" placeholder="类别" clearable @change="loadIssues">
          <el-option v-for="c in categories" :key="c" :label="c" :value="c" />
        </el-select>
        <el-switch v-model="filters.overdue" active-text="仅逾期" @change="loadIssues" />
        <div class="spacer" />
        <el-button type="primary" v-if="canCreate" @click="showForm = true">新建 Issue</el-button>
      </div>
    </el-card>

    <el-card>
      <el-table :data="issues" v-loading="loading" style="width: 100%" @row-click="goDetail">
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="level" label="等级" width="120" />
        <el-table-column prop="category" label="类别" width="140" />
        <el-table-column prop="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'">{{ scope.row.status }}</el-tag>
          </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>

    <IssueForm v-model="showForm" @success="loadIssues" />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { fetchIssues } from "../api/issues";
import { useStudyStore } from "../store/study";
import { useAuthStore } from "../store/auth";
import IssueForm from "../components/IssueForm.vue";

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

const issues = ref<any[]>([]);
const loading = ref(false);
const total = ref(0);
const page = ref(1);
const pageSize = 10;

const statuses = ["OPEN", "MITIGATING", "CLOSED"];
const levels = ["LOW", "MEDIUM", "HIGH", "CRITICAL"];
const categories = ["RISK", "ISSUE", "PROTOCOL_DEVIATION"];

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

const showForm = ref(false);

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

const loadIssues = 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.level) params.level = filters.value.level;
    if (filters.value.category) params.category = filters.value.category;
    if (filters.value.overdue) params.overdue = true;
    const { data } = await fetchIssues(study.currentStudy.id, params);
    const mapOverdue = (list: any[]) =>
      list.map((item) => ({
        ...item,
        is_overdue:
          item.is_overdue ?? (item.due_date && item.status !== "CLOSED" && new Date() > new Date(item.due_date)),
      }));
    if (Array.isArray(data)) {
      issues.value = mapOverdue(data);
      total.value = data.length;
    } else {
      const list = data.items || [];
      issues.value = mapOverdue(list);
      total.value = data.total || issues.value.length;
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "Issue 加载失败");
  } finally {
    loading.value = false;
  }
};

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

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

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