<template>
  <div class="page">
    <el-card class="mb-12">
      <div class="filters">
        <el-select v-model="filters.status" placeholder="状态" clearable @change="loadQueries">
          <el-option v-for="s in statuses" :key="s" :label="s" :value="s" />
        </el-select>
        <el-switch v-model="filters.overdue" active-text="仅逾期" @change="loadQueries" />
        <el-input v-model="filters.assigned_to" placeholder="指派人ID" style="width: 180px" @change="loadQueries" />
        <div class="spacer" />
        <el-button type="primary" v-if="canEdit" @click="showForm = true">新建 Query</el-button>
      </div>
    </el-card>

    <el-card>
      <el-table :data="queries" v-loading="loading" style="width: 100%" @row-click="goDetail">
        <el-table-column prop="title" label="标题" />
        <el-table-column label="受试者">
          <template #default="scope">
            {{ subjectMap[scope.row.subject_id] || scope.row.subject_id || "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="category" label="类别" width="140" />
        <el-table-column prop="priority" label="优先级" width="120" />
        <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>

    <DataQueryForm v-model="showForm" :subjects="subjects" @success="loadQueries" />
  </div>
</template>

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

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

const queries = 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 = ["OPEN", "IN_PROGRESS", "ANSWERED", "CLOSED"];

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

const showForm = ref(false);

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

const loadQueries = 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.assigned_to) params.assigned_to = filters.value.assigned_to;
    if (filters.value.overdue) params.overdue = true;
    const { data } = await fetchDataQueries(study.currentStudy.id, params);
    const markOverdue = (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)) {
      queries.value = markOverdue(data);
      total.value = data.length;
    } else {
      const list = data.items || [];
      queries.value = markOverdue(list);
      total.value = data.total || queries.value.length;
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "数据问题加载失败");
  } finally {
    loading.value = false;
  }
};

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

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

onMounted(async () => {
  if (!auth.user && auth.token) {
    await auth.fetchMe().catch(() => {});
  }
  if (study.currentStudy) {
    const { data } = await fetchSubjects(study.currentStudy.id, { skip: 0, limit: 500 });
    subjects.value = data.items || data || [];
  }
  loadQueries();
});
</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>
