<template>
  <div class="page">
    <el-card class="mb-12">
      <div class="filters">
        <el-select v-model="filters.level" placeholder="核查层级" clearable @change="load">
          <el-option label="SDV 核查" value="SDV" />
          <el-option label="SDR 核查" value="SDR" />
        </el-select>
        <SiteSelect
          v-model="filters.site_id"
          :study-id="study.currentStudy?.id || null"
          placeholder="中心"
          style="width: 220px"
          @change="load"
        />
        <div class="spacer" />
        <el-button v-if="canEdit" type="primary" @click="openCreate">新增核查进度</el-button>
      </div>
    </el-card>

    <VerificationTable :verifications="verifications" :can-edit="canEdit" :loading="loading" @edit="openEdit" />

    <el-dialog :title="editForm.id ? '更新核查进度' : '新增核查进度'" v-model="showEdit" width="520px">
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="受试者">
          <SubjectSelect
            v-model="editForm.subject_id"
            :study-id="study.currentStudy?.id || null"
            :disabled="!!editForm.id"
          />
        </el-form-item>
        <el-form-item label="中心">
          <SiteSelect v-model="editForm.site_id" :study-id="study.currentStudy?.id || null" />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="editForm.level" placeholder="请选择">
            <el-option label="SDV 核查" value="SDV" />
            <el-option label="SDR 核查" value="SDR" />
          </el-select>
        </el-form-item>
        <el-form-item label="完成度">
          <el-input-number v-model="editForm.percent" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="核查日期">
          <el-date-picker v-model="editForm.last_verified_at" type="date" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editForm.notes" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEdit = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submitEdit">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import { fetchVerifications, upsertVerification } from "../api/verifications";
import { useStudyStore } from "../store/study";
import { useAuthStore } from "../store/auth";
import VerificationTable from "../components/VerificationTable.vue";
import SiteSelect from "../components/selectors/SiteSelect.vue";
import SubjectSelect from "../components/selectors/SubjectSelect.vue";

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

const verifications = ref<any[]>([]);
const loading = ref(false);
const submitting = ref(false);
const showEdit = ref(false);
const editForm = ref<any>({});

const filters = ref({
  level: "",
  site_id: "",
});

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

const load = async () => {
  if (!study.currentStudy) return;
  loading.value = true;
  try {
    const params: Record<string, any> = {};
    if (filters.value.level) params.level = filters.value.level;
    if (filters.value.site_id) params.site_id = filters.value.site_id;
    const { data } = await fetchVerifications(study.currentStudy.id, params);
    verifications.value = data.items || data || [];
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "核查进度加载失败");
  } finally {
    loading.value = false;
  }
};

const openEdit = (row: any) => {
  if (!canEdit.value) return;
  editForm.value = { ...row };
  showEdit.value = true;
};

const openCreate = () => {
  if (!canEdit.value) return;
  editForm.value = { subject_id: "", site_id: "", level: filters.value.level || "SDV", percent: 0, notes: "" };
  showEdit.value = true;
};

const submitEdit = async () => {
  if (!study.currentStudy) return;
  if (!editForm.value.subject_id) {
    ElMessage.warning("请输入受试者ID");
    return;
  }
  if (!editForm.value.level) {
    ElMessage.warning("请选择类型");
    return;
  }
  submitting.value = true;
  try {
    await upsertVerification(study.currentStudy.id, {
      subject_id: editForm.value.subject_id,
      site_id: editForm.value.site_id || null,
      level: editForm.value.level,
      percent: editForm.value.percent,
      last_verified_at: editForm.value.last_verified_at,
      verifier_id: editForm.value.verifier_id,
      notes: editForm.value.notes,
    });
    ElMessage.success("更新成功");
    showEdit.value = false;
    load();
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "更新失败");
  } finally {
    submitting.value = false;
  }
};

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

<style scoped>
.page {
  padding: 16px;
}
.filters {
  display: flex;
  gap: 8px;
  align-items: center;
}
.spacer {
  flex: 1;
}
.mb-12 {
  margin-bottom: 12px;
}
</style>
