<template>
  <el-dialog :title="isEdit ? '编辑数据问题' : '新建数据问题'" v-model="visible" width="600px" @close="onClose" class="ctms-dialog">
    <el-form ref="formRef" :model="form" :rules="rules" label-position="top" class="ctms-form--dense form-body">
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" />
      </el-form-item>
      <el-form-item label="受试者" prop="subject_id">
        <SubjectSelect v-model="form.subject_id" :study-id="study.currentStudy?.id || null" placeholder="可选" />
      </el-form-item>
      <el-form-item label="类别" prop="category">
        <el-select v-model="form.category" placeholder="请选择">
          <el-option label="缺失(MISSING)" value="MISSING" />
          <el-option label="不一致(INCONSISTENT)" value="INCONSISTENT" />
          <el-option label="超范围(OUT_OF_RANGE)" value="OUT_OF_RANGE" />
          <el-option label="其他(OTHER)" value="OTHER" />
        </el-select>
      </el-form-item>
      <el-form-item label="优先级" prop="priority">
        <el-select v-model="form.priority" placeholder="请选择">
          <el-option label="低" value="LOW" />
          <el-option label="中" value="MEDIUM" />
          <el-option label="高" value="HIGH" />
        </el-select>
      </el-form-item>
      <el-form-item label="指派给" prop="assigned_to">
        <UserSelect v-model="form.assigned_to" placeholder="可选" />
      </el-form-item>
      <el-form-item label="截止日期" prop="due_date">
        <el-date-picker v-model="form.due_date" type="date" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="form.description" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="footer-right">
        <el-button @click="onClose">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="onSubmit">提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { createDataQuery, updateDataQuery } from "../api/dataQueries";
import { useStudyStore } from "../store/study";
import SubjectSelect from "./selectors/SubjectSelect.vue";
import UserSelect from "./selectors/UserSelect.vue";

const props = defineProps<{
  modelValue: boolean;
  query?: Record<string, any>;
}>();
const emit = defineEmits(["update:modelValue", "success"]);

const visible = computed({
  get: () => props.modelValue,
  set: (v: boolean) => emit("update:modelValue", v),
});

const formRef = ref<FormInstance>();
const submitting = ref(false);
const study = useStudyStore();
const isEdit = computed(() => !!props.query);

const form = reactive({
  title: "",
  subject_id: "",
  category: "MISSING",
  priority: "MEDIUM",
  assigned_to: "",
  due_date: "",
  description: "",
});

const rules: FormRules = {
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  category: [{ required: true, message: "请选择类别", trigger: "change" }],
  priority: [{ required: true, message: "请选择优先级", trigger: "change" }],
};

watch(
  () => props.query,
  (val) => {
    if (val) {
      Object.assign(form, {
        title: val.title || "",
        subject_id: val.subject_id || "",
        category: val.category || "MISSING",
        priority: val.priority || "MEDIUM",
        assigned_to: val.assigned_to || "",
        due_date: val.due_date || "",
        description: val.description || "",
      });
    } else {
      Object.assign(form, {
        title: "",
        subject_id: "",
        category: "MISSING",
        priority: "MEDIUM",
        assigned_to: "",
        due_date: "",
        description: "",
      });
    }
  },
  { immediate: true }
);

const onClose = () => {
  visible.value = false;
};

const onSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    if (!study.currentStudy) {
      ElMessage.error("未选择项目");
      return;
    }
    submitting.value = true;
    try {
      const payload: Record<string, any> = {};
      Object.entries(form).forEach(([k, v]) => {
        if (v !== "" && v !== null && v !== undefined) payload[k] = v;
      });
      if (isEdit.value && props.query) {
        await updateDataQuery(study.currentStudy.id, props.query.id, payload);
      } else {
        await createDataQuery(study.currentStudy.id, payload);
      }
      ElMessage.success("提交成功");
      emit("success");
      onClose();
    } catch (e: any) {
      ElMessage.error(e?.response?.data?.message || "提交失败");
    } finally {
      submitting.value = false;
    }
  });
};
</script>

<style scoped>
.form-body {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

:deep(.el-dialog__body) {
  padding-top: 12px;
}

:deep(.el-dialog__footer) {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
