<script setup lang="ts">
import { reactive, ref } from "vue";
import { addFaq, modifyFaq, getFaqDetail } from "@/api/faq";
import { ElMessage } from "element-plus";

const emit = defineEmits(["refresh"]);

const formRef = ref();
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");
const loading = ref(false);

const state = reactive({
  ruleForm: {
    id: null as number | null,
    question: "",
    answer: "",
    status: 1
  },
  rules: {
    question: [{ required: true, message: "请输入问题", trigger: "blur" }],
    answer: [{ required: true, message: "请输入答案", trigger: "blur" }]
  }
});

const resetForm = () => {
  state.ruleForm = {
    id: null,
    question: "",
    answer: "",
    status: 1
  };
  formRef.value?.resetFields();
};

const getTitle = () => {
  return dialogType.value === "add" ? "新增常见问题" : "编辑常见问题";
};

const open = async (type: "add" | "edit", row?: any) => {
  dialogType.value = type;
  resetForm();
  if (type === "edit" && row) {
    loading.value = true;
    try {
      const res = await getFaqDetail(row.id);
      Object.assign(state.ruleForm, res);
    } catch (e) {
      ElMessage.error("获取详情失败");
    } finally {
      loading.value = false;
    }
  }
  dialogVisible.value = true;
};

const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};

const handleSubmit = async () => {
  const valid = await formRef.value?.validate().catch(() => false);
  if (!valid) return;

  loading.value = true;
  try {
    if (dialogType.value === "add") {
      await addFaq(state.ruleForm);
    } else {
      await modifyFaq(state.ruleForm);
    }
    ElMessage.success("操作成功");
    handleClose();
    emit("refresh");
  } catch (e) {
    ElMessage.error("操作失败");
  } finally {
    loading.value = false;
  }
};

defineExpose({ open });
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="getTitle()"
    width="820px"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" :model="state.ruleForm" :rules="state.rules" label-width="100px" :disabled="loading">
      <el-form-item label="问题" prop="question">
        <el-input v-model="state.ruleForm.question" placeholder="请输入问题" clearable />
      </el-form-item>
      <el-form-item label="答案" prop="answer">
        <el-input
          v-model="state.ruleForm.answer"
          placeholder="请输入答案"
          type="textarea"
          :rows="6"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button :loading="loading" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>
