<template>
  <el-dialog :title="isEdit ? '编辑 AE' : '新增 AE'" 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="subject_id">
        <SubjectSelect v-model="form.subject_id" :study-id="study.currentStudy?.id || null" placeholder="可留空" />
      </el-form-item>
      <el-form-item label="事件描述" prop="term">
        <el-input v-model="form.term" />
      </el-form-item>
      <el-form-item label="发生日期" prop="onset_date">
        <el-date-picker
          v-model="form.onset_date"
          type="date"
          value-format="YYYY-MM-DD"
          :disabled-date="disableFutureDate"
        />
      </el-form-item>
      <el-form-item label="SAE" prop="seriousness">
        <el-select v-model="form.seriousness" placeholder="请选择">
          <el-option label="是" value="SERIOUS" />
          <el-option label="否" value="NON_SERIOUS" />
        </el-select>
      </el-form-item>
      <el-form-item label="严重程度" prop="severity">
        <el-select v-model="form.severity" placeholder="请选择">
          <el-option v-for="s in severities" :key="s" :label="severityLabel(s)" :value="s" />
        </el-select>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="form.description" type="textarea" />
      </el-form-item>
      <el-form-item label="转归结局" prop="outcome">
        <el-select v-model="form.outcome" placeholder="可留空" clearable>
          <el-option v-for="o in outcomes" :key="o" :label="o" :value="o" />
        </el-select>
      </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 { createAe, updateAe } from "../api/aes";
import { useStudyStore } from "../store/study";
import SubjectSelect from "./selectors/SubjectSelect.vue";

const props = defineProps<{
  modelValue: boolean;
  ae?: Record<string, any>;
  subjects?: 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 severities = ["G1", "G2", "G3", "G4", "G5"];
const outcomes = ["痊愈", "好转", "持续", "恶化", "死亡", "其他"];
const severityLabel = (v: string) =>
  ({
    G1: "I级",
    G2: "II级",
    G3: "III级",
    G4: "IV级",
    G5: "V级",
  }[v] || v);

const form = reactive({
  subject_id: "",
  term: "",
  onset_date: "",
  seriousness: "NON_SERIOUS",
  severity: "G1",
  description: "",
  outcome: "",
});

const rules: FormRules = {
  term: [{ required: true, message: "请输入事件描述", trigger: "blur" }],
  onset_date: [{ required: true, message: "请选择发生日期", trigger: "change" }],
  seriousness: [{ required: true, message: "请选择严重性", trigger: "change" }],
  severity: [{ required: true, message: "请选择严重程度", trigger: "change" }],
};

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

watch(
  () => props.ae,
  (val) => {
    if (val) {
      Object.assign(form, {
        subject_id: val.subject_id || "",
        term: val.term || "",
        onset_date: val.onset_date || "",
        seriousness: val.seriousness || "NON_SERIOUS",
        severity: val.severity || "G1",
        description: val.description || "",
        outcome: val.outcome || "",
      });
    } else {
      Object.assign(form, {
        subject_id: "",
        term: "",
        onset_date: "",
        seriousness: "NON_SERIOUS",
        severity: "G1",
        description: "",
        outcome: "",
      });
    }
  },
  { immediate: true }
);

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

const disableFutureDate = (time: Date) => time.getTime() > Date.now();

const onSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    if (form.onset_date && new Date(form.onset_date) > new Date()) {
      ElMessage.warning("发生日期不得晚于当前日期");
      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 (form.outcome === "" || form.outcome === null || form.outcome === undefined) {
        payload.outcome = null;
      }
      if (isEdit.value && props.ae) {
        await updateAe(study.currentStudy.id, props.ae.id, payload);
      } else {
        await createAe(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>
