<template>
  <el-form
    ref="seoFormRef"
    :model="seoForm"
    :rules="seoRules"
    label-width="120px"
    style="max-width: 600px"
  >
    <el-form-item label="SEO标题" prop="seoTitle">
      <el-input v-model="seoForm.seoTitle" placeholder="请输入SEO标题" />
    </el-form-item>
    <el-form-item label="SEO关键词" prop="seoKeywords">
      <el-input
        v-model="seoForm.seoKeywords"
        placeholder="多个关键词用逗号分隔"
      />
    </el-form-item>
    <el-form-item label="SEO描述" prop="seoDescription">
      <el-input
        v-model="seoForm.seoDescription"
        type="textarea"
        :rows="3"
        placeholder="请输入SEO描述"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="saveSeoSettings">保存设置</el-button>
      <el-button @click="resetSeoForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElLoading } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { getCompanySeo, saveCompanySeo } from "@/api/sitesettings";

const seoFormRef = ref<FormInstance>();

const seoForm = reactive({
  seoTitle: "",
  seoKeywords: "",
  seoDescription: "",
});

const seoRules: FormRules = {
  seoTitle: [{ required: true, message: "请输入SEO标题", trigger: "blur" }],
};

const fetchSeoData = async () => {
  try {
    const res = await getCompanySeo();
    if (res.code === 200) {
      Object.assign(seoForm, res.data);
    }
  } catch (error) {
    ElMessage.error("获取SEO数据失败");
  }
};

const saveSeoSettings = async () => {
  if (!seoFormRef.value) return;

  await seoFormRef.value.validate(async (valid) => {
    if (valid) {
      const loading = ElLoading.service({ text: "正在保存..." });
      try {
        const res = await saveCompanySeo({
          seoTitle: seoForm.seoTitle,
          seoKeywords: seoForm.seoKeywords,
          seoDescription: seoForm.seoDescription,
        });

        if (res.code === 200) {
          ElMessage.success("SEO设置保存成功");
        } else {
          ElMessage.error(res.msg);
        }
      } catch (error) {
        ElMessage.error("网络请求失败");
      } finally {
        loading.close();
      }
    }
  });
};

const resetSeoForm = () => {
  if (!seoFormRef.value) return;
  seoFormRef.value.resetFields();
};

onMounted(() => {
  fetchSeoData();
});

defineExpose({
  seoForm,
});
</script>
