<template>
  <el-dialog :model-value="modelValue" :title="isEdit ? '编辑咨询' : '新建咨询'" width="640px" @close="close">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="分类" prop="category_id">
        <el-select v-model="form.category_id" placeholder="请选择分类">
          <el-option v-for="c in categories" :key="c.id" :label="c.name" :value="c.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="问题" prop="question">
        <el-input v-model="form.question" />
      </el-form-item>
      <el-form-item label="启用">
        <el-switch v-model="form.is_active" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取消</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 { ElMessage, FormInstance, FormRules } from "element-plus";
import { createFaqItem, updateFaqItem } from "../api/faqs";
import { useStudyStore } from "../store/study";

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

const study = useStudyStore();
const formRef = ref<FormInstance>();
const submitting = ref(false);

const form = reactive({
  study_id: "",
  category_id: "",
  question: "",
  is_active: true,
});

const rules: FormRules = {
  category_id: [{ required: true, message: "请选择分类", trigger: "change" }],
  question: [{ required: true, message: "请输入问题", trigger: "blur" }],
};

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

const reset = () => {
  form.study_id = study.currentStudy?.id || "";
  form.category_id = "";
  form.question = "";
  form.is_active = true;
};

watch(
  () => props.item,
  (val) => {
    if (val) {
      form.study_id = val.study_id || "";
      form.category_id = val.category_id;
      form.question = val.question;
      form.is_active = val.is_active;
    } else {
      reset();
    }
  },
  { immediate: true }
);

const close = () => emit("update:modelValue", false);

const onSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate();
  submitting.value = true;
  try {
    const payload: Record<string, any> = {
      study_id: study.currentStudy?.id || null,
      category_id: form.category_id,
      question: form.question,
      is_active: form.is_active,
    };
    if (isEdit.value && props.item) {
      await updateFaqItem(props.item.id, payload);
    } else {
      await createFaqItem(payload);
    }
    ElMessage.success("保存成功");
    emit("success");
    close();
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "保存失败");
  } finally {
    submitting.value = false;
  }
};
</script>
