<template>
  <div class="platform-settings">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="settings-form"
    >
      <el-card shadow="never" class="settings-card">
        <el-form-item label="开启验证">
          <el-switch v-model="formData.openVerify_enabled" />
        </el-form-item>
        <el-form-item label="登录验证方式" prop="use_geetest">
          <el-radio-group v-model="formData.use_geetest">
            <el-radio label="captcha">验证码</el-radio>
            <el-radio label="sms">短信</el-radio>
            <el-radio label="geetest">极验</el-radio>
            <el-radio label="email">邮箱</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="formData.openVerify_enabled && formData.use_geetest === 'geetest'">
          <el-form-item label="geetest3ID" prop="geetest3_id">
            <el-input
              v-model="formData.geetest3_id"
              placeholder="请输入 geetest3ID"
            />
          </el-form-item>
          <el-form-item label="geetest3KEY" prop="geetest3_key">
            <el-input
              v-model="formData.geetest3_key"
              placeholder="请输入 geetest3KEY"
            />
          </el-form-item>
          <el-form-item label="geetest4ID" prop="geetest4_id">
            <el-input
              v-model="formData.geetest4_id"
              placeholder="请输入 geetest4ID"
            />
          </el-form-item>
          <el-form-item label="geetest4KEY" prop="geetest4_key">
            <el-input
              v-model="formData.geetest4_key"
              placeholder="请输入 geetest4KEY"
            />
          </el-form-item>
        </template>
      </el-card>
    </el-form>

    <div class="footer-actions">
      <el-button @click="handleReset">重置</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSubmit"
        >保存设置</el-button
      >
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { getVerifyInfos, saveVerifyInfos } from "@/api/sitesettings";

const STORAGE_KEY = "platform_settings_draft";

const formRef = ref();
const submitting = ref(false);

const formData = reactive({
  openVerify_enabled: true,
  use_geetest: "captcha",
  geetest3_id: "",
  geetest3_key: "",
  geetest4_id: "",
  geetest4_key: "",
});

const validateGeetestField = (_rule, value, callback) => {
  if (formData.openVerify_enabled && formData.use_geetest === "geetest" && !String(value || "").trim()) {
    callback(new Error("已启用极验时该参数不能为空"));
    return;
  }
  callback();
};

const rules = {
  geetest3_id: [{ validator: validateGeetestField, trigger: "blur" }],
  geetest3_key: [{ validator: validateGeetestField, trigger: "blur" }],
  geetest4_id: [{ validator: validateGeetestField, trigger: "blur" }],
  geetest4_key: [{ validator: validateGeetestField, trigger: "blur" }],
};

const loadDraft = () => {
  const raw = localStorage.getItem(STORAGE_KEY);
  if (!raw) return;
  try {
    const data = JSON.parse(raw);
    Object.assign(formData, data);
  } catch {
    // ignore invalid cache
  }
};

const loadRemoteVerifyInfos = async () => {
  try {
    const res = await getVerifyInfos();
    if (res?.code === 200 && res?.data) {
      Object.assign(formData, {
        openVerify_enabled: Number(res.data.openVerify_enabled ?? 1) === 1,
        use_geetest: res.data.use_geetest || "captcha",
        geetest3_id: res.data.geetest3_id || "",
        geetest3_key: res.data.geetest3_key || "",
        geetest4_id: res.data.geetest4_id || "",
        geetest4_key: res.data.geetest4_key || "",
      });
    }
  } catch {
    // ignore remote errors
  }
};

const saveDraft = () => {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(formData));
};

const handleReset = () => {
  Object.assign(formData, {
    openVerify_enabled: true,
    use_geetest: "captcha",
    geetest3_id: "",
    geetest3_key: "",
    geetest4_id: "",
    geetest4_key: "",
  });
  saveDraft();
  ElMessage.success("已重置");
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate();
  submitting.value = true;
  try {
    await saveVerifyInfos({
      openVerify_enabled: formData.openVerify_enabled ? 1 : 0,
      use_geetest: formData.use_geetest,
      geetest3_id: formData.geetest3_id,
      geetest3_key: formData.geetest3_key,
      geetest4_id: formData.geetest4_id,
      geetest4_key: formData.geetest4_key,
    });
    saveDraft();
    ElMessage.success("保存成功");
  } finally {
    submitting.value = false;
  }
};

onMounted(() => {
  loadDraft();
  loadRemoteVerifyInfos();
});
</script>

<style scoped>
.platform-settings {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.settings-card {
  margin-bottom: 12px;
}

.footer-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
