<template>
  <el-form
    ref="legalNoticeFormRef"
    :model="formData"
    label-width="120px"
    style="max-width: 600px"
  >
    <el-form-item label="法律声明" prop="legalNotice">
      <el-input
        v-model="legalNotice"
        type="textarea"
        :rows="8"
        placeholder="请输入法律声明"
      />
    </el-form-item>
    <el-form-item label="隐私条款" prop="privacyTerms">
      <el-input
        v-model="privacyTerms"
        type="textarea"
        :rows="8"
        placeholder="请输入隐私条款"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleSaveLegalInfos">保存设置</el-button>
      <el-button @click="resetLegalNoticeForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

import { getLegalInfos, saveLegalInfos } from "@/api/sitesettings";
import { useAuthStore } from "@/stores/auth";

const authStore = useAuthStore();
const legalNoticeFormRef = ref<FormInstance>();

const legalNotice = ref("");
const privacyTerms = ref("");

const seoForm = reactive({
  legalNotice: "",
  privacyTerms: "",
});

const formData = {
  legalNotice,
  privacyTerms,
};

//调用法律声明和隐私条款数据
const initLegalInfos = async () => {
  const res = await getLegalInfos();
  if (res.code === 200 && res.data) {
    const data = res.data;
    const dataMap: Record<string, string> = {};
    data.forEach((item: any) => {
      dataMap[item.label] = item.value;
    });
    legalNotice.value = dataMap["legalNotice"] || "";
    privacyTerms.value = dataMap["privacyTerms"] || "";
  }
};

const handleSaveLegalInfos = async () => {
  if (!legalNoticeFormRef.value) return;
  await legalNoticeFormRef.value.validate(async (valid) => {
    if (valid) {
      const data = {
        tid: authStore.user.tid,
        legalNotice: legalNotice.value,
        privacyTerms: privacyTerms.value
      };
      const res = await saveLegalInfos(data);
      if (res.code === 200) {
        ElMessage.success("保存成功");
      } else {
        ElMessage.error(res.msg || "保存失败");
      }
    }
  });
};

const resetLegalNoticeForm = () => {
  legalNotice.value = "";
  privacyTerms.value = "";
};

defineExpose({
  legalNotice,
  privacyTerms,
});

// 初始化法律声明和隐私条款数据
onMounted(() => {
  initLegalInfos();
});
</script>
