<template>
  <el-dialog :title="isEdit ? '编辑问题' : '新增问题'" v-model="visible" width="600px" @close="onClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" />
      </el-form-item>
      <el-form-item label="类别" prop="category">
        <el-select v-model="form.category" placeholder="请选择">
          <el-option v-for="c in categories" :key="c" :label="c" :value="c" />
        </el-select>
      </el-form-item>
      <el-form-item label="等级" prop="level">
        <el-select v-model="form.level" placeholder="请选择">
          <el-option v-for="l in levels" :key="l" :label="l" :value="l" />
        </el-select>
      </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>
      <el-button @click="onClose">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="onSubmit">提交</el-button>
    </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 { createIssue, updateIssue } from "../api/issues";
import { useStudyStore } from "../store/study";

interface Props {
  modelValue: boolean;
  issue?: Record<string, any>;
}

const props = defineProps<Props>();
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 categories = ["RISK", "ISSUE", "PROTOCOL_DEVIATION"];
const levels = ["LOW", "MEDIUM", "HIGH", "CRITICAL"];

const form = reactive({
  title: "",
  category: "ISSUE",
  level: "MEDIUM",
  due_date: "",
  description: "",
});

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

const isEdit = computed(() => !!props.issue);

watch(
  () => props.issue,
  (val) => {
    if (val) {
      Object.assign(form, {
        title: val.title || "",
        category: val.category || "ISSUE",
        level: val.level || "MEDIUM",
        due_date: val.due_date || "",
        description: val.description || "",
      });
    } else {
      Object.assign(form, {
        title: "",
        category: "ISSUE",
        level: "MEDIUM",
        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 = { ...form };
      if (isEdit.value && props.issue) {
        await updateIssue(study.currentStudy.id, props.issue.id, payload);
      } else {
        await createIssue(study.currentStudy.id, payload);
      }
      ElMessage.success("提交成功");
      emit("success");
      onClose();
    } catch (e: any) {
      ElMessage.error(e?.response?.data?.message || "提交失败");
    } finally {
      submitting.value = false;
    }
  });
};
</script>
